blob: bb7042d1954d18cf4a688772a1a86a405f2eee77 [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 Smith9ec71972012-02-05 01:23:16 +00001563/// \param Type - The type we expect this conversion to produce, before
1564/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smith180f4792011-11-10 06:34:14 +00001565/// \param LVal - The glvalue on which we are attempting to perform this action.
1566/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001567static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1568 QualType Type,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001569 const LValue &LVal, CCValue &RVal) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001570 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1571 if (!Info.getLangOpts().CPlusPlus)
1572 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1573
Richard Smithb4e85ed2012-01-06 16:39:00 +00001574 if (LVal.Designator.Invalid)
1575 // A diagnostic will have already been produced.
1576 return false;
1577
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001578 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001579 CallStackFrame *Frame = LVal.Frame;
Richard Smith7098cbd2011-12-21 05:04:46 +00001580 SourceLocation Loc = Conv->getExprLoc();
Richard Smithc49bd112011-10-28 17:51:58 +00001581
Richard Smithf48fdb02011-12-09 22:58:01 +00001582 if (!LVal.Base) {
1583 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith7098cbd2011-12-21 05:04:46 +00001584 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1585 return false;
1586 }
1587
1588 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1589 // is not a constant expression (even if the object is non-volatile). We also
1590 // apply this rule to C++98, in order to conform to the expected 'volatile'
1591 // semantics.
1592 if (Type.isVolatileQualified()) {
1593 if (Info.getLangOpts().CPlusPlus)
1594 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1595 else
1596 Info.Diag(Loc);
Richard Smithc49bd112011-10-28 17:51:58 +00001597 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001598 }
Richard Smithc49bd112011-10-28 17:51:58 +00001599
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001600 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001601 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1602 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001603 // expressions are constant expressions too. Inside constexpr functions,
1604 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001605 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001606 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf15fda02012-02-02 01:16:57 +00001607 if (const VarDecl *VDef = VD->getDefinition())
1608 VD = VDef;
Richard Smithf48fdb02011-12-09 22:58:01 +00001609 if (!VD || VD->isInvalidDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001610 Info.Diag(Loc);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001611 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001612 }
1613
Richard Smith7098cbd2011-12-21 05:04:46 +00001614 // DR1313: If the object is volatile-qualified but the glvalue was not,
1615 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001616 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001617 if (VT.isVolatileQualified()) {
1618 if (Info.getLangOpts().CPlusPlus) {
1619 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1620 Info.Note(VD->getLocation(), diag::note_declared_at);
1621 } else {
1622 Info.Diag(Loc);
Richard Smithf48fdb02011-12-09 22:58:01 +00001623 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001624 return false;
1625 }
1626
1627 if (!isa<ParmVarDecl>(VD)) {
1628 if (VD->isConstexpr()) {
1629 // OK, we can read this variable.
1630 } else if (VT->isIntegralOrEnumerationType()) {
1631 if (!VT.isConstQualified()) {
1632 if (Info.getLangOpts().CPlusPlus) {
1633 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1634 Info.Note(VD->getLocation(), diag::note_declared_at);
1635 } else {
1636 Info.Diag(Loc);
1637 }
1638 return false;
1639 }
1640 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1641 // We support folding of const floating-point types, in order to make
1642 // static const data members of such types (supported as an extension)
1643 // more useful.
1644 if (Info.getLangOpts().CPlusPlus0x) {
1645 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1646 Info.Note(VD->getLocation(), diag::note_declared_at);
1647 } else {
1648 Info.CCEDiag(Loc);
1649 }
1650 } else {
1651 // FIXME: Allow folding of values of any literal type in all languages.
1652 if (Info.getLangOpts().CPlusPlus0x) {
1653 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1654 Info.Note(VD->getLocation(), diag::note_declared_at);
1655 } else {
1656 Info.Diag(Loc);
1657 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001658 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001659 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001660 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001661
Richard Smithf48fdb02011-12-09 22:58:01 +00001662 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001663 return false;
1664
Richard Smith47a1eed2011-10-29 20:57:55 +00001665 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001666 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001667
1668 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1669 // conversion. This happens when the declaration and the lvalue should be
1670 // considered synonymous, for instance when initializing an array of char
1671 // from a string literal. Continue as if the initializer lvalue was the
1672 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001673 assert(RVal.getLValueOffset().isZero() &&
1674 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001675 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001676 Frame = RVal.getLValueFrame();
Richard Smithc49bd112011-10-28 17:51:58 +00001677 }
1678
Richard Smith7098cbd2011-12-21 05:04:46 +00001679 // Volatile temporary objects cannot be read in constant expressions.
1680 if (Base->getType().isVolatileQualified()) {
1681 if (Info.getLangOpts().CPlusPlus) {
1682 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1683 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1684 } else {
1685 Info.Diag(Loc);
1686 }
1687 return false;
1688 }
1689
Richard Smith0a3bdb62011-11-04 02:25:55 +00001690 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1691 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1692 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf48fdb02011-12-09 22:58:01 +00001693 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001694 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001695 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001696 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001697
1698 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith9a17a682011-11-07 05:07:52 +00001699 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smith7098cbd2011-12-21 05:04:46 +00001700 const ConstantArrayType *CAT =
1701 Info.Ctx.getAsConstantArrayType(S->getType());
1702 if (Index >= CAT->getSize().getZExtValue()) {
1703 // Note, it should not be possible to form a pointer which points more
1704 // than one past the end of the array without producing a prior const expr
1705 // diagnostic.
1706 Info.Diag(Loc, diag::note_constexpr_read_past_end);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001707 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001708 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001709 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1710 Type->isUnsignedIntegerType());
1711 if (Index < S->getLength())
1712 Value = S->getCodeUnit(Index);
1713 RVal = CCValue(Value);
1714 return true;
1715 }
1716
Richard Smithcc5d4f62011-11-07 09:22:26 +00001717 if (Frame) {
1718 // If this is a temporary expression with a nontrivial initializer, grab the
1719 // value from the relevant stack frame.
1720 RVal = Frame->Temporaries[Base];
1721 } else if (const CompoundLiteralExpr *CLE
1722 = dyn_cast<CompoundLiteralExpr>(Base)) {
1723 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1724 // initializer until now for such expressions. Such an expression can't be
1725 // an ICE in C, so this only matters for fold.
1726 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1727 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1728 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001729 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001730 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001731 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001732 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001733
Richard Smithf48fdb02011-12-09 22:58:01 +00001734 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1735 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001736}
1737
Richard Smith59efe262011-11-11 04:05:33 +00001738/// Build an lvalue for the object argument of a member function call.
1739static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1740 LValue &This) {
1741 if (Object->getType()->isPointerType())
1742 return EvaluatePointer(Object, This, Info);
1743
1744 if (Object->isGLValue())
1745 return EvaluateLValue(Object, This, Info);
1746
Richard Smithe24f5fc2011-11-17 22:56:20 +00001747 if (Object->getType()->isLiteralType())
1748 return EvaluateTemporary(Object, This, Info);
1749
1750 return false;
1751}
1752
1753/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1754/// lvalue referring to the result.
1755///
1756/// \param Info - Information about the ongoing evaluation.
1757/// \param BO - The member pointer access operation.
1758/// \param LV - Filled in with a reference to the resulting object.
1759/// \param IncludeMember - Specifies whether the member itself is included in
1760/// the resulting LValue subobject designator. This is not possible when
1761/// creating a bound member function.
1762/// \return The field or method declaration to which the member pointer refers,
1763/// or 0 if evaluation fails.
1764static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1765 const BinaryOperator *BO,
1766 LValue &LV,
1767 bool IncludeMember = true) {
1768 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1769
Richard Smith745f5142012-01-27 01:14:48 +00001770 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1771 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001772 return 0;
1773
1774 MemberPtr MemPtr;
1775 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1776 return 0;
1777
1778 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1779 // member value, the behavior is undefined.
1780 if (!MemPtr.getDecl())
1781 return 0;
1782
Richard Smith745f5142012-01-27 01:14:48 +00001783 if (!EvalObjOK)
1784 return 0;
1785
Richard Smithe24f5fc2011-11-17 22:56:20 +00001786 if (MemPtr.isDerivedMember()) {
1787 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001788 // The end of the derived-to-base path for the base object must match the
1789 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001790 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001791 LV.Designator.Entries.size())
1792 return 0;
1793 unsigned PathLengthToMember =
1794 LV.Designator.Entries.size() - MemPtr.Path.size();
1795 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1796 const CXXRecordDecl *LVDecl = getAsBaseClass(
1797 LV.Designator.Entries[PathLengthToMember + I]);
1798 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1799 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1800 return 0;
1801 }
1802
1803 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001804 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1805 PathLengthToMember))
1806 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001807 } else if (!MemPtr.Path.empty()) {
1808 // Extend the LValue path with the member pointer's path.
1809 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1810 MemPtr.Path.size() + IncludeMember);
1811
1812 // Walk down to the appropriate base class.
1813 QualType LVType = BO->getLHS()->getType();
1814 if (const PointerType *PT = LVType->getAs<PointerType>())
1815 LVType = PT->getPointeeType();
1816 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1817 assert(RD && "member pointer access on non-class-type expression");
1818 // The first class in the path is that of the lvalue.
1819 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1820 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smithb4e85ed2012-01-06 16:39:00 +00001821 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001822 RD = Base;
1823 }
1824 // Finally cast to the class containing the member.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001825 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smithe24f5fc2011-11-17 22:56:20 +00001826 }
1827
1828 // Add the member. Note that we cannot build bound member functions here.
1829 if (IncludeMember) {
Richard Smithd9b02e72012-01-25 22:15:11 +00001830 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
1831 HandleLValueMember(Info, BO, LV, FD);
1832 else if (const IndirectFieldDecl *IFD =
1833 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
1834 HandleLValueIndirectMember(Info, BO, LV, IFD);
1835 else
1836 llvm_unreachable("can't construct reference to bound member function");
Richard Smithe24f5fc2011-11-17 22:56:20 +00001837 }
1838
1839 return MemPtr.getDecl();
1840}
1841
1842/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1843/// the provided lvalue, which currently refers to the base object.
1844static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1845 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001846 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001847 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001848 return false;
1849
Richard Smithb4e85ed2012-01-06 16:39:00 +00001850 QualType TargetQT = E->getType();
1851 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1852 TargetQT = PT->getPointeeType();
1853
1854 // Check this cast lands within the final derived-to-base subobject path.
1855 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
1856 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1857 << D.MostDerivedType << TargetQT;
1858 return false;
1859 }
1860
Richard Smithe24f5fc2011-11-17 22:56:20 +00001861 // Check the type of the final cast. We don't need to check the path,
1862 // since a cast can only be formed if the path is unique.
1863 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001864 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1865 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001866 if (NewEntriesSize == D.MostDerivedPathLength)
1867 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
1868 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00001869 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001870 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
1871 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1872 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001873 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001874 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001875
1876 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001877 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00001878}
1879
Mike Stumpc4c90452009-10-27 22:09:17 +00001880namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00001881enum EvalStmtResult {
1882 /// Evaluation failed.
1883 ESR_Failed,
1884 /// Hit a 'return' statement.
1885 ESR_Returned,
1886 /// Evaluation succeeded.
1887 ESR_Succeeded
1888};
1889}
1890
1891// Evaluate a statement.
Richard Smithc1c5f272011-12-13 06:39:58 +00001892static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00001893 const Stmt *S) {
1894 switch (S->getStmtClass()) {
1895 default:
1896 return ESR_Failed;
1897
1898 case Stmt::NullStmtClass:
1899 case Stmt::DeclStmtClass:
1900 return ESR_Succeeded;
1901
Richard Smithc1c5f272011-12-13 06:39:58 +00001902 case Stmt::ReturnStmtClass: {
1903 CCValue CCResult;
1904 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1905 if (!Evaluate(CCResult, Info, RetExpr) ||
1906 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1907 CCEK_ReturnValue))
1908 return ESR_Failed;
1909 return ESR_Returned;
1910 }
Richard Smithd0dccea2011-10-28 22:34:42 +00001911
1912 case Stmt::CompoundStmtClass: {
1913 const CompoundStmt *CS = cast<CompoundStmt>(S);
1914 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1915 BE = CS->body_end(); BI != BE; ++BI) {
1916 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1917 if (ESR != ESR_Succeeded)
1918 return ESR;
1919 }
1920 return ESR_Succeeded;
1921 }
1922 }
1923}
1924
Richard Smith61802452011-12-22 02:22:31 +00001925/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
1926/// default constructor. If so, we'll fold it whether or not it's marked as
1927/// constexpr. If it is marked as constexpr, we will never implicitly define it,
1928/// so we need special handling.
1929static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00001930 const CXXConstructorDecl *CD,
1931 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00001932 if (!CD->isTrivial() || !CD->isDefaultConstructor())
1933 return false;
1934
Richard Smith4c3fc9b2012-01-18 05:21:49 +00001935 // Value-initialization does not call a trivial default constructor, so such a
1936 // call is a core constant expression whether or not the constructor is
1937 // constexpr.
1938 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00001939 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00001940 // FIXME: If DiagDecl is an implicitly-declared special member function,
1941 // we should be much more explicit about why it's not constexpr.
1942 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
1943 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
1944 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00001945 } else {
1946 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
1947 }
1948 }
1949 return true;
1950}
1951
Richard Smithc1c5f272011-12-13 06:39:58 +00001952/// CheckConstexprFunction - Check that a function can be called in a constant
1953/// expression.
1954static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1955 const FunctionDecl *Declaration,
1956 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00001957 // Potential constant expressions can contain calls to declared, but not yet
1958 // defined, constexpr functions.
1959 if (Info.CheckingPotentialConstantExpression && !Definition &&
1960 Declaration->isConstexpr())
1961 return false;
1962
Richard Smithc1c5f272011-12-13 06:39:58 +00001963 // Can we evaluate this function call?
1964 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1965 return true;
1966
1967 if (Info.getLangOpts().CPlusPlus0x) {
1968 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00001969 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1970 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00001971 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1972 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1973 << DiagDecl;
1974 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1975 } else {
1976 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1977 }
1978 return false;
1979}
1980
Richard Smith180f4792011-11-10 06:34:14 +00001981namespace {
Richard Smithcd99b072011-11-11 05:48:57 +00001982typedef SmallVector<CCValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00001983}
1984
1985/// EvaluateArgs - Evaluate the arguments to a function call.
1986static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1987 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00001988 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00001989 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00001990 I != E; ++I) {
1991 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
1992 // If we're checking for a potential constant expression, evaluate all
1993 // initializers even if some of them fail.
1994 if (!Info.keepEvaluatingAfterFailure())
1995 return false;
1996 Success = false;
1997 }
1998 }
1999 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002000}
2001
Richard Smithd0dccea2011-10-28 22:34:42 +00002002/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002003static bool HandleFunctionCall(SourceLocation CallLoc,
2004 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002005 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smithc1c5f272011-12-13 06:39:58 +00002006 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002007 ArgVector ArgValues(Args.size());
2008 if (!EvaluateArgs(Args, ArgValues, Info))
2009 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00002010
Richard Smith745f5142012-01-27 01:14:48 +00002011 if (!Info.CheckCallLimit(CallLoc))
2012 return false;
2013
2014 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002015 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2016}
2017
Richard Smith180f4792011-11-10 06:34:14 +00002018/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002019static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002020 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002021 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002022 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002023 ArgVector ArgValues(Args.size());
2024 if (!EvaluateArgs(Args, ArgValues, Info))
2025 return false;
2026
Richard Smith745f5142012-01-27 01:14:48 +00002027 if (!Info.CheckCallLimit(CallLoc))
2028 return false;
2029
2030 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002031
2032 // If it's a delegating constructor, just delegate.
2033 if (Definition->isDelegatingConstructor()) {
2034 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
2035 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
2036 }
2037
Richard Smith610a60c2012-01-10 04:32:03 +00002038 // For a trivial copy or move constructor, perform an APValue copy. This is
2039 // essential for unions, where the operations performed by the constructor
2040 // cannot be represented by ctor-initializers.
Richard Smith180f4792011-11-10 06:34:14 +00002041 const CXXRecordDecl *RD = Definition->getParent();
Richard Smith610a60c2012-01-10 04:32:03 +00002042 if (Definition->isDefaulted() &&
2043 ((Definition->isCopyConstructor() && RD->hasTrivialCopyConstructor()) ||
2044 (Definition->isMoveConstructor() && RD->hasTrivialMoveConstructor()))) {
2045 LValue RHS;
2046 RHS.setFrom(ArgValues[0]);
2047 CCValue Value;
Richard Smith745f5142012-01-27 01:14:48 +00002048 if (!HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2049 RHS, Value))
2050 return false;
2051 assert((Value.isStruct() || Value.isUnion()) &&
2052 "trivial copy/move from non-class type?");
2053 // Any CCValue of class type must already be a constant expression.
2054 Result = Value;
2055 return true;
Richard Smith610a60c2012-01-10 04:32:03 +00002056 }
2057
2058 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002059 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002060 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2061 std::distance(RD->field_begin(), RD->field_end()));
2062
2063 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2064
Richard Smith745f5142012-01-27 01:14:48 +00002065 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002066 unsigned BasesSeen = 0;
2067#ifndef NDEBUG
2068 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2069#endif
2070 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2071 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002072 LValue Subobject = This;
2073 APValue *Value = &Result;
2074
2075 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002076 if ((*I)->isBaseInitializer()) {
2077 QualType BaseType((*I)->getBaseClass(), 0);
2078#ifndef NDEBUG
2079 // Non-virtual base classes are initialized in the order in the class
2080 // definition. We cannot have a virtual base class for a literal type.
2081 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2082 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2083 "base class initializers not in expected order");
2084 ++BaseIt;
2085#endif
Richard Smithb4e85ed2012-01-06 16:39:00 +00002086 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smith180f4792011-11-10 06:34:14 +00002087 BaseType->getAsCXXRecordDecl(), &Layout);
Richard Smith745f5142012-01-27 01:14:48 +00002088 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002089 } else if (FieldDecl *FD = (*I)->getMember()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002090 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00002091 if (RD->isUnion()) {
2092 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002093 Value = &Result.getUnionValue();
2094 } else {
2095 Value = &Result.getStructField(FD->getFieldIndex());
2096 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002097 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002098 // Walk the indirect field decl's chain to find the object to initialize,
2099 // and make sure we've initialized every step along it.
2100 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2101 CE = IFD->chain_end();
2102 C != CE; ++C) {
2103 FieldDecl *FD = cast<FieldDecl>(*C);
2104 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2105 // Switch the union field if it differs. This happens if we had
2106 // preceding zero-initialization, and we're now initializing a union
2107 // subobject other than the first.
2108 // FIXME: In this case, the values of the other subobjects are
2109 // specified, since zero-initialization sets all padding bits to zero.
2110 if (Value->isUninit() ||
2111 (Value->isUnion() && Value->getUnionField() != FD)) {
2112 if (CD->isUnion())
2113 *Value = APValue(FD);
2114 else
2115 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2116 std::distance(CD->field_begin(), CD->field_end()));
2117 }
Richard Smith745f5142012-01-27 01:14:48 +00002118 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
Richard Smithd9b02e72012-01-25 22:15:11 +00002119 if (CD->isUnion())
2120 Value = &Value->getUnionValue();
2121 else
2122 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002123 }
Richard Smith180f4792011-11-10 06:34:14 +00002124 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002125 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002126 }
Richard Smith745f5142012-01-27 01:14:48 +00002127
2128 if (!EvaluateConstantExpression(*Value, Info, Subobject, (*I)->getInit(),
2129 (*I)->isBaseInitializer()
2130 ? CCEK_Constant : CCEK_MemberInit)) {
2131 // If we're checking for a potential constant expression, evaluate all
2132 // initializers even if some of them fail.
2133 if (!Info.keepEvaluatingAfterFailure())
2134 return false;
2135 Success = false;
2136 }
Richard Smith180f4792011-11-10 06:34:14 +00002137 }
2138
Richard Smith745f5142012-01-27 01:14:48 +00002139 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002140}
2141
Richard Smithd0dccea2011-10-28 22:34:42 +00002142namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002143class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002144 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002145 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002146public:
2147
Richard Smith1e12c592011-10-16 21:26:27 +00002148 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002149
2150 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002151 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002152 return true;
2153 }
2154
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002155 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2156 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002157 return Visit(E->getResultExpr());
2158 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002159 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002160 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002161 return true;
2162 return false;
2163 }
John McCallf85e1932011-06-15 23:02:42 +00002164 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002165 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002166 return true;
2167 return false;
2168 }
2169 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002170 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002171 return true;
2172 return false;
2173 }
2174
Mike Stumpc4c90452009-10-27 22:09:17 +00002175 // We don't want to evaluate BlockExprs multiple times, as they generate
2176 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002177 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2178 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2179 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002180 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002181 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2182 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2183 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2184 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2185 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2186 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002187 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002188 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002189 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002190 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002191 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002192 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2193 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2194 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2195 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002196 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002197 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2198 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2199 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2200 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2201 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002202 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002203 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002204 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002205 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002206 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002207
2208 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002209 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002210 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2211 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002212 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002213 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002214 return false;
2215 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002216
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002217 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002218};
2219
John McCall56ca35d2011-02-17 10:25:35 +00002220class OpaqueValueEvaluation {
2221 EvalInfo &info;
2222 OpaqueValueExpr *opaqueValue;
2223
2224public:
2225 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2226 Expr *value)
2227 : info(info), opaqueValue(opaqueValue) {
2228
2229 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002230 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002231 this->opaqueValue = 0;
2232 return;
2233 }
John McCall56ca35d2011-02-17 10:25:35 +00002234 }
2235
2236 bool hasError() const { return opaqueValue == 0; }
2237
2238 ~OpaqueValueEvaluation() {
Richard Smith1e12c592011-10-16 21:26:27 +00002239 // FIXME: This will not work for recursive constexpr functions using opaque
2240 // values. Restore the former value.
John McCall56ca35d2011-02-17 10:25:35 +00002241 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2242 }
2243};
2244
Mike Stumpc4c90452009-10-27 22:09:17 +00002245} // end anonymous namespace
2246
Eli Friedman4efaa272008-11-12 09:44:48 +00002247//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002248// Generic Evaluation
2249//===----------------------------------------------------------------------===//
2250namespace {
2251
Richard Smithf48fdb02011-12-09 22:58:01 +00002252// FIXME: RetTy is always bool. Remove it.
2253template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002254class ExprEvaluatorBase
2255 : public ConstStmtVisitor<Derived, RetTy> {
2256private:
Richard Smith47a1eed2011-10-29 20:57:55 +00002257 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002258 return static_cast<Derived*>(this)->Success(V, E);
2259 }
Richard Smith51201882011-12-30 21:15:51 +00002260 RetTy DerivedZeroInitialization(const Expr *E) {
2261 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002262 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002263
2264protected:
2265 EvalInfo &Info;
2266 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2267 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2268
Richard Smithdd1f29b2011-12-12 09:28:41 +00002269 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd5093422011-12-12 09:41:58 +00002270 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002271 }
2272
2273 /// Report an evaluation error. This should only be called when an error is
2274 /// first discovered. When propagating an error, just return false.
2275 bool Error(const Expr *E, diag::kind D) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00002276 Info.Diag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002277 return false;
2278 }
2279 bool Error(const Expr *E) {
2280 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2281 }
2282
Richard Smith51201882011-12-30 21:15:51 +00002283 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00002284
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002285public:
2286 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2287
2288 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002289 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002290 }
2291 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002292 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002293 }
2294
2295 RetTy VisitParenExpr(const ParenExpr *E)
2296 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2297 RetTy VisitUnaryExtension(const UnaryOperator *E)
2298 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2299 RetTy VisitUnaryPlus(const UnaryOperator *E)
2300 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2301 RetTy VisitChooseExpr(const ChooseExpr *E)
2302 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2303 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2304 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002305 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2306 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002307 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2308 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002309 // We cannot create any objects for which cleanups are required, so there is
2310 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2311 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2312 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002313
Richard Smithc216a012011-12-12 12:46:16 +00002314 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2315 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2316 return static_cast<Derived*>(this)->VisitCastExpr(E);
2317 }
2318 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2319 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2320 return static_cast<Derived*>(this)->VisitCastExpr(E);
2321 }
2322
Richard Smithe24f5fc2011-11-17 22:56:20 +00002323 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2324 switch (E->getOpcode()) {
2325 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002326 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002327
2328 case BO_Comma:
2329 VisitIgnoredValue(E->getLHS());
2330 return StmtVisitorTy::Visit(E->getRHS());
2331
2332 case BO_PtrMemD:
2333 case BO_PtrMemI: {
2334 LValue Obj;
2335 if (!HandleMemberPointerAccess(Info, E, Obj))
2336 return false;
2337 CCValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002338 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002339 return false;
2340 return DerivedSuccess(Result, E);
2341 }
2342 }
2343 }
2344
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002345 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2346 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2347 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002348 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002349
2350 bool cond;
Richard Smithc49bd112011-10-28 17:51:58 +00002351 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002352 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002353
2354 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
2355 }
2356
2357 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002358 bool IsBcpCall = false;
2359 // If the condition (ignoring parens) is a __builtin_constant_p call,
2360 // the result is a constant expression if it can be folded without
2361 // side-effects. This is an important GNU extension. See GCC PR38377
2362 // for discussion.
2363 if (const CallExpr *CallCE =
2364 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2365 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2366 IsBcpCall = true;
2367
2368 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2369 // constant expression; we can't check whether it's potentially foldable.
2370 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2371 return false;
2372
2373 FoldConstant Fold(Info);
2374
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002375 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00002376 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002377 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002378
Richard Smithc49bd112011-10-28 17:51:58 +00002379 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Richard Smithf15fda02012-02-02 01:16:57 +00002380 if (!StmtVisitorTy::Visit(EvalExpr))
2381 return false;
2382
2383 if (IsBcpCall)
2384 Fold.Fold(Info);
2385
2386 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002387 }
2388
2389 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002390 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002391 if (!Value) {
2392 const Expr *Source = E->getSourceExpr();
2393 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002394 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002395 if (Source == E) { // sanity checking.
2396 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002397 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002398 }
2399 return StmtVisitorTy::Visit(Source);
2400 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002401 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002402 }
Richard Smithf10d9172011-10-11 21:43:33 +00002403
Richard Smithd0dccea2011-10-28 22:34:42 +00002404 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002405 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002406 QualType CalleeType = Callee->getType();
2407
Richard Smithd0dccea2011-10-28 22:34:42 +00002408 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002409 LValue *This = 0, ThisVal;
2410 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith6c957872011-11-10 09:31:24 +00002411
Richard Smith59efe262011-11-11 04:05:33 +00002412 // Extract function decl and 'this' pointer from the callee.
2413 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002414 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002415 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2416 // Explicit bound member calls, such as x.f() or p->g();
2417 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002418 return false;
2419 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002420 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002421 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2422 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002423 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2424 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002425 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002426 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002427 return Error(Callee);
2428
2429 FD = dyn_cast<FunctionDecl>(Member);
2430 if (!FD)
2431 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002432 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002433 LValue Call;
2434 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002435 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002436
Richard Smithb4e85ed2012-01-06 16:39:00 +00002437 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002438 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002439 FD = dyn_cast_or_null<FunctionDecl>(
2440 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002441 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002442 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002443
2444 // Overloaded operator calls to member functions are represented as normal
2445 // calls with '*this' as the first argument.
2446 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2447 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002448 // FIXME: When selecting an implicit conversion for an overloaded
2449 // operator delete, we sometimes try to evaluate calls to conversion
2450 // operators without a 'this' parameter!
2451 if (Args.empty())
2452 return Error(E);
2453
Richard Smith59efe262011-11-11 04:05:33 +00002454 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2455 return false;
2456 This = &ThisVal;
2457 Args = Args.slice(1);
2458 }
2459
2460 // Don't call function pointers which have been cast to some other type.
2461 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002462 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002463 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002464 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002465
Richard Smithb04035a2012-02-01 02:39:43 +00002466 if (This && !This->checkSubobject(Info, E, CSK_This))
2467 return false;
2468
Richard Smithc1c5f272011-12-13 06:39:58 +00002469 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002470 Stmt *Body = FD->getBody(Definition);
Richard Smith69c2c502011-11-04 05:33:44 +00002471 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002472
Richard Smithc1c5f272011-12-13 06:39:58 +00002473 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002474 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2475 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002476 return false;
2477
Richard Smithb4e85ed2012-01-06 16:39:00 +00002478 return DerivedSuccess(CCValue(Info.Ctx, Result, CCValue::GlobalValue()), E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002479 }
2480
Richard Smithc49bd112011-10-28 17:51:58 +00002481 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2482 return StmtVisitorTy::Visit(E->getInitializer());
2483 }
Richard Smithf10d9172011-10-11 21:43:33 +00002484 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002485 if (E->getNumInits() == 0)
2486 return DerivedZeroInitialization(E);
2487 if (E->getNumInits() == 1)
2488 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002489 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002490 }
2491 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002492 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002493 }
2494 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002495 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002496 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002497 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002498 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002499 }
Richard Smithf10d9172011-10-11 21:43:33 +00002500
Richard Smith180f4792011-11-10 06:34:14 +00002501 /// A member expression where the object is a prvalue is itself a prvalue.
2502 RetTy VisitMemberExpr(const MemberExpr *E) {
2503 assert(!E->isArrow() && "missing call to bound member function?");
2504
2505 CCValue Val;
2506 if (!Evaluate(Val, Info, E->getBase()))
2507 return false;
2508
2509 QualType BaseTy = E->getBase()->getType();
2510
2511 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002512 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002513 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2514 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2515 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2516
Richard Smithb4e85ed2012-01-06 16:39:00 +00002517 SubobjectDesignator Designator(BaseTy);
2518 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002519
Richard Smithf48fdb02011-12-09 22:58:01 +00002520 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002521 DerivedSuccess(Val, E);
2522 }
2523
Richard Smithc49bd112011-10-28 17:51:58 +00002524 RetTy VisitCastExpr(const CastExpr *E) {
2525 switch (E->getCastKind()) {
2526 default:
2527 break;
2528
David Chisnall7a7ee302012-01-16 17:27:18 +00002529 case CK_AtomicToNonAtomic:
2530 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002531 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002532 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002533 return StmtVisitorTy::Visit(E->getSubExpr());
2534
2535 case CK_LValueToRValue: {
2536 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002537 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2538 return false;
2539 CCValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00002540 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2541 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2542 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002543 return false;
2544 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002545 }
2546 }
2547
Richard Smithf48fdb02011-12-09 22:58:01 +00002548 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002549 }
2550
Richard Smith8327fad2011-10-24 18:44:57 +00002551 /// Visit a value which is evaluated, but whose value is ignored.
2552 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002553 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002554 if (!Evaluate(Scratch, Info, E))
2555 Info.EvalStatus.HasSideEffects = true;
2556 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002557};
2558
2559}
2560
2561//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002562// Common base class for lvalue and temporary evaluation.
2563//===----------------------------------------------------------------------===//
2564namespace {
2565template<class Derived>
2566class LValueExprEvaluatorBase
2567 : public ExprEvaluatorBase<Derived, bool> {
2568protected:
2569 LValue &Result;
2570 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2571 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2572
2573 bool Success(APValue::LValueBase B) {
2574 Result.set(B);
2575 return true;
2576 }
2577
2578public:
2579 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2580 ExprEvaluatorBaseTy(Info), Result(Result) {}
2581
2582 bool Success(const CCValue &V, const Expr *E) {
2583 Result.setFrom(V);
2584 return true;
2585 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002586
Richard Smithe24f5fc2011-11-17 22:56:20 +00002587 bool VisitMemberExpr(const MemberExpr *E) {
2588 // Handle non-static data members.
2589 QualType BaseTy;
2590 if (E->isArrow()) {
2591 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2592 return false;
2593 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002594 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002595 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002596 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2597 return false;
2598 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002599 } else {
2600 if (!this->Visit(E->getBase()))
2601 return false;
2602 BaseTy = E->getBase()->getType();
2603 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002604
Richard Smithd9b02e72012-01-25 22:15:11 +00002605 const ValueDecl *MD = E->getMemberDecl();
2606 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2607 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2608 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2609 (void)BaseTy;
2610 HandleLValueMember(this->Info, E, Result, FD);
2611 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2612 HandleLValueIndirectMember(this->Info, E, Result, IFD);
2613 } else
2614 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002615
Richard Smithd9b02e72012-01-25 22:15:11 +00002616 if (MD->getType()->isReferenceType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002617 CCValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002618 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002619 RefValue))
2620 return false;
2621 return Success(RefValue, E);
2622 }
2623 return true;
2624 }
2625
2626 bool VisitBinaryOperator(const BinaryOperator *E) {
2627 switch (E->getOpcode()) {
2628 default:
2629 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2630
2631 case BO_PtrMemD:
2632 case BO_PtrMemI:
2633 return HandleMemberPointerAccess(this->Info, E, Result);
2634 }
2635 }
2636
2637 bool VisitCastExpr(const CastExpr *E) {
2638 switch (E->getCastKind()) {
2639 default:
2640 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2641
2642 case CK_DerivedToBase:
2643 case CK_UncheckedDerivedToBase: {
2644 if (!this->Visit(E->getSubExpr()))
2645 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002646
2647 // Now figure out the necessary offset to add to the base LV to get from
2648 // the derived class to the base class.
2649 QualType Type = E->getSubExpr()->getType();
2650
2651 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2652 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002653 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002654 *PathI))
2655 return false;
2656 Type = (*PathI)->getType();
2657 }
2658
2659 return true;
2660 }
2661 }
2662 }
2663};
2664}
2665
2666//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002667// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002668//
2669// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2670// function designators (in C), decl references to void objects (in C), and
2671// temporaries (if building with -Wno-address-of-temporary).
2672//
2673// LValue evaluation produces values comprising a base expression of one of the
2674// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002675// - Declarations
2676// * VarDecl
2677// * FunctionDecl
2678// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002679// * CompoundLiteralExpr in C
2680// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002681// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002682// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002683// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002684// * ObjCEncodeExpr
2685// * AddrLabelExpr
2686// * BlockExpr
2687// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002688// - Locals and temporaries
2689// * Any Expr, with a Frame indicating the function in which the temporary was
2690// evaluated.
2691// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002692//===----------------------------------------------------------------------===//
2693namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002694class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002695 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002696public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002697 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2698 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002699
Richard Smithc49bd112011-10-28 17:51:58 +00002700 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2701
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002702 bool VisitDeclRefExpr(const DeclRefExpr *E);
2703 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002704 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002705 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2706 bool VisitMemberExpr(const MemberExpr *E);
2707 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2708 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002709 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002710 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2711 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002712
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002713 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002714 switch (E->getCastKind()) {
2715 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002716 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002717
Eli Friedmandb924222011-10-11 00:13:24 +00002718 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002719 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002720 if (!Visit(E->getSubExpr()))
2721 return false;
2722 Result.Designator.setInvalid();
2723 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002724
Richard Smithe24f5fc2011-11-17 22:56:20 +00002725 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002726 if (!Visit(E->getSubExpr()))
2727 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002728 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002729 }
2730 }
Sebastian Redlcea8d962011-09-24 17:48:14 +00002731
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002732 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002733
Eli Friedman4efaa272008-11-12 09:44:48 +00002734};
2735} // end anonymous namespace
2736
Richard Smithc49bd112011-10-28 17:51:58 +00002737/// Evaluate an expression as an lvalue. This can be legitimately called on
2738/// expressions which are not glvalues, in a few cases:
2739/// * function designators in C,
2740/// * "extern void" objects,
2741/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002742static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002743 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2744 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2745 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002746 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002747}
2748
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002749bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002750 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2751 return Success(FD);
2752 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002753 return VisitVarDecl(E, VD);
2754 return Error(E);
2755}
Richard Smith436c8892011-10-24 23:14:33 +00002756
Richard Smithc49bd112011-10-28 17:51:58 +00002757bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002758 if (!VD->getType()->isReferenceType()) {
2759 if (isa<ParmVarDecl>(VD)) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002760 Result.set(VD, Info.CurrentCall);
Richard Smith177dce72011-11-01 16:57:24 +00002761 return true;
2762 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002763 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002764 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002765
Richard Smith47a1eed2011-10-29 20:57:55 +00002766 CCValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002767 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2768 return false;
2769 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002770}
2771
Richard Smithbd552ef2011-10-31 05:52:43 +00002772bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2773 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002774 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002775 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002776 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2777
2778 Result.set(E, Info.CurrentCall);
2779 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2780 Result, E->GetTemporaryExpr());
2781 }
2782
2783 // Materialization of an lvalue temporary occurs when we need to force a copy
2784 // (for instance, if it's a bitfield).
2785 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2786 if (!Visit(E->GetTemporaryExpr()))
2787 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002788 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002789 Info.CurrentCall->Temporaries[E]))
2790 return false;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002791 Result.set(E, Info.CurrentCall);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002792 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002793}
2794
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002795bool
2796LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002797 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2798 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2799 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002800 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002801}
2802
Richard Smith47d21452011-12-27 12:18:28 +00002803bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2804 if (E->isTypeOperand())
2805 return Success(E);
2806 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2807 if (RD && RD->isPolymorphic()) {
2808 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2809 << E->getExprOperand()->getType()
2810 << E->getExprOperand()->getSourceRange();
2811 return false;
2812 }
2813 return Success(E);
2814}
2815
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002816bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002817 // Handle static data members.
2818 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2819 VisitIgnoredValue(E->getBase());
2820 return VisitVarDecl(E, VD);
2821 }
2822
Richard Smithd0dccea2011-10-28 22:34:42 +00002823 // Handle static member functions.
2824 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2825 if (MD->isStatic()) {
2826 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002827 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002828 }
2829 }
2830
Richard Smith180f4792011-11-10 06:34:14 +00002831 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002832 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002833}
2834
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002835bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002836 // FIXME: Deal with vectors as array subscript bases.
2837 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002838 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002839
Anders Carlsson3068d112008-11-16 19:01:22 +00002840 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002841 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002842
Anders Carlsson3068d112008-11-16 19:01:22 +00002843 APSInt Index;
2844 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002845 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002846 int64_t IndexValue
2847 = Index.isSigned() ? Index.getSExtValue()
2848 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00002849
Richard Smithb4e85ed2012-01-06 16:39:00 +00002850 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00002851}
Eli Friedman4efaa272008-11-12 09:44:48 +00002852
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002853bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002854 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00002855}
2856
Eli Friedman4efaa272008-11-12 09:44:48 +00002857//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002858// Pointer Evaluation
2859//===----------------------------------------------------------------------===//
2860
Anders Carlssonc754aa62008-07-08 05:13:58 +00002861namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002862class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002863 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00002864 LValue &Result;
2865
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002866 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002867 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00002868 return true;
2869 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002870public:
Mike Stump1eb44332009-09-09 15:08:12 +00002871
John McCallefdb83e2010-05-07 21:00:08 +00002872 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002873 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002874
Richard Smith47a1eed2011-10-29 20:57:55 +00002875 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002876 Result.setFrom(V);
2877 return true;
2878 }
Richard Smith51201882011-12-30 21:15:51 +00002879 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00002880 return Success((Expr*)0);
2881 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002882
John McCallefdb83e2010-05-07 21:00:08 +00002883 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002884 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00002885 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002886 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00002887 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002888 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00002889 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002890 bool VisitCallExpr(const CallExpr *E);
2891 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00002892 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00002893 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00002894 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00002895 }
Richard Smith180f4792011-11-10 06:34:14 +00002896 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2897 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00002898 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002899 Result = *Info.CurrentCall->This;
2900 return true;
2901 }
John McCall56ca35d2011-02-17 10:25:35 +00002902
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002903 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00002904};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002905} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00002906
John McCallefdb83e2010-05-07 21:00:08 +00002907static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002908 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002909 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002910}
2911
John McCallefdb83e2010-05-07 21:00:08 +00002912bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002913 if (E->getOpcode() != BO_Add &&
2914 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00002915 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002916
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002917 const Expr *PExp = E->getLHS();
2918 const Expr *IExp = E->getRHS();
2919 if (IExp->getType()->isPointerType())
2920 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002921
Richard Smith745f5142012-01-27 01:14:48 +00002922 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
2923 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00002924 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002925
John McCallefdb83e2010-05-07 21:00:08 +00002926 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00002927 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00002928 return false;
2929 int64_t AdditionalOffset
2930 = Offset.isSigned() ? Offset.getSExtValue()
2931 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00002932 if (E->getOpcode() == BO_Sub)
2933 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002934
Richard Smith180f4792011-11-10 06:34:14 +00002935 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00002936 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
2937 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002938}
Eli Friedman4efaa272008-11-12 09:44:48 +00002939
John McCallefdb83e2010-05-07 21:00:08 +00002940bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2941 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002942}
Mike Stump1eb44332009-09-09 15:08:12 +00002943
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002944bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2945 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002946
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002947 switch (E->getCastKind()) {
2948 default:
2949 break;
2950
John McCall2de56d12010-08-25 11:45:40 +00002951 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002952 case CK_CPointerToObjCPointerCast:
2953 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00002954 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00002955 if (!Visit(SubExpr))
2956 return false;
Richard Smithc216a012011-12-12 12:46:16 +00002957 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2958 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2959 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002960 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00002961 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002962 if (SubExpr->getType()->isVoidPointerType())
2963 CCEDiag(E, diag::note_constexpr_invalid_cast)
2964 << 3 << SubExpr->getType();
2965 else
2966 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2967 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002968 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002969
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002970 case CK_DerivedToBase:
2971 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00002972 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002973 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002974 if (!Result.Base && Result.Offset.isZero())
2975 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002976
Richard Smith180f4792011-11-10 06:34:14 +00002977 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002978 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00002979 QualType Type =
2980 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002981
Richard Smith180f4792011-11-10 06:34:14 +00002982 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002983 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002984 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2985 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002986 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002987 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002988 }
2989
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002990 return true;
2991 }
2992
Richard Smithe24f5fc2011-11-17 22:56:20 +00002993 case CK_BaseToDerived:
2994 if (!Visit(E->getSubExpr()))
2995 return false;
2996 if (!Result.Base && Result.Offset.isZero())
2997 return true;
2998 return HandleBaseToDerivedCast(Info, E, Result);
2999
Richard Smith47a1eed2011-10-29 20:57:55 +00003000 case CK_NullToPointer:
Richard Smith51201882011-12-30 21:15:51 +00003001 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00003002
John McCall2de56d12010-08-25 11:45:40 +00003003 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003004 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3005
Richard Smith47a1eed2011-10-29 20:57:55 +00003006 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003007 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003008 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003009
John McCallefdb83e2010-05-07 21:00:08 +00003010 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003011 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3012 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003013 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003014 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith177dce72011-11-01 16:57:24 +00003015 Result.Frame = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003016 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003017 return true;
3018 } else {
3019 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00003020 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00003021 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003022 }
3023 }
John McCall2de56d12010-08-25 11:45:40 +00003024 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003025 if (SubExpr->isGLValue()) {
3026 if (!EvaluateLValue(SubExpr, Result, Info))
3027 return false;
3028 } else {
3029 Result.set(SubExpr, Info.CurrentCall);
3030 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
3031 Info, Result, SubExpr))
3032 return false;
3033 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003034 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003035 if (const ConstantArrayType *CAT
3036 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3037 Result.addArray(Info, E, CAT);
3038 else
3039 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003040 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003041
John McCall2de56d12010-08-25 11:45:40 +00003042 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003043 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003044 }
3045
Richard Smithc49bd112011-10-28 17:51:58 +00003046 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003047}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003048
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003049bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003050 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003051 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003052
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003053 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003054}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003055
3056//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003057// Member Pointer Evaluation
3058//===----------------------------------------------------------------------===//
3059
3060namespace {
3061class MemberPointerExprEvaluator
3062 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3063 MemberPtr &Result;
3064
3065 bool Success(const ValueDecl *D) {
3066 Result = MemberPtr(D);
3067 return true;
3068 }
3069public:
3070
3071 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3072 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3073
3074 bool Success(const CCValue &V, const Expr *E) {
3075 Result.setFrom(V);
3076 return true;
3077 }
Richard Smith51201882011-12-30 21:15:51 +00003078 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003079 return Success((const ValueDecl*)0);
3080 }
3081
3082 bool VisitCastExpr(const CastExpr *E);
3083 bool VisitUnaryAddrOf(const UnaryOperator *E);
3084};
3085} // end anonymous namespace
3086
3087static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3088 EvalInfo &Info) {
3089 assert(E->isRValue() && E->getType()->isMemberPointerType());
3090 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3091}
3092
3093bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3094 switch (E->getCastKind()) {
3095 default:
3096 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3097
3098 case CK_NullToMemberPointer:
Richard Smith51201882011-12-30 21:15:51 +00003099 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003100
3101 case CK_BaseToDerivedMemberPointer: {
3102 if (!Visit(E->getSubExpr()))
3103 return false;
3104 if (E->path_empty())
3105 return true;
3106 // Base-to-derived member pointer casts store the path in derived-to-base
3107 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3108 // the wrong end of the derived->base arc, so stagger the path by one class.
3109 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3110 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3111 PathI != PathE; ++PathI) {
3112 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3113 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3114 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003115 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003116 }
3117 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3118 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003119 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003120 return true;
3121 }
3122
3123 case CK_DerivedToBaseMemberPointer:
3124 if (!Visit(E->getSubExpr()))
3125 return false;
3126 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3127 PathE = E->path_end(); PathI != PathE; ++PathI) {
3128 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3129 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3130 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003131 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003132 }
3133 return true;
3134 }
3135}
3136
3137bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3138 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3139 // member can be formed.
3140 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3141}
3142
3143//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003144// Record Evaluation
3145//===----------------------------------------------------------------------===//
3146
3147namespace {
3148 class RecordExprEvaluator
3149 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3150 const LValue &This;
3151 APValue &Result;
3152 public:
3153
3154 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3155 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3156
3157 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00003158 return CheckConstantExpression(Info, E, V, Result);
Richard Smith180f4792011-11-10 06:34:14 +00003159 }
Richard Smith51201882011-12-30 21:15:51 +00003160 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003161
Richard Smith59efe262011-11-11 04:05:33 +00003162 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003163 bool VisitInitListExpr(const InitListExpr *E);
3164 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3165 };
3166}
3167
Richard Smith51201882011-12-30 21:15:51 +00003168/// Perform zero-initialization on an object of non-union class type.
3169/// C++11 [dcl.init]p5:
3170/// To zero-initialize an object or reference of type T means:
3171/// [...]
3172/// -- if T is a (possibly cv-qualified) non-union class type,
3173/// each non-static data member and each base-class subobject is
3174/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003175static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3176 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003177 const LValue &This, APValue &Result) {
3178 assert(!RD->isUnion() && "Expected non-union class type");
3179 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3180 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3181 std::distance(RD->field_begin(), RD->field_end()));
3182
3183 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3184
3185 if (CD) {
3186 unsigned Index = 0;
3187 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003188 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003189 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3190 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003191 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3192 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003193 Result.getStructBase(Index)))
3194 return false;
3195 }
3196 }
3197
Richard Smithb4e85ed2012-01-06 16:39:00 +00003198 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3199 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003200 // -- if T is a reference type, no initialization is performed.
3201 if ((*I)->getType()->isReferenceType())
3202 continue;
3203
3204 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003205 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smith51201882011-12-30 21:15:51 +00003206
3207 ImplicitValueInitExpr VIE((*I)->getType());
3208 if (!EvaluateConstantExpression(
3209 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3210 return false;
3211 }
3212
3213 return true;
3214}
3215
3216bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3217 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3218 if (RD->isUnion()) {
3219 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3220 // object's first non-static named data member is zero-initialized
3221 RecordDecl::field_iterator I = RD->field_begin();
3222 if (I == RD->field_end()) {
3223 Result = APValue((const FieldDecl*)0);
3224 return true;
3225 }
3226
3227 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003228 HandleLValueMember(Info, E, Subobject, *I);
Richard Smith51201882011-12-30 21:15:51 +00003229 Result = APValue(*I);
3230 ImplicitValueInitExpr VIE((*I)->getType());
3231 return EvaluateConstantExpression(Result.getUnionValue(), Info,
3232 Subobject, &VIE);
3233 }
3234
Richard Smithb4e85ed2012-01-06 16:39:00 +00003235 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003236}
3237
Richard Smith59efe262011-11-11 04:05:33 +00003238bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3239 switch (E->getCastKind()) {
3240 default:
3241 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3242
3243 case CK_ConstructorConversion:
3244 return Visit(E->getSubExpr());
3245
3246 case CK_DerivedToBase:
3247 case CK_UncheckedDerivedToBase: {
3248 CCValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003249 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003250 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003251 if (!DerivedObject.isStruct())
3252 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003253
3254 // Derived-to-base rvalue conversion: just slice off the derived part.
3255 APValue *Value = &DerivedObject;
3256 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3257 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3258 PathE = E->path_end(); PathI != PathE; ++PathI) {
3259 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3260 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3261 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3262 RD = Base;
3263 }
3264 Result = *Value;
3265 return true;
3266 }
3267 }
3268}
3269
Richard Smith180f4792011-11-10 06:34:14 +00003270bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3271 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3272 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3273
3274 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003275 const FieldDecl *Field = E->getInitializedFieldInUnion();
3276 Result = APValue(Field);
3277 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003278 return true;
Richard Smithec789162012-01-12 18:54:33 +00003279
3280 // If the initializer list for a union does not contain any elements, the
3281 // first element of the union is value-initialized.
3282 ImplicitValueInitExpr VIE(Field->getType());
3283 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3284
Richard Smith180f4792011-11-10 06:34:14 +00003285 LValue Subobject = This;
Richard Smithec789162012-01-12 18:54:33 +00003286 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00003287 return EvaluateConstantExpression(Result.getUnionValue(), Info,
Richard Smithec789162012-01-12 18:54:33 +00003288 Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003289 }
3290
3291 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3292 "initializer list for class with base classes");
3293 Result = APValue(APValue::UninitStruct(), 0,
3294 std::distance(RD->field_begin(), RD->field_end()));
3295 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003296 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003297 for (RecordDecl::field_iterator Field = RD->field_begin(),
3298 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3299 // Anonymous bit-fields are not considered members of the class for
3300 // purposes of aggregate initialization.
3301 if (Field->isUnnamedBitfield())
3302 continue;
3303
3304 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003305
Richard Smith745f5142012-01-27 01:14:48 +00003306 bool HaveInit = ElementNo < E->getNumInits();
3307
3308 // FIXME: Diagnostics here should point to the end of the initializer
3309 // list, not the start.
3310 HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3311 *Field, &Layout);
3312
3313 // Perform an implicit value-initialization for members beyond the end of
3314 // the initializer list.
3315 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3316
3317 if (!EvaluateConstantExpression(
3318 Result.getStructField((*Field)->getFieldIndex()),
3319 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3320 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003321 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003322 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003323 }
3324 }
3325
Richard Smith745f5142012-01-27 01:14:48 +00003326 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003327}
3328
3329bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3330 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith51201882011-12-30 21:15:51 +00003331 bool ZeroInit = E->requiresZeroInitialization();
3332 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003333 // If we've already performed zero-initialization, we're already done.
3334 if (!Result.isUninit())
3335 return true;
3336
Richard Smith51201882011-12-30 21:15:51 +00003337 if (ZeroInit)
3338 return ZeroInitialization(E);
3339
Richard Smith61802452011-12-22 02:22:31 +00003340 const CXXRecordDecl *RD = FD->getParent();
3341 if (RD->isUnion())
3342 Result = APValue((FieldDecl*)0);
3343 else
3344 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3345 std::distance(RD->field_begin(), RD->field_end()));
3346 return true;
3347 }
3348
Richard Smith180f4792011-11-10 06:34:14 +00003349 const FunctionDecl *Definition = 0;
3350 FD->getBody(Definition);
3351
Richard Smithc1c5f272011-12-13 06:39:58 +00003352 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3353 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003354
Richard Smith610a60c2012-01-10 04:32:03 +00003355 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003356 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003357 if (const MaterializeTemporaryExpr *ME
3358 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3359 return Visit(ME->GetTemporaryExpr());
3360
Richard Smith51201882011-12-30 21:15:51 +00003361 if (ZeroInit && !ZeroInitialization(E))
3362 return false;
3363
Richard Smith180f4792011-11-10 06:34:14 +00003364 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003365 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003366 cast<CXXConstructorDecl>(Definition), Info,
3367 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003368}
3369
3370static bool EvaluateRecord(const Expr *E, const LValue &This,
3371 APValue &Result, EvalInfo &Info) {
3372 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003373 "can't evaluate expression as a record rvalue");
3374 return RecordExprEvaluator(Info, This, Result).Visit(E);
3375}
3376
3377//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003378// Temporary Evaluation
3379//
3380// Temporaries are represented in the AST as rvalues, but generally behave like
3381// lvalues. The full-object of which the temporary is a subobject is implicitly
3382// materialized so that a reference can bind to it.
3383//===----------------------------------------------------------------------===//
3384namespace {
3385class TemporaryExprEvaluator
3386 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3387public:
3388 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3389 LValueExprEvaluatorBaseTy(Info, Result) {}
3390
3391 /// Visit an expression which constructs the value of this temporary.
3392 bool VisitConstructExpr(const Expr *E) {
3393 Result.set(E, Info.CurrentCall);
3394 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
3395 Result, E);
3396 }
3397
3398 bool VisitCastExpr(const CastExpr *E) {
3399 switch (E->getCastKind()) {
3400 default:
3401 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3402
3403 case CK_ConstructorConversion:
3404 return VisitConstructExpr(E->getSubExpr());
3405 }
3406 }
3407 bool VisitInitListExpr(const InitListExpr *E) {
3408 return VisitConstructExpr(E);
3409 }
3410 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3411 return VisitConstructExpr(E);
3412 }
3413 bool VisitCallExpr(const CallExpr *E) {
3414 return VisitConstructExpr(E);
3415 }
3416};
3417} // end anonymous namespace
3418
3419/// Evaluate an expression of record type as a temporary.
3420static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003421 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003422 return TemporaryExprEvaluator(Info, Result).Visit(E);
3423}
3424
3425//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003426// Vector Evaluation
3427//===----------------------------------------------------------------------===//
3428
3429namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003430 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003431 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3432 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003433 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003434
Richard Smith07fc6572011-10-22 21:10:00 +00003435 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3436 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003437
Richard Smith07fc6572011-10-22 21:10:00 +00003438 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3439 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3440 // FIXME: remove this APValue copy.
3441 Result = APValue(V.data(), V.size());
3442 return true;
3443 }
Richard Smith69c2c502011-11-04 05:33:44 +00003444 bool Success(const CCValue &V, const Expr *E) {
3445 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003446 Result = V;
3447 return true;
3448 }
Richard Smith51201882011-12-30 21:15:51 +00003449 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003450
Richard Smith07fc6572011-10-22 21:10:00 +00003451 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003452 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003453 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003454 bool VisitInitListExpr(const InitListExpr *E);
3455 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003456 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003457 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003458 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003459 };
3460} // end anonymous namespace
3461
3462static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003463 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003464 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003465}
3466
Richard Smith07fc6572011-10-22 21:10:00 +00003467bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3468 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003469 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003470
Richard Smithd62ca372011-12-06 22:44:34 +00003471 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003472 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003473
Eli Friedman46a52322011-03-25 00:43:55 +00003474 switch (E->getCastKind()) {
3475 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003476 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003477 if (SETy->isIntegerType()) {
3478 APSInt IntResult;
3479 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003480 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003481 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003482 } else if (SETy->isRealFloatingType()) {
3483 APFloat F(0.0);
3484 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003485 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003486 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003487 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003488 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003489 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003490
3491 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003492 SmallVector<APValue, 4> Elts(NElts, Val);
3493 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003494 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003495 case CK_BitCast: {
3496 // Evaluate the operand into an APInt we can extract from.
3497 llvm::APInt SValInt;
3498 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3499 return false;
3500 // Extract the elements
3501 QualType EltTy = VTy->getElementType();
3502 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3503 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3504 SmallVector<APValue, 4> Elts;
3505 if (EltTy->isRealFloatingType()) {
3506 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3507 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3508 unsigned FloatEltSize = EltSize;
3509 if (&Sem == &APFloat::x87DoubleExtended)
3510 FloatEltSize = 80;
3511 for (unsigned i = 0; i < NElts; i++) {
3512 llvm::APInt Elt;
3513 if (BigEndian)
3514 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3515 else
3516 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3517 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3518 }
3519 } else if (EltTy->isIntegerType()) {
3520 for (unsigned i = 0; i < NElts; i++) {
3521 llvm::APInt Elt;
3522 if (BigEndian)
3523 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3524 else
3525 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3526 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3527 }
3528 } else {
3529 return Error(E);
3530 }
3531 return Success(Elts, E);
3532 }
Eli Friedman46a52322011-03-25 00:43:55 +00003533 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003534 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003535 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003536}
3537
Richard Smith07fc6572011-10-22 21:10:00 +00003538bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003539VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003540 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003541 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003542 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003543
Nate Begeman59b5da62009-01-18 03:20:47 +00003544 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003545 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003546
Eli Friedman3edd5a92012-01-03 23:24:20 +00003547 // The number of initializers can be less than the number of
3548 // vector elements. For OpenCL, this can be due to nested vector
3549 // initialization. For GCC compatibility, missing trailing elements
3550 // should be initialized with zeroes.
3551 unsigned CountInits = 0, CountElts = 0;
3552 while (CountElts < NumElements) {
3553 // Handle nested vector initialization.
3554 if (CountInits < NumInits
3555 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3556 APValue v;
3557 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3558 return Error(E);
3559 unsigned vlen = v.getVectorLength();
3560 for (unsigned j = 0; j < vlen; j++)
3561 Elements.push_back(v.getVectorElt(j));
3562 CountElts += vlen;
3563 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003564 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003565 if (CountInits < NumInits) {
3566 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3567 return Error(E);
3568 } else // trailing integer zero.
3569 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3570 Elements.push_back(APValue(sInt));
3571 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003572 } else {
3573 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003574 if (CountInits < NumInits) {
3575 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3576 return Error(E);
3577 } else // trailing float zero.
3578 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3579 Elements.push_back(APValue(f));
3580 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003581 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003582 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003583 }
Richard Smith07fc6572011-10-22 21:10:00 +00003584 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003585}
3586
Richard Smith07fc6572011-10-22 21:10:00 +00003587bool
Richard Smith51201882011-12-30 21:15:51 +00003588VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003589 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003590 QualType EltTy = VT->getElementType();
3591 APValue ZeroElement;
3592 if (EltTy->isIntegerType())
3593 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3594 else
3595 ZeroElement =
3596 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3597
Chris Lattner5f9e2722011-07-23 10:55:15 +00003598 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003599 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003600}
3601
Richard Smith07fc6572011-10-22 21:10:00 +00003602bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003603 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003604 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003605}
3606
Nate Begeman59b5da62009-01-18 03:20:47 +00003607//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003608// Array Evaluation
3609//===----------------------------------------------------------------------===//
3610
3611namespace {
3612 class ArrayExprEvaluator
3613 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003614 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003615 APValue &Result;
3616 public:
3617
Richard Smith180f4792011-11-10 06:34:14 +00003618 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3619 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003620
3621 bool Success(const APValue &V, const Expr *E) {
3622 assert(V.isArray() && "Expected array type");
3623 Result = V;
3624 return true;
3625 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003626
Richard Smith51201882011-12-30 21:15:51 +00003627 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003628 const ConstantArrayType *CAT =
3629 Info.Ctx.getAsConstantArrayType(E->getType());
3630 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003631 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003632
3633 Result = APValue(APValue::UninitArray(), 0,
3634 CAT->getSize().getZExtValue());
3635 if (!Result.hasArrayFiller()) return true;
3636
Richard Smith51201882011-12-30 21:15:51 +00003637 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003638 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003639 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003640 ImplicitValueInitExpr VIE(CAT->getElementType());
3641 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3642 Subobject, &VIE);
3643 }
3644
Richard Smithcc5d4f62011-11-07 09:22:26 +00003645 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003646 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003647 };
3648} // end anonymous namespace
3649
Richard Smith180f4792011-11-10 06:34:14 +00003650static bool EvaluateArray(const Expr *E, const LValue &This,
3651 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003652 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003653 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003654}
3655
3656bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3657 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3658 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003659 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003660
Richard Smith974c5f92011-12-22 01:07:19 +00003661 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3662 // an appropriately-typed string literal enclosed in braces.
Richard Smithec789162012-01-12 18:54:33 +00003663 if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
Richard Smith974c5f92011-12-22 01:07:19 +00003664 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3665 LValue LV;
3666 if (!EvaluateLValue(E->getInit(0), LV, Info))
3667 return false;
3668 uint64_t NumElements = CAT->getSize().getZExtValue();
3669 Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3670
3671 // Copy the string literal into the array. FIXME: Do this better.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003672 LV.addArray(Info, E, CAT);
Richard Smith974c5f92011-12-22 01:07:19 +00003673 for (uint64_t I = 0; I < NumElements; ++I) {
3674 CCValue Char;
3675 if (!HandleLValueToRValueConversion(Info, E->getInit(0),
Richard Smith745f5142012-01-27 01:14:48 +00003676 CAT->getElementType(), LV, Char) ||
3677 !CheckConstantExpression(Info, E->getInit(0), Char,
3678 Result.getArrayInitializedElt(I)) ||
3679 !HandleLValueArrayAdjustment(Info, E->getInit(0), LV,
Richard Smithb4e85ed2012-01-06 16:39:00 +00003680 CAT->getElementType(), 1))
Richard Smith974c5f92011-12-22 01:07:19 +00003681 return false;
3682 }
3683 return true;
3684 }
3685
Richard Smith745f5142012-01-27 01:14:48 +00003686 bool Success = true;
3687
Richard Smithcc5d4f62011-11-07 09:22:26 +00003688 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3689 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003690 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003691 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003692 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003693 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003694 I != End; ++I, ++Index) {
3695 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
Richard Smith745f5142012-01-27 01:14:48 +00003696 Info, Subobject, cast<Expr>(*I)) ||
3697 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3698 CAT->getElementType(), 1)) {
3699 if (!Info.keepEvaluatingAfterFailure())
3700 return false;
3701 Success = false;
3702 }
Richard Smith180f4792011-11-10 06:34:14 +00003703 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003704
Richard Smith745f5142012-01-27 01:14:48 +00003705 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003706 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003707 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3708 // but sometimes does:
3709 // struct S { constexpr S() : p(&p) {} void *p; };
3710 // S s[10] = {};
Richard Smithcc5d4f62011-11-07 09:22:26 +00003711 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smith745f5142012-01-27 01:14:48 +00003712 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003713}
3714
Richard Smithe24f5fc2011-11-17 22:56:20 +00003715bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3716 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3717 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003718 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003719
Richard Smithec789162012-01-12 18:54:33 +00003720 bool HadZeroInit = !Result.isUninit();
3721 if (!HadZeroInit)
3722 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003723 if (!Result.hasArrayFiller())
3724 return true;
3725
3726 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003727
Richard Smith51201882011-12-30 21:15:51 +00003728 bool ZeroInit = E->requiresZeroInitialization();
3729 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003730 if (HadZeroInit)
3731 return true;
3732
Richard Smith51201882011-12-30 21:15:51 +00003733 if (ZeroInit) {
3734 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003735 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003736 ImplicitValueInitExpr VIE(CAT->getElementType());
3737 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3738 Subobject, &VIE);
3739 }
3740
Richard Smith61802452011-12-22 02:22:31 +00003741 const CXXRecordDecl *RD = FD->getParent();
3742 if (RD->isUnion())
3743 Result.getArrayFiller() = APValue((FieldDecl*)0);
3744 else
3745 Result.getArrayFiller() =
3746 APValue(APValue::UninitStruct(), RD->getNumBases(),
3747 std::distance(RD->field_begin(), RD->field_end()));
3748 return true;
3749 }
3750
Richard Smithe24f5fc2011-11-17 22:56:20 +00003751 const FunctionDecl *Definition = 0;
3752 FD->getBody(Definition);
3753
Richard Smithc1c5f272011-12-13 06:39:58 +00003754 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3755 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003756
3757 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3758 // but sometimes does:
3759 // struct S { constexpr S() : p(&p) {} void *p; };
3760 // S s[10];
3761 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003762 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003763
Richard Smithec789162012-01-12 18:54:33 +00003764 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003765 ImplicitValueInitExpr VIE(CAT->getElementType());
3766 if (!EvaluateConstantExpression(Result.getArrayFiller(), Info, Subobject,
3767 &VIE))
3768 return false;
3769 }
3770
Richard Smithe24f5fc2011-11-17 22:56:20 +00003771 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003772 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003773 cast<CXXConstructorDecl>(Definition),
3774 Info, Result.getArrayFiller());
3775}
3776
Richard Smithcc5d4f62011-11-07 09:22:26 +00003777//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003778// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003779//
3780// As a GNU extension, we support casting pointers to sufficiently-wide integer
3781// types and back in constant folding. Integer values are thus represented
3782// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003783//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003784
3785namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003786class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003787 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00003788 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003789public:
Richard Smith47a1eed2011-10-29 20:57:55 +00003790 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003791 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003792
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003793 bool Success(const llvm::APSInt &SI, const Expr *E) {
3794 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003795 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003796 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003797 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003798 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003799 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003800 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003801 return true;
3802 }
3803
Daniel Dunbar131eb432009-02-19 09:06:44 +00003804 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003805 assert(E->getType()->isIntegralOrEnumerationType() &&
3806 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003807 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003808 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003809 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003810 Result.getInt().setIsUnsigned(
3811 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003812 return true;
3813 }
3814
3815 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003816 assert(E->getType()->isIntegralOrEnumerationType() &&
3817 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003818 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003819 return true;
3820 }
3821
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003822 bool Success(CharUnits Size, const Expr *E) {
3823 return Success(Size.getQuantity(), E);
3824 }
3825
Richard Smith47a1eed2011-10-29 20:57:55 +00003826 bool Success(const CCValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00003827 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00003828 Result = V;
3829 return true;
3830 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003831 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003832 }
Mike Stump1eb44332009-09-09 15:08:12 +00003833
Richard Smith51201882011-12-30 21:15:51 +00003834 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00003835
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003836 //===--------------------------------------------------------------------===//
3837 // Visitor Methods
3838 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003839
Chris Lattner4c4867e2008-07-12 00:38:25 +00003840 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003841 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003842 }
3843 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003844 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003845 }
Eli Friedman04309752009-11-24 05:28:59 +00003846
3847 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3848 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003849 if (CheckReferencedDecl(E, E->getDecl()))
3850 return true;
3851
3852 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003853 }
3854 bool VisitMemberExpr(const MemberExpr *E) {
3855 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00003856 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00003857 return true;
3858 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003859
3860 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003861 }
3862
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003863 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003864 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003865 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003866 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00003867
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003868 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003869 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00003870
Anders Carlsson3068d112008-11-16 19:01:22 +00003871 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003872 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00003873 }
Mike Stump1eb44332009-09-09 15:08:12 +00003874
Richard Smithf10d9172011-10-11 21:43:33 +00003875 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00003876 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00003877 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00003878 }
3879
Sebastian Redl64b45f72009-01-05 20:52:13 +00003880 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003881 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003882 }
3883
Francois Pichet6ad6f282010-12-07 00:08:36 +00003884 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3885 return Success(E->getValue(), E);
3886 }
3887
John Wiegley21ff2e52011-04-28 00:16:57 +00003888 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3889 return Success(E->getValue(), E);
3890 }
3891
John Wiegley55262202011-04-25 06:54:41 +00003892 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3893 return Success(E->getValue(), E);
3894 }
3895
Eli Friedman722c7172009-02-28 03:59:05 +00003896 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003897 bool VisitUnaryImag(const UnaryOperator *E);
3898
Sebastian Redl295995c2010-09-10 20:55:47 +00003899 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00003900 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00003901
Chris Lattnerfcee0012008-07-11 21:24:13 +00003902private:
Ken Dyck8b752f12010-01-27 17:10:57 +00003903 CharUnits GetAlignOfExpr(const Expr *E);
3904 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003905 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003906 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003907 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003908};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003909} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003910
Richard Smithc49bd112011-10-28 17:51:58 +00003911/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3912/// produce either the integer value or a pointer.
3913///
3914/// GCC has a heinous extension which folds casts between pointer types and
3915/// pointer-sized integral types. We support this by allowing the evaluation of
3916/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3917/// Some simple arithmetic on such values is supported (they are treated much
3918/// like char*).
Richard Smithf48fdb02011-12-09 22:58:01 +00003919static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00003920 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003921 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003922 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003923}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003924
Richard Smithf48fdb02011-12-09 22:58:01 +00003925static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003926 CCValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00003927 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003928 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003929 if (!Val.isInt()) {
3930 // FIXME: It would be better to produce the diagnostic for casting
3931 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00003932 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00003933 return false;
3934 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003935 Result = Val.getInt();
3936 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00003937}
Anders Carlsson650c92f2008-07-08 15:34:11 +00003938
Richard Smithf48fdb02011-12-09 22:58:01 +00003939/// Check whether the given declaration can be directly converted to an integral
3940/// rvalue. If not, no diagnostic is produced; there are other things we can
3941/// try.
Eli Friedman04309752009-11-24 05:28:59 +00003942bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00003943 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003944 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003945 // Check for signedness/width mismatches between E type and ECD value.
3946 bool SameSign = (ECD->getInitVal().isSigned()
3947 == E->getType()->isSignedIntegerOrEnumerationType());
3948 bool SameWidth = (ECD->getInitVal().getBitWidth()
3949 == Info.Ctx.getIntWidth(E->getType()));
3950 if (SameSign && SameWidth)
3951 return Success(ECD->getInitVal(), E);
3952 else {
3953 // Get rid of mismatch (otherwise Success assertions will fail)
3954 // by computing a new value matching the type of E.
3955 llvm::APSInt Val = ECD->getInitVal();
3956 if (!SameSign)
3957 Val.setIsSigned(!ECD->getInitVal().isSigned());
3958 if (!SameWidth)
3959 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3960 return Success(Val, E);
3961 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003962 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003963 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00003964}
3965
Chris Lattnera4d55d82008-10-06 06:40:35 +00003966/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3967/// as GCC.
3968static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3969 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003970 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00003971 enum gcc_type_class {
3972 no_type_class = -1,
3973 void_type_class, integer_type_class, char_type_class,
3974 enumeral_type_class, boolean_type_class,
3975 pointer_type_class, reference_type_class, offset_type_class,
3976 real_type_class, complex_type_class,
3977 function_type_class, method_type_class,
3978 record_type_class, union_type_class,
3979 array_type_class, string_type_class,
3980 lang_type_class
3981 };
Mike Stump1eb44332009-09-09 15:08:12 +00003982
3983 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00003984 // ideal, however it is what gcc does.
3985 if (E->getNumArgs() == 0)
3986 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00003987
Chris Lattnera4d55d82008-10-06 06:40:35 +00003988 QualType ArgTy = E->getArg(0)->getType();
3989 if (ArgTy->isVoidType())
3990 return void_type_class;
3991 else if (ArgTy->isEnumeralType())
3992 return enumeral_type_class;
3993 else if (ArgTy->isBooleanType())
3994 return boolean_type_class;
3995 else if (ArgTy->isCharType())
3996 return string_type_class; // gcc doesn't appear to use char_type_class
3997 else if (ArgTy->isIntegerType())
3998 return integer_type_class;
3999 else if (ArgTy->isPointerType())
4000 return pointer_type_class;
4001 else if (ArgTy->isReferenceType())
4002 return reference_type_class;
4003 else if (ArgTy->isRealType())
4004 return real_type_class;
4005 else if (ArgTy->isComplexType())
4006 return complex_type_class;
4007 else if (ArgTy->isFunctionType())
4008 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004009 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004010 return record_type_class;
4011 else if (ArgTy->isUnionType())
4012 return union_type_class;
4013 else if (ArgTy->isArrayType())
4014 return array_type_class;
4015 else if (ArgTy->isUnionType())
4016 return union_type_class;
4017 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004018 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004019}
4020
Richard Smith80d4b552011-12-28 19:48:30 +00004021/// EvaluateBuiltinConstantPForLValue - Determine the result of
4022/// __builtin_constant_p when applied to the given lvalue.
4023///
4024/// An lvalue is only "constant" if it is a pointer or reference to the first
4025/// character of a string literal.
4026template<typename LValue>
4027static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
4028 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
4029 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4030}
4031
4032/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4033/// GCC as we can manage.
4034static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4035 QualType ArgType = Arg->getType();
4036
4037 // __builtin_constant_p always has one operand. The rules which gcc follows
4038 // are not precisely documented, but are as follows:
4039 //
4040 // - If the operand is of integral, floating, complex or enumeration type,
4041 // and can be folded to a known value of that type, it returns 1.
4042 // - If the operand and can be folded to a pointer to the first character
4043 // of a string literal (or such a pointer cast to an integral type), it
4044 // returns 1.
4045 //
4046 // Otherwise, it returns 0.
4047 //
4048 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4049 // its support for this does not currently work.
4050 if (ArgType->isIntegralOrEnumerationType()) {
4051 Expr::EvalResult Result;
4052 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4053 return false;
4054
4055 APValue &V = Result.Val;
4056 if (V.getKind() == APValue::Int)
4057 return true;
4058
4059 return EvaluateBuiltinConstantPForLValue(V);
4060 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4061 return Arg->isEvaluatable(Ctx);
4062 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4063 LValue LV;
4064 Expr::EvalStatus Status;
4065 EvalInfo Info(Ctx, Status);
4066 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4067 : EvaluatePointer(Arg, LV, Info)) &&
4068 !Status.HasSideEffects)
4069 return EvaluateBuiltinConstantPForLValue(LV);
4070 }
4071
4072 // Anything else isn't considered to be sufficiently constant.
4073 return false;
4074}
4075
John McCall42c8f872010-05-10 23:27:23 +00004076/// Retrieves the "underlying object type" of the given expression,
4077/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004078QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4079 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4080 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004081 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004082 } else if (const Expr *E = B.get<const Expr*>()) {
4083 if (isa<CompoundLiteralExpr>(E))
4084 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004085 }
4086
4087 return QualType();
4088}
4089
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004090bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004091 // TODO: Perhaps we should let LLVM lower this?
4092 LValue Base;
4093 if (!EvaluatePointer(E->getArg(0), Base, Info))
4094 return false;
4095
4096 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004097 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004098
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004099 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004100 if (T.isNull() ||
4101 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004102 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004103 T->isVariablyModifiedType() ||
4104 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004105 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004106
4107 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4108 CharUnits Offset = Base.getLValueOffset();
4109
4110 if (!Offset.isNegative() && Offset <= Size)
4111 Size -= Offset;
4112 else
4113 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004114 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004115}
4116
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004117bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004118 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004119 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004120 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004121
4122 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004123 if (TryEvaluateBuiltinObjectSize(E))
4124 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004125
Eric Christopherb2aaf512010-01-19 22:58:35 +00004126 // If evaluating the argument has side-effects we can't determine
4127 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004128 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004129 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004130 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004131 return Success(0, E);
4132 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004133
Richard Smithf48fdb02011-12-09 22:58:01 +00004134 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004135 }
4136
Chris Lattner019f4e82008-10-06 05:28:25 +00004137 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004138 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004139
Richard Smith80d4b552011-12-28 19:48:30 +00004140 case Builtin::BI__builtin_constant_p:
4141 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004142
Chris Lattner21fb98e2009-09-23 06:06:36 +00004143 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004144 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004145 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004146 return Success(Operand, E);
4147 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004148
4149 case Builtin::BI__builtin_expect:
4150 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004151
Douglas Gregor5726d402010-09-10 06:27:15 +00004152 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004153 // A call to strlen is not a constant expression.
4154 if (Info.getLangOpts().CPlusPlus0x)
4155 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_function)
4156 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4157 else
4158 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
4159 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004160 case Builtin::BI__builtin_strlen:
4161 // As an extension, we support strlen() and __builtin_strlen() as constant
4162 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004163 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004164 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4165 // The string literal may have embedded null characters. Find the first
4166 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004167 StringRef Str = S->getString();
4168 StringRef::size_type Pos = Str.find(0);
4169 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004170 Str = Str.substr(0, Pos);
4171
4172 return Success(Str.size(), E);
4173 }
4174
Richard Smithf48fdb02011-12-09 22:58:01 +00004175 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004176
4177 case Builtin::BI__atomic_is_lock_free: {
4178 APSInt SizeVal;
4179 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4180 return false;
4181
4182 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4183 // of two less than the maximum inline atomic width, we know it is
4184 // lock-free. If the size isn't a power of two, or greater than the
4185 // maximum alignment where we promote atomics, we know it is not lock-free
4186 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4187 // the answer can only be determined at runtime; for example, 16-byte
4188 // atomics have lock-free implementations on some, but not all,
4189 // x86-64 processors.
4190
4191 // Check power-of-two.
4192 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4193 if (!Size.isPowerOfTwo())
4194#if 0
4195 // FIXME: Suppress this folding until the ABI for the promotion width
4196 // settles.
4197 return Success(0, E);
4198#else
Richard Smithf48fdb02011-12-09 22:58:01 +00004199 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004200#endif
4201
4202#if 0
4203 // Check against promotion width.
4204 // FIXME: Suppress this folding until the ABI for the promotion width
4205 // settles.
4206 unsigned PromoteWidthBits =
4207 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
4208 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
4209 return Success(0, E);
4210#endif
4211
4212 // Check against inlining width.
4213 unsigned InlineWidthBits =
4214 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4215 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
4216 return Success(1, E);
4217
Richard Smithf48fdb02011-12-09 22:58:01 +00004218 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004219 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004220 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004221}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004222
Richard Smith625b8072011-10-31 01:37:14 +00004223static bool HasSameBase(const LValue &A, const LValue &B) {
4224 if (!A.getLValueBase())
4225 return !B.getLValueBase();
4226 if (!B.getLValueBase())
4227 return false;
4228
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004229 if (A.getLValueBase().getOpaqueValue() !=
4230 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004231 const Decl *ADecl = GetLValueBaseDecl(A);
4232 if (!ADecl)
4233 return false;
4234 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004235 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004236 return false;
4237 }
4238
4239 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith177dce72011-11-01 16:57:24 +00004240 A.getLValueFrame() == B.getLValueFrame();
Richard Smith625b8072011-10-31 01:37:14 +00004241}
4242
Richard Smith7b48a292012-02-01 05:53:12 +00004243/// Perform the given integer operation, which is known to need at most BitWidth
4244/// bits, and check for overflow in the original type (if that type was not an
4245/// unsigned type).
4246template<typename Operation>
4247static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4248 const APSInt &LHS, const APSInt &RHS,
4249 unsigned BitWidth, Operation Op) {
4250 if (LHS.isUnsigned())
4251 return Op(LHS, RHS);
4252
4253 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4254 APSInt Result = Value.trunc(LHS.getBitWidth());
4255 if (Result.extend(BitWidth) != Value)
4256 HandleOverflow(Info, E, Value, E->getType());
4257 return Result;
4258}
4259
Chris Lattnerb542afe2008-07-11 19:10:17 +00004260bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004261 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004262 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004263
John McCall2de56d12010-08-25 11:45:40 +00004264 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00004265 VisitIgnoredValue(E->getLHS());
4266 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00004267 }
4268
4269 if (E->isLogicalOp()) {
4270 // These need to be handled specially because the operands aren't
4271 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004272 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00004273
Richard Smithc49bd112011-10-28 17:51:58 +00004274 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00004275 // We were able to evaluate the LHS, see if we can get away with not
4276 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00004277 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004278 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004279
Richard Smithc49bd112011-10-28 17:51:58 +00004280 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00004281 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004282 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004283 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00004284 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004285 }
4286 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00004287 // FIXME: If both evaluations fail, we should produce the diagnostic from
4288 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
4289 // less clear how to diagnose this.
Richard Smithc49bd112011-10-28 17:51:58 +00004290 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004291 // We can't evaluate the LHS; however, sometimes the result
4292 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf48fdb02011-12-09 22:58:01 +00004293 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004294 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004295 // must have had side effects.
Richard Smith1e12c592011-10-16 21:26:27 +00004296 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004297
4298 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004299 }
4300 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00004301 }
Eli Friedmana6afa762008-11-13 06:09:17 +00004302
Eli Friedmana6afa762008-11-13 06:09:17 +00004303 return false;
4304 }
4305
Anders Carlsson286f85e2008-11-16 07:17:21 +00004306 QualType LHSTy = E->getLHS()->getType();
4307 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004308
4309 if (LHSTy->isAnyComplexType()) {
4310 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004311 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004312
Richard Smith745f5142012-01-27 01:14:48 +00004313 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4314 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004315 return false;
4316
Richard Smith745f5142012-01-27 01:14:48 +00004317 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004318 return false;
4319
4320 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004321 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004322 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004323 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004324 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4325
John McCall2de56d12010-08-25 11:45:40 +00004326 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004327 return Success((CR_r == APFloat::cmpEqual &&
4328 CR_i == APFloat::cmpEqual), E);
4329 else {
John McCall2de56d12010-08-25 11:45:40 +00004330 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004331 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004332 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004333 CR_r == APFloat::cmpLessThan ||
4334 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004335 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004336 CR_i == APFloat::cmpLessThan ||
4337 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004338 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004339 } else {
John McCall2de56d12010-08-25 11:45:40 +00004340 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004341 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4342 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4343 else {
John McCall2de56d12010-08-25 11:45:40 +00004344 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004345 "Invalid compex comparison.");
4346 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4347 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4348 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004349 }
4350 }
Mike Stump1eb44332009-09-09 15:08:12 +00004351
Anders Carlsson286f85e2008-11-16 07:17:21 +00004352 if (LHSTy->isRealFloatingType() &&
4353 RHSTy->isRealFloatingType()) {
4354 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004355
Richard Smith745f5142012-01-27 01:14:48 +00004356 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4357 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004358 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004359
Richard Smith745f5142012-01-27 01:14:48 +00004360 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004361 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004362
Anders Carlsson286f85e2008-11-16 07:17:21 +00004363 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004364
Anders Carlsson286f85e2008-11-16 07:17:21 +00004365 switch (E->getOpcode()) {
4366 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004367 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004368 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004369 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004370 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004371 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004372 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004373 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004374 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004375 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004376 E);
John McCall2de56d12010-08-25 11:45:40 +00004377 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004378 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004379 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004380 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004381 || CR == APFloat::cmpLessThan
4382 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004383 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004384 }
Mike Stump1eb44332009-09-09 15:08:12 +00004385
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004386 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004387 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004388 LValue LHSValue, RHSValue;
4389
4390 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4391 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004392 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004393
Richard Smith745f5142012-01-27 01:14:48 +00004394 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004395 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004396
Richard Smith625b8072011-10-31 01:37:14 +00004397 // Reject differing bases from the normal codepath; we special-case
4398 // comparisons to null.
4399 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004400 if (E->getOpcode() == BO_Sub) {
4401 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004402 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4403 return false;
4404 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4405 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4406 if (!LHSExpr || !RHSExpr)
4407 return false;
4408 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4409 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4410 if (!LHSAddrExpr || !RHSAddrExpr)
4411 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004412 // Make sure both labels come from the same function.
4413 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4414 RHSAddrExpr->getLabel()->getDeclContext())
4415 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004416 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4417 return true;
4418 }
Richard Smith9e36b532011-10-31 05:11:32 +00004419 // Inequalities and subtractions between unrelated pointers have
4420 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004421 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004422 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004423 // A constant address may compare equal to the address of a symbol.
4424 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004425 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004426 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4427 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004428 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004429 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004430 // distinct addresses. In clang, the result of such a comparison is
4431 // unspecified, so it is not a constant expression. However, we do know
4432 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004433 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4434 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004435 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004436 // We can't tell whether weak symbols will end up pointing to the same
4437 // object.
4438 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004439 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004440 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004441 // (Note that clang defaults to -fmerge-all-constants, which can
4442 // lead to inconsistent results for comparisons involving the address
4443 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004444 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004445 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004446
Richard Smith15efc4d2012-02-01 08:10:20 +00004447 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4448 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4449
Richard Smithf15fda02012-02-02 01:16:57 +00004450 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4451 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4452
John McCall2de56d12010-08-25 11:45:40 +00004453 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00004454 // C++11 [expr.add]p6:
4455 // Unless both pointers point to elements of the same array object, or
4456 // one past the last element of the array object, the behavior is
4457 // undefined.
4458 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4459 !AreElementsOfSameArray(getType(LHSValue.Base),
4460 LHSDesignator, RHSDesignator))
4461 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4462
Chris Lattner4992bdd2010-04-20 17:13:14 +00004463 QualType Type = E->getLHS()->getType();
4464 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004465
Richard Smith180f4792011-11-10 06:34:14 +00004466 CharUnits ElementSize;
4467 if (!HandleSizeof(Info, ElementType, ElementSize))
4468 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004469
Richard Smith15efc4d2012-02-01 08:10:20 +00004470 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
4471 // and produce incorrect results when it overflows. Such behavior
4472 // appears to be non-conforming, but is common, so perhaps we should
4473 // assume the standard intended for such cases to be undefined behavior
4474 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00004475
Richard Smith15efc4d2012-02-01 08:10:20 +00004476 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
4477 // overflow in the final conversion to ptrdiff_t.
4478 APSInt LHS(
4479 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
4480 APSInt RHS(
4481 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
4482 APSInt ElemSize(
4483 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
4484 APSInt TrueResult = (LHS - RHS) / ElemSize;
4485 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
4486
4487 if (Result.extend(65) != TrueResult)
4488 HandleOverflow(Info, E, TrueResult, E->getType());
4489 return Success(Result, E);
4490 }
Richard Smith82f28582012-01-31 06:41:30 +00004491
4492 // C++11 [expr.rel]p3:
4493 // Pointers to void (after pointer conversions) can be compared, with a
4494 // result defined as follows: If both pointers represent the same
4495 // address or are both the null pointer value, the result is true if the
4496 // operator is <= or >= and false otherwise; otherwise the result is
4497 // unspecified.
4498 // We interpret this as applying to pointers to *cv* void.
4499 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00004500 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00004501 CCEDiag(E, diag::note_constexpr_void_comparison);
4502
Richard Smithf15fda02012-02-02 01:16:57 +00004503 // C++11 [expr.rel]p2:
4504 // - If two pointers point to non-static data members of the same object,
4505 // or to subobjects or array elements fo such members, recursively, the
4506 // pointer to the later declared member compares greater provided the
4507 // two members have the same access control and provided their class is
4508 // not a union.
4509 // [...]
4510 // - Otherwise pointer comparisons are unspecified.
4511 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4512 E->isRelationalOp()) {
4513 bool WasArrayIndex;
4514 unsigned Mismatch =
4515 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
4516 RHSDesignator, WasArrayIndex);
4517 // At the point where the designators diverge, the comparison has a
4518 // specified value if:
4519 // - we are comparing array indices
4520 // - we are comparing fields of a union, or fields with the same access
4521 // Otherwise, the result is unspecified and thus the comparison is not a
4522 // constant expression.
4523 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
4524 Mismatch < RHSDesignator.Entries.size()) {
4525 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
4526 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
4527 if (!LF && !RF)
4528 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
4529 else if (!LF)
4530 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4531 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
4532 << RF->getParent() << RF;
4533 else if (!RF)
4534 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4535 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
4536 << LF->getParent() << LF;
4537 else if (!LF->getParent()->isUnion() &&
4538 LF->getAccess() != RF->getAccess())
4539 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
4540 << LF << LF->getAccess() << RF << RF->getAccess()
4541 << LF->getParent();
4542 }
4543 }
4544
Richard Smith625b8072011-10-31 01:37:14 +00004545 switch (E->getOpcode()) {
4546 default: llvm_unreachable("missing comparison operator");
4547 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4548 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4549 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4550 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4551 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4552 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004553 }
Anders Carlsson3068d112008-11-16 19:01:22 +00004554 }
4555 }
Richard Smithb02e4622012-02-01 01:42:44 +00004556
4557 if (LHSTy->isMemberPointerType()) {
4558 assert(E->isEqualityOp() && "unexpected member pointer operation");
4559 assert(RHSTy->isMemberPointerType() && "invalid comparison");
4560
4561 MemberPtr LHSValue, RHSValue;
4562
4563 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
4564 if (!LHSOK && Info.keepEvaluatingAfterFailure())
4565 return false;
4566
4567 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
4568 return false;
4569
4570 // C++11 [expr.eq]p2:
4571 // If both operands are null, they compare equal. Otherwise if only one is
4572 // null, they compare unequal.
4573 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
4574 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
4575 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4576 }
4577
4578 // Otherwise if either is a pointer to a virtual member function, the
4579 // result is unspecified.
4580 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
4581 if (MD->isVirtual())
4582 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4583 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
4584 if (MD->isVirtual())
4585 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4586
4587 // Otherwise they compare equal if and only if they would refer to the
4588 // same member of the same most derived object or the same subobject if
4589 // they were dereferenced with a hypothetical object of the associated
4590 // class type.
4591 bool Equal = LHSValue == RHSValue;
4592 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4593 }
4594
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004595 if (!LHSTy->isIntegralOrEnumerationType() ||
4596 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004597 // We can't continue from here for non-integral types.
4598 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004599 }
4600
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004601 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00004602 CCValue LHSVal;
Richard Smith745f5142012-01-27 01:14:48 +00004603
4604 bool LHSOK = EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info);
4605 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Richard Smithf48fdb02011-12-09 22:58:01 +00004606 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00004607
Richard Smith745f5142012-01-27 01:14:48 +00004608 if (!Visit(E->getRHS()) || !LHSOK)
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004609 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004610
Richard Smith47a1eed2011-10-29 20:57:55 +00004611 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004612
4613 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00004614 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00004615 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4616 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00004617 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00004618 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004619 else
Richard Smith47a1eed2011-10-29 20:57:55 +00004620 LHSVal.getLValueOffset() -= AdditionalOffset;
4621 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004622 return true;
4623 }
4624
4625 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00004626 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00004627 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004628 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4629 LHSVal.getInt().getZExtValue());
4630 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00004631 return true;
4632 }
4633
Eli Friedman65639282012-01-04 23:13:47 +00004634 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4635 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedman65639282012-01-04 23:13:47 +00004636 if (!LHSVal.getLValueOffset().isZero() ||
4637 !RHSVal.getLValueOffset().isZero())
4638 return false;
4639 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4640 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4641 if (!LHSExpr || !RHSExpr)
4642 return false;
4643 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4644 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4645 if (!LHSAddrExpr || !RHSAddrExpr)
4646 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004647 // Make sure both labels come from the same function.
4648 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4649 RHSAddrExpr->getLabel()->getDeclContext())
4650 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004651 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4652 return true;
4653 }
4654
Eli Friedman42edd0d2009-03-24 01:14:50 +00004655 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00004656 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00004657 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004658
Richard Smithc49bd112011-10-28 17:51:58 +00004659 APSInt &LHS = LHSVal.getInt();
4660 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00004661
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004662 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00004663 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004664 return Error(E);
Richard Smith7b48a292012-02-01 05:53:12 +00004665 case BO_Mul:
4666 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4667 LHS.getBitWidth() * 2,
4668 std::multiplies<APSInt>()), E);
4669 case BO_Add:
4670 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4671 LHS.getBitWidth() + 1,
4672 std::plus<APSInt>()), E);
4673 case BO_Sub:
4674 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4675 LHS.getBitWidth() + 1,
4676 std::minus<APSInt>()), E);
Richard Smithc49bd112011-10-28 17:51:58 +00004677 case BO_And: return Success(LHS & RHS, E);
4678 case BO_Xor: return Success(LHS ^ RHS, E);
4679 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004680 case BO_Div:
John McCall2de56d12010-08-25 11:45:40 +00004681 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00004682 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004683 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith3df61302012-01-31 23:24:19 +00004684 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is not
4685 // actually undefined behavior in C++11 due to a language defect.
4686 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4687 LHS.isSigned() && LHS.isMinSignedValue())
4688 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4689 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004690 case BO_Shl: {
Richard Smith789f9b62012-01-31 04:08:20 +00004691 // During constant-folding, a negative shift is an opposite shift. Such a
4692 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004693 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004694 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004695 RHS = -RHS;
4696 goto shift_right;
4697 }
4698
4699 shift_left:
Richard Smith789f9b62012-01-31 04:08:20 +00004700 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4701 // shifted type.
4702 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4703 if (SA != RHS) {
4704 CCEDiag(E, diag::note_constexpr_large_shift)
4705 << RHS << E->getType() << LHS.getBitWidth();
4706 } else if (LHS.isSigned()) {
4707 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4708 // operand, and must not overflow.
4709 if (LHS.isNegative())
4710 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4711 else if (LHS.countLeadingZeros() <= SA)
4712 HandleOverflow(Info, E, LHS.extend(LHS.getBitWidth() + SA) << SA,
4713 E->getType());
4714 }
4715
Richard Smithc49bd112011-10-28 17:51:58 +00004716 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004717 }
John McCall2de56d12010-08-25 11:45:40 +00004718 case BO_Shr: {
Richard Smith789f9b62012-01-31 04:08:20 +00004719 // During constant-folding, a negative shift is an opposite shift. Such a
4720 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004721 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004722 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004723 RHS = -RHS;
4724 goto shift_left;
4725 }
4726
4727 shift_right:
Richard Smith789f9b62012-01-31 04:08:20 +00004728 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4729 // shifted type.
4730 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4731 if (SA != RHS)
4732 CCEDiag(E, diag::note_constexpr_large_shift)
4733 << RHS << E->getType() << LHS.getBitWidth();
4734
Richard Smithc49bd112011-10-28 17:51:58 +00004735 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004736 }
Mike Stump1eb44332009-09-09 15:08:12 +00004737
Richard Smithc49bd112011-10-28 17:51:58 +00004738 case BO_LT: return Success(LHS < RHS, E);
4739 case BO_GT: return Success(LHS > RHS, E);
4740 case BO_LE: return Success(LHS <= RHS, E);
4741 case BO_GE: return Success(LHS >= RHS, E);
4742 case BO_EQ: return Success(LHS == RHS, E);
4743 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00004744 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004745}
4746
Ken Dyck8b752f12010-01-27 17:10:57 +00004747CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00004748 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4749 // the result is the size of the referenced type."
4750 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4751 // result shall be the alignment of the referenced type."
4752 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4753 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00004754
4755 // __alignof is defined to return the preferred alignment.
4756 return Info.Ctx.toCharUnitsFromBits(
4757 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00004758}
4759
Ken Dyck8b752f12010-01-27 17:10:57 +00004760CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00004761 E = E->IgnoreParens();
4762
4763 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00004764 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00004765 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004766 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4767 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00004768
Chris Lattneraf707ab2009-01-24 21:53:27 +00004769 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004770 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4771 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00004772
Chris Lattnere9feb472009-01-24 21:09:06 +00004773 return GetAlignOfType(E->getType());
4774}
4775
4776
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004777/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4778/// a result as the expression's type.
4779bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4780 const UnaryExprOrTypeTraitExpr *E) {
4781 switch(E->getKind()) {
4782 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00004783 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004784 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004785 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004786 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004787 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004788
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004789 case UETT_VecStep: {
4790 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00004791
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004792 if (Ty->isVectorType()) {
4793 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00004794
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004795 // The vec_step built-in functions that take a 3-component
4796 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4797 if (n == 3)
4798 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00004799
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004800 return Success(n, E);
4801 } else
4802 return Success(1, E);
4803 }
4804
4805 case UETT_SizeOf: {
4806 QualType SrcTy = E->getTypeOfArgument();
4807 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4808 // the result is the size of the referenced type."
4809 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4810 // result shall be the alignment of the referenced type."
4811 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4812 SrcTy = Ref->getPointeeType();
4813
Richard Smith180f4792011-11-10 06:34:14 +00004814 CharUnits Sizeof;
4815 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004816 return false;
Richard Smith180f4792011-11-10 06:34:14 +00004817 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004818 }
4819 }
4820
4821 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00004822}
4823
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004824bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004825 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004826 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004827 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004828 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004829 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004830 for (unsigned i = 0; i != n; ++i) {
4831 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4832 switch (ON.getKind()) {
4833 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004834 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004835 APSInt IdxResult;
4836 if (!EvaluateInteger(Idx, IdxResult, Info))
4837 return false;
4838 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4839 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004840 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004841 CurrentType = AT->getElementType();
4842 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4843 Result += IdxResult.getSExtValue() * ElementSize;
4844 break;
4845 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004846
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004847 case OffsetOfExpr::OffsetOfNode::Field: {
4848 FieldDecl *MemberDecl = ON.getField();
4849 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004850 if (!RT)
4851 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004852 RecordDecl *RD = RT->getDecl();
4853 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00004854 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004855 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00004856 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004857 CurrentType = MemberDecl->getType().getNonReferenceType();
4858 break;
4859 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004860
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004861 case OffsetOfExpr::OffsetOfNode::Identifier:
4862 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00004863
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004864 case OffsetOfExpr::OffsetOfNode::Base: {
4865 CXXBaseSpecifier *BaseSpec = ON.getBase();
4866 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00004867 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004868
4869 // Find the layout of the class whose base we are looking into.
4870 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004871 if (!RT)
4872 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004873 RecordDecl *RD = RT->getDecl();
4874 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4875
4876 // Find the base class itself.
4877 CurrentType = BaseSpec->getType();
4878 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4879 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004880 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004881
4882 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00004883 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004884 break;
4885 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004886 }
4887 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004888 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004889}
4890
Chris Lattnerb542afe2008-07-11 19:10:17 +00004891bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004892 switch (E->getOpcode()) {
4893 default:
4894 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4895 // See C99 6.6p3.
4896 return Error(E);
4897 case UO_Extension:
4898 // FIXME: Should extension allow i-c-e extension expressions in its scope?
4899 // If so, we could clear the diagnostic ID.
4900 return Visit(E->getSubExpr());
4901 case UO_Plus:
4902 // The result is just the value.
4903 return Visit(E->getSubExpr());
4904 case UO_Minus: {
4905 if (!Visit(E->getSubExpr()))
4906 return false;
4907 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00004908 const APSInt &Value = Result.getInt();
4909 if (Value.isSigned() && Value.isMinSignedValue())
4910 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
4911 E->getType());
4912 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00004913 }
4914 case UO_Not: {
4915 if (!Visit(E->getSubExpr()))
4916 return false;
4917 if (!Result.isInt()) return Error(E);
4918 return Success(~Result.getInt(), E);
4919 }
4920 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00004921 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00004922 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00004923 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004924 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004925 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004926 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004927}
Mike Stump1eb44332009-09-09 15:08:12 +00004928
Chris Lattner732b2232008-07-12 01:15:53 +00004929/// HandleCast - This is used to evaluate implicit or explicit casts where the
4930/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004931bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4932 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00004933 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00004934 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00004935
Eli Friedman46a52322011-03-25 00:43:55 +00004936 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00004937 case CK_BaseToDerived:
4938 case CK_DerivedToBase:
4939 case CK_UncheckedDerivedToBase:
4940 case CK_Dynamic:
4941 case CK_ToUnion:
4942 case CK_ArrayToPointerDecay:
4943 case CK_FunctionToPointerDecay:
4944 case CK_NullToPointer:
4945 case CK_NullToMemberPointer:
4946 case CK_BaseToDerivedMemberPointer:
4947 case CK_DerivedToBaseMemberPointer:
4948 case CK_ConstructorConversion:
4949 case CK_IntegralToPointer:
4950 case CK_ToVoid:
4951 case CK_VectorSplat:
4952 case CK_IntegralToFloating:
4953 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00004954 case CK_CPointerToObjCPointerCast:
4955 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004956 case CK_AnyPointerToBlockPointerCast:
4957 case CK_ObjCObjectLValueCast:
4958 case CK_FloatingRealToComplex:
4959 case CK_FloatingComplexToReal:
4960 case CK_FloatingComplexCast:
4961 case CK_FloatingComplexToIntegralComplex:
4962 case CK_IntegralRealToComplex:
4963 case CK_IntegralComplexCast:
4964 case CK_IntegralComplexToFloatingComplex:
4965 llvm_unreachable("invalid cast kind for integral value");
4966
Eli Friedmane50c2972011-03-25 19:07:11 +00004967 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004968 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00004969 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00004970 case CK_ARCProduceObject:
4971 case CK_ARCConsumeObject:
4972 case CK_ARCReclaimReturnedObject:
4973 case CK_ARCExtendBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00004974 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004975
Richard Smith7d580a42012-01-17 21:17:26 +00004976 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00004977 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00004978 case CK_AtomicToNonAtomic:
4979 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00004980 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00004981 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004982
4983 case CK_MemberPointerToBoolean:
4984 case CK_PointerToBoolean:
4985 case CK_IntegralToBoolean:
4986 case CK_FloatingToBoolean:
4987 case CK_FloatingComplexToBoolean:
4988 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004989 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00004990 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00004991 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004992 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004993 }
4994
Eli Friedman46a52322011-03-25 00:43:55 +00004995 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00004996 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004997 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00004998
Eli Friedmanbe265702009-02-20 01:15:07 +00004999 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00005000 // Allow casts of address-of-label differences if they are no-ops
5001 // or narrowing. (The narrowing case isn't actually guaranteed to
5002 // be constant-evaluatable except in some narrow cases which are hard
5003 // to detect here. We let it through on the assumption the user knows
5004 // what they are doing.)
5005 if (Result.isAddrLabelDiff())
5006 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005007 // Only allow casts of lvalues if they are lossless.
5008 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5009 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005010
Richard Smithf72fccf2012-01-30 22:27:01 +00005011 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5012 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005013 }
Mike Stump1eb44332009-09-09 15:08:12 +00005014
Eli Friedman46a52322011-03-25 00:43:55 +00005015 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005016 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5017
John McCallefdb83e2010-05-07 21:00:08 +00005018 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005019 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005020 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005021
Daniel Dunbardd211642009-02-19 22:24:01 +00005022 if (LV.getLValueBase()) {
5023 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005024 // FIXME: Allow a larger integer size than the pointer size, and allow
5025 // narrowing back down to pointer width in subsequent integral casts.
5026 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005027 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005028 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005029
Richard Smithb755a9d2011-11-16 07:18:12 +00005030 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005031 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005032 return true;
5033 }
5034
Ken Dycka7305832010-01-15 12:37:54 +00005035 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5036 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005037 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005038 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005039
Eli Friedman46a52322011-03-25 00:43:55 +00005040 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005041 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005042 if (!EvaluateComplex(SubExpr, C, Info))
5043 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005044 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005045 }
Eli Friedman2217c872009-02-22 11:46:18 +00005046
Eli Friedman46a52322011-03-25 00:43:55 +00005047 case CK_FloatingToIntegral: {
5048 APFloat F(0.0);
5049 if (!EvaluateFloat(SubExpr, F, Info))
5050 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005051
Richard Smithc1c5f272011-12-13 06:39:58 +00005052 APSInt Value;
5053 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5054 return false;
5055 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005056 }
5057 }
Mike Stump1eb44332009-09-09 15:08:12 +00005058
Eli Friedman46a52322011-03-25 00:43:55 +00005059 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005060}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005061
Eli Friedman722c7172009-02-28 03:59:05 +00005062bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5063 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005064 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005065 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5066 return false;
5067 if (!LV.isComplexInt())
5068 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005069 return Success(LV.getComplexIntReal(), E);
5070 }
5071
5072 return Visit(E->getSubExpr());
5073}
5074
Eli Friedman664a1042009-02-27 04:45:43 +00005075bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005076 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005077 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005078 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5079 return false;
5080 if (!LV.isComplexInt())
5081 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005082 return Success(LV.getComplexIntImag(), E);
5083 }
5084
Richard Smith8327fad2011-10-24 18:44:57 +00005085 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005086 return Success(0, E);
5087}
5088
Douglas Gregoree8aff02011-01-04 17:33:58 +00005089bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5090 return Success(E->getPackLength(), E);
5091}
5092
Sebastian Redl295995c2010-09-10 20:55:47 +00005093bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5094 return Success(E->getValue(), E);
5095}
5096
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005097//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005098// Float Evaluation
5099//===----------------------------------------------------------------------===//
5100
5101namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005102class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005103 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005104 APFloat &Result;
5105public:
5106 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005107 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005108
Richard Smith47a1eed2011-10-29 20:57:55 +00005109 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005110 Result = V.getFloat();
5111 return true;
5112 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005113
Richard Smith51201882011-12-30 21:15:51 +00005114 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005115 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5116 return true;
5117 }
5118
Chris Lattner019f4e82008-10-06 05:28:25 +00005119 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005120
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005121 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005122 bool VisitBinaryOperator(const BinaryOperator *E);
5123 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005124 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005125
John McCallabd3a852010-05-07 22:08:54 +00005126 bool VisitUnaryReal(const UnaryOperator *E);
5127 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005128
Richard Smith51201882011-12-30 21:15:51 +00005129 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005130};
5131} // end anonymous namespace
5132
5133static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005134 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005135 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005136}
5137
Jay Foad4ba2a172011-01-12 09:06:06 +00005138static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005139 QualType ResultTy,
5140 const Expr *Arg,
5141 bool SNaN,
5142 llvm::APFloat &Result) {
5143 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5144 if (!S) return false;
5145
5146 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5147
5148 llvm::APInt fill;
5149
5150 // Treat empty strings as if they were zero.
5151 if (S->getString().empty())
5152 fill = llvm::APInt(32, 0);
5153 else if (S->getString().getAsInteger(0, fill))
5154 return false;
5155
5156 if (SNaN)
5157 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5158 else
5159 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5160 return true;
5161}
5162
Chris Lattner019f4e82008-10-06 05:28:25 +00005163bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005164 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005165 default:
5166 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5167
Chris Lattner019f4e82008-10-06 05:28:25 +00005168 case Builtin::BI__builtin_huge_val:
5169 case Builtin::BI__builtin_huge_valf:
5170 case Builtin::BI__builtin_huge_vall:
5171 case Builtin::BI__builtin_inf:
5172 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005173 case Builtin::BI__builtin_infl: {
5174 const llvm::fltSemantics &Sem =
5175 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005176 Result = llvm::APFloat::getInf(Sem);
5177 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005178 }
Mike Stump1eb44332009-09-09 15:08:12 +00005179
John McCalldb7b72a2010-02-28 13:00:19 +00005180 case Builtin::BI__builtin_nans:
5181 case Builtin::BI__builtin_nansf:
5182 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005183 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5184 true, Result))
5185 return Error(E);
5186 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005187
Chris Lattner9e621712008-10-06 06:31:58 +00005188 case Builtin::BI__builtin_nan:
5189 case Builtin::BI__builtin_nanf:
5190 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005191 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005192 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005193 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5194 false, Result))
5195 return Error(E);
5196 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005197
5198 case Builtin::BI__builtin_fabs:
5199 case Builtin::BI__builtin_fabsf:
5200 case Builtin::BI__builtin_fabsl:
5201 if (!EvaluateFloat(E->getArg(0), Result, Info))
5202 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005203
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005204 if (Result.isNegative())
5205 Result.changeSign();
5206 return true;
5207
Mike Stump1eb44332009-09-09 15:08:12 +00005208 case Builtin::BI__builtin_copysign:
5209 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005210 case Builtin::BI__builtin_copysignl: {
5211 APFloat RHS(0.);
5212 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5213 !EvaluateFloat(E->getArg(1), RHS, Info))
5214 return false;
5215 Result.copySign(RHS);
5216 return true;
5217 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005218 }
5219}
5220
John McCallabd3a852010-05-07 22:08:54 +00005221bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005222 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5223 ComplexValue CV;
5224 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5225 return false;
5226 Result = CV.FloatReal;
5227 return true;
5228 }
5229
5230 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005231}
5232
5233bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005234 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5235 ComplexValue CV;
5236 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5237 return false;
5238 Result = CV.FloatImag;
5239 return true;
5240 }
5241
Richard Smith8327fad2011-10-24 18:44:57 +00005242 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005243 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5244 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005245 return true;
5246}
5247
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005248bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005249 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005250 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005251 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005252 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005253 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005254 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5255 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005256 Result.changeSign();
5257 return true;
5258 }
5259}
Chris Lattner019f4e82008-10-06 05:28:25 +00005260
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005261bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005262 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5263 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005264
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005265 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005266 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5267 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005268 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005269 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005270 return false;
5271
5272 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005273 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005274 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005275 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005276 break;
John McCall2de56d12010-08-25 11:45:40 +00005277 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005278 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005279 break;
John McCall2de56d12010-08-25 11:45:40 +00005280 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005281 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005282 break;
John McCall2de56d12010-08-25 11:45:40 +00005283 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005284 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005285 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005286 }
Richard Smith7b48a292012-02-01 05:53:12 +00005287
5288 if (Result.isInfinity() || Result.isNaN())
5289 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5290 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005291}
5292
5293bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5294 Result = E->getValue();
5295 return true;
5296}
5297
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005298bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5299 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005300
Eli Friedman2a523ee2011-03-25 00:54:52 +00005301 switch (E->getCastKind()) {
5302 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005303 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005304
5305 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005306 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005307 return EvaluateInteger(SubExpr, IntResult, Info) &&
5308 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5309 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005310 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005311
5312 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005313 if (!Visit(SubExpr))
5314 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005315 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5316 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005317 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005318
Eli Friedman2a523ee2011-03-25 00:54:52 +00005319 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005320 ComplexValue V;
5321 if (!EvaluateComplex(SubExpr, V, Info))
5322 return false;
5323 Result = V.getComplexFloatReal();
5324 return true;
5325 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005326 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005327}
5328
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005329//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005330// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005331//===----------------------------------------------------------------------===//
5332
5333namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005334class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005335 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005336 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005337
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005338public:
John McCallf4cf1a12010-05-07 17:22:02 +00005339 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005340 : ExprEvaluatorBaseTy(info), Result(Result) {}
5341
Richard Smith47a1eed2011-10-29 20:57:55 +00005342 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005343 Result.setFrom(V);
5344 return true;
5345 }
Mike Stump1eb44332009-09-09 15:08:12 +00005346
Eli Friedman7ead5c72012-01-10 04:58:17 +00005347 bool ZeroInitialization(const Expr *E);
5348
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005349 //===--------------------------------------------------------------------===//
5350 // Visitor Methods
5351 //===--------------------------------------------------------------------===//
5352
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005353 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005354 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005355 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005356 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005357 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005358};
5359} // end anonymous namespace
5360
John McCallf4cf1a12010-05-07 17:22:02 +00005361static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5362 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005363 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005364 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005365}
5366
Eli Friedman7ead5c72012-01-10 04:58:17 +00005367bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005368 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005369 if (ElemTy->isRealFloatingType()) {
5370 Result.makeComplexFloat();
5371 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5372 Result.FloatReal = Zero;
5373 Result.FloatImag = Zero;
5374 } else {
5375 Result.makeComplexInt();
5376 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5377 Result.IntReal = Zero;
5378 Result.IntImag = Zero;
5379 }
5380 return true;
5381}
5382
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005383bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5384 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005385
5386 if (SubExpr->getType()->isRealFloatingType()) {
5387 Result.makeComplexFloat();
5388 APFloat &Imag = Result.FloatImag;
5389 if (!EvaluateFloat(SubExpr, Imag, Info))
5390 return false;
5391
5392 Result.FloatReal = APFloat(Imag.getSemantics());
5393 return true;
5394 } else {
5395 assert(SubExpr->getType()->isIntegerType() &&
5396 "Unexpected imaginary literal.");
5397
5398 Result.makeComplexInt();
5399 APSInt &Imag = Result.IntImag;
5400 if (!EvaluateInteger(SubExpr, Imag, Info))
5401 return false;
5402
5403 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5404 return true;
5405 }
5406}
5407
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005408bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005409
John McCall8786da72010-12-14 17:51:41 +00005410 switch (E->getCastKind()) {
5411 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005412 case CK_BaseToDerived:
5413 case CK_DerivedToBase:
5414 case CK_UncheckedDerivedToBase:
5415 case CK_Dynamic:
5416 case CK_ToUnion:
5417 case CK_ArrayToPointerDecay:
5418 case CK_FunctionToPointerDecay:
5419 case CK_NullToPointer:
5420 case CK_NullToMemberPointer:
5421 case CK_BaseToDerivedMemberPointer:
5422 case CK_DerivedToBaseMemberPointer:
5423 case CK_MemberPointerToBoolean:
5424 case CK_ConstructorConversion:
5425 case CK_IntegralToPointer:
5426 case CK_PointerToIntegral:
5427 case CK_PointerToBoolean:
5428 case CK_ToVoid:
5429 case CK_VectorSplat:
5430 case CK_IntegralCast:
5431 case CK_IntegralToBoolean:
5432 case CK_IntegralToFloating:
5433 case CK_FloatingToIntegral:
5434 case CK_FloatingToBoolean:
5435 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005436 case CK_CPointerToObjCPointerCast:
5437 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005438 case CK_AnyPointerToBlockPointerCast:
5439 case CK_ObjCObjectLValueCast:
5440 case CK_FloatingComplexToReal:
5441 case CK_FloatingComplexToBoolean:
5442 case CK_IntegralComplexToReal:
5443 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005444 case CK_ARCProduceObject:
5445 case CK_ARCConsumeObject:
5446 case CK_ARCReclaimReturnedObject:
5447 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005448 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005449
John McCall8786da72010-12-14 17:51:41 +00005450 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005451 case CK_AtomicToNonAtomic:
5452 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005453 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005454 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005455
5456 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005457 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005458 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005459 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005460
5461 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005462 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005463 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005464 return false;
5465
John McCall8786da72010-12-14 17:51:41 +00005466 Result.makeComplexFloat();
5467 Result.FloatImag = APFloat(Real.getSemantics());
5468 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005469 }
5470
John McCall8786da72010-12-14 17:51:41 +00005471 case CK_FloatingComplexCast: {
5472 if (!Visit(E->getSubExpr()))
5473 return false;
5474
5475 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5476 QualType From
5477 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5478
Richard Smithc1c5f272011-12-13 06:39:58 +00005479 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5480 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005481 }
5482
5483 case CK_FloatingComplexToIntegralComplex: {
5484 if (!Visit(E->getSubExpr()))
5485 return false;
5486
5487 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5488 QualType From
5489 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5490 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005491 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5492 To, Result.IntReal) &&
5493 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5494 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005495 }
5496
5497 case CK_IntegralRealToComplex: {
5498 APSInt &Real = Result.IntReal;
5499 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5500 return false;
5501
5502 Result.makeComplexInt();
5503 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5504 return true;
5505 }
5506
5507 case CK_IntegralComplexCast: {
5508 if (!Visit(E->getSubExpr()))
5509 return false;
5510
5511 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5512 QualType From
5513 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5514
Richard Smithf72fccf2012-01-30 22:27:01 +00005515 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5516 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005517 return true;
5518 }
5519
5520 case CK_IntegralComplexToFloatingComplex: {
5521 if (!Visit(E->getSubExpr()))
5522 return false;
5523
5524 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5525 QualType From
5526 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5527 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005528 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5529 To, Result.FloatReal) &&
5530 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5531 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005532 }
5533 }
5534
5535 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005536}
5537
John McCallf4cf1a12010-05-07 17:22:02 +00005538bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005539 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005540 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5541
Richard Smith745f5142012-01-27 01:14:48 +00005542 bool LHSOK = Visit(E->getLHS());
5543 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005544 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005545
John McCallf4cf1a12010-05-07 17:22:02 +00005546 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005547 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005548 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005549
Daniel Dunbar3f279872009-01-29 01:32:56 +00005550 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5551 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005552 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005553 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005554 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005555 if (Result.isComplexFloat()) {
5556 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5557 APFloat::rmNearestTiesToEven);
5558 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5559 APFloat::rmNearestTiesToEven);
5560 } else {
5561 Result.getComplexIntReal() += RHS.getComplexIntReal();
5562 Result.getComplexIntImag() += RHS.getComplexIntImag();
5563 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005564 break;
John McCall2de56d12010-08-25 11:45:40 +00005565 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005566 if (Result.isComplexFloat()) {
5567 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5568 APFloat::rmNearestTiesToEven);
5569 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5570 APFloat::rmNearestTiesToEven);
5571 } else {
5572 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5573 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5574 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005575 break;
John McCall2de56d12010-08-25 11:45:40 +00005576 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005577 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005578 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005579 APFloat &LHS_r = LHS.getComplexFloatReal();
5580 APFloat &LHS_i = LHS.getComplexFloatImag();
5581 APFloat &RHS_r = RHS.getComplexFloatReal();
5582 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005583
Daniel Dunbar3f279872009-01-29 01:32:56 +00005584 APFloat Tmp = LHS_r;
5585 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5586 Result.getComplexFloatReal() = Tmp;
5587 Tmp = LHS_i;
5588 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5589 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5590
5591 Tmp = LHS_r;
5592 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5593 Result.getComplexFloatImag() = Tmp;
5594 Tmp = LHS_i;
5595 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5596 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5597 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005598 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005599 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005600 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5601 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00005602 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005603 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5604 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5605 }
5606 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005607 case BO_Div:
5608 if (Result.isComplexFloat()) {
5609 ComplexValue LHS = Result;
5610 APFloat &LHS_r = LHS.getComplexFloatReal();
5611 APFloat &LHS_i = LHS.getComplexFloatImag();
5612 APFloat &RHS_r = RHS.getComplexFloatReal();
5613 APFloat &RHS_i = RHS.getComplexFloatImag();
5614 APFloat &Res_r = Result.getComplexFloatReal();
5615 APFloat &Res_i = Result.getComplexFloatImag();
5616
5617 APFloat Den = RHS_r;
5618 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5619 APFloat Tmp = RHS_i;
5620 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5621 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5622
5623 Res_r = LHS_r;
5624 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5625 Tmp = LHS_i;
5626 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5627 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5628 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5629
5630 Res_i = LHS_i;
5631 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5632 Tmp = LHS_r;
5633 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5634 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5635 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5636 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00005637 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5638 return Error(E, diag::note_expr_divide_by_zero);
5639
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005640 ComplexValue LHS = Result;
5641 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5642 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5643 Result.getComplexIntReal() =
5644 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5645 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5646 Result.getComplexIntImag() =
5647 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5648 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5649 }
5650 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005651 }
5652
John McCallf4cf1a12010-05-07 17:22:02 +00005653 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005654}
5655
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005656bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5657 // Get the operand value into 'Result'.
5658 if (!Visit(E->getSubExpr()))
5659 return false;
5660
5661 switch (E->getOpcode()) {
5662 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00005663 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005664 case UO_Extension:
5665 return true;
5666 case UO_Plus:
5667 // The result is always just the subexpr.
5668 return true;
5669 case UO_Minus:
5670 if (Result.isComplexFloat()) {
5671 Result.getComplexFloatReal().changeSign();
5672 Result.getComplexFloatImag().changeSign();
5673 }
5674 else {
5675 Result.getComplexIntReal() = -Result.getComplexIntReal();
5676 Result.getComplexIntImag() = -Result.getComplexIntImag();
5677 }
5678 return true;
5679 case UO_Not:
5680 if (Result.isComplexFloat())
5681 Result.getComplexFloatImag().changeSign();
5682 else
5683 Result.getComplexIntImag() = -Result.getComplexIntImag();
5684 return true;
5685 }
5686}
5687
Eli Friedman7ead5c72012-01-10 04:58:17 +00005688bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5689 if (E->getNumInits() == 2) {
5690 if (E->getType()->isComplexType()) {
5691 Result.makeComplexFloat();
5692 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5693 return false;
5694 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5695 return false;
5696 } else {
5697 Result.makeComplexInt();
5698 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5699 return false;
5700 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5701 return false;
5702 }
5703 return true;
5704 }
5705 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5706}
5707
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005708//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00005709// Void expression evaluation, primarily for a cast to void on the LHS of a
5710// comma operator
5711//===----------------------------------------------------------------------===//
5712
5713namespace {
5714class VoidExprEvaluator
5715 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5716public:
5717 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5718
5719 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00005720
5721 bool VisitCastExpr(const CastExpr *E) {
5722 switch (E->getCastKind()) {
5723 default:
5724 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5725 case CK_ToVoid:
5726 VisitIgnoredValue(E->getSubExpr());
5727 return true;
5728 }
5729 }
5730};
5731} // end anonymous namespace
5732
5733static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5734 assert(E->isRValue() && E->getType()->isVoidType());
5735 return VoidExprEvaluator(Info).Visit(E);
5736}
5737
5738//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00005739// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005740//===----------------------------------------------------------------------===//
5741
Richard Smith47a1eed2011-10-29 20:57:55 +00005742static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00005743 // In C, function designators are not lvalues, but we evaluate them as if they
5744 // are.
5745 if (E->isGLValue() || E->getType()->isFunctionType()) {
5746 LValue LV;
5747 if (!EvaluateLValue(E, LV, Info))
5748 return false;
5749 LV.moveInto(Result);
5750 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005751 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00005752 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00005753 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005754 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005755 return false;
John McCallefdb83e2010-05-07 21:00:08 +00005756 } else if (E->getType()->hasPointerRepresentation()) {
5757 LValue LV;
5758 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005759 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005760 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00005761 } else if (E->getType()->isRealFloatingType()) {
5762 llvm::APFloat F(0.0);
5763 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005764 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00005765 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00005766 } else if (E->getType()->isAnyComplexType()) {
5767 ComplexValue C;
5768 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005769 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005770 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00005771 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005772 MemberPtr P;
5773 if (!EvaluateMemberPointer(E, P, Info))
5774 return false;
5775 P.moveInto(Result);
5776 return true;
Richard Smith51201882011-12-30 21:15:51 +00005777 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005778 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005779 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005780 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00005781 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005782 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00005783 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005784 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005785 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005786 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5787 return false;
5788 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00005789 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00005790 if (Info.getLangOpts().CPlusPlus0x)
5791 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5792 << E->getType();
5793 else
5794 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00005795 if (!EvaluateVoid(E, Info))
5796 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005797 } else if (Info.getLangOpts().CPlusPlus0x) {
5798 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5799 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005800 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00005801 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00005802 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005803 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005804
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00005805 return true;
5806}
5807
Richard Smith69c2c502011-11-04 05:33:44 +00005808/// EvaluateConstantExpression - Evaluate an expression as a constant expression
5809/// in-place in an APValue. In some cases, the in-place evaluation is essential,
5810/// since later initializers for an object can indirectly refer to subobjects
5811/// which were initialized earlier.
5812static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +00005813 const LValue &This, const Expr *E,
5814 CheckConstantExpressionKind CCEK) {
Richard Smith51201882011-12-30 21:15:51 +00005815 if (!CheckLiteralType(Info, E))
5816 return false;
5817
5818 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00005819 // Evaluate arrays and record types in-place, so that later initializers can
5820 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00005821 if (E->getType()->isArrayType())
5822 return EvaluateArray(E, This, Result, Info);
5823 else if (E->getType()->isRecordType())
5824 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00005825 }
5826
5827 // For any other type, in-place evaluation is unimportant.
5828 CCValue CoreConstResult;
5829 return Evaluate(CoreConstResult, Info, E) &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005830 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smith69c2c502011-11-04 05:33:44 +00005831}
5832
Richard Smithf48fdb02011-12-09 22:58:01 +00005833/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5834/// lvalue-to-rvalue cast if it is an lvalue.
5835static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00005836 if (!CheckLiteralType(Info, E))
5837 return false;
5838
Richard Smithf48fdb02011-12-09 22:58:01 +00005839 CCValue Value;
5840 if (!::Evaluate(Value, Info, E))
5841 return false;
5842
5843 if (E->isGLValue()) {
5844 LValue LV;
5845 LV.setFrom(Value);
5846 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
5847 return false;
5848 }
5849
5850 // Check this core constant expression is a constant expression, and if so,
5851 // convert it to one.
5852 return CheckConstantExpression(Info, E, Value, Result);
5853}
Richard Smithc49bd112011-10-28 17:51:58 +00005854
Richard Smith51f47082011-10-29 00:50:52 +00005855/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00005856/// any crazy technique (that has nothing to do with language standards) that
5857/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00005858/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
5859/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00005860bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00005861 // Fast-path evaluations of integer literals, since we sometimes see files
5862 // containing vast quantities of these.
5863 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
5864 Result.Val = APValue(APSInt(L->getValue(),
5865 L->getType()->isUnsignedIntegerType()));
5866 return true;
5867 }
5868
Richard Smith2d6a5672012-01-14 04:30:29 +00005869 // FIXME: Evaluating values of large array and record types can cause
5870 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00005871 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5872 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00005873 return false;
5874
Richard Smithf48fdb02011-12-09 22:58:01 +00005875 EvalInfo Info(Ctx, Result);
5876 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00005877}
5878
Jay Foad4ba2a172011-01-12 09:06:06 +00005879bool Expr::EvaluateAsBooleanCondition(bool &Result,
5880 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00005881 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00005882 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithb4e85ed2012-01-06 16:39:00 +00005883 HandleConversionToBool(CCValue(const_cast<ASTContext&>(Ctx),
5884 Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00005885 Result);
John McCallcd7a4452010-01-05 23:42:56 +00005886}
5887
Richard Smith80d4b552011-12-28 19:48:30 +00005888bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
5889 SideEffectsKind AllowSideEffects) const {
5890 if (!getType()->isIntegralOrEnumerationType())
5891 return false;
5892
Richard Smithc49bd112011-10-28 17:51:58 +00005893 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00005894 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
5895 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00005896 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005897
Richard Smithc49bd112011-10-28 17:51:58 +00005898 Result = ExprResult.Val.getInt();
5899 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005900}
5901
Jay Foad4ba2a172011-01-12 09:06:06 +00005902bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00005903 EvalInfo Info(Ctx, Result);
5904
John McCallefdb83e2010-05-07 21:00:08 +00005905 LValue LV;
Richard Smith9a17a682011-11-07 05:07:52 +00005906 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005907 CheckLValueConstantExpression(Info, this, LV, Result.Val,
5908 CCEK_Constant);
Eli Friedmanb2f295c2009-09-13 10:17:44 +00005909}
5910
Richard Smith099e7f62011-12-19 06:19:21 +00005911bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
5912 const VarDecl *VD,
5913 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00005914 // FIXME: Evaluating initializers for large array and record types can cause
5915 // performance problems. Only do so in C++11 for now.
5916 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5917 !Ctx.getLangOptions().CPlusPlus0x)
5918 return false;
5919
Richard Smith099e7f62011-12-19 06:19:21 +00005920 Expr::EvalStatus EStatus;
5921 EStatus.Diag = &Notes;
5922
5923 EvalInfo InitInfo(Ctx, EStatus);
5924 InitInfo.setEvaluatingDecl(VD, Value);
5925
Richard Smith51201882011-12-30 21:15:51 +00005926 if (!CheckLiteralType(InitInfo, this))
5927 return false;
5928
Richard Smith099e7f62011-12-19 06:19:21 +00005929 LValue LVal;
5930 LVal.set(VD);
5931
Richard Smith51201882011-12-30 21:15:51 +00005932 // C++11 [basic.start.init]p2:
5933 // Variables with static storage duration or thread storage duration shall be
5934 // zero-initialized before any other initialization takes place.
5935 // This behavior is not present in C.
5936 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
5937 !VD->getType()->isReferenceType()) {
5938 ImplicitValueInitExpr VIE(VD->getType());
5939 if (!EvaluateConstantExpression(Value, InitInfo, LVal, &VIE))
5940 return false;
5941 }
5942
Richard Smith099e7f62011-12-19 06:19:21 +00005943 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
5944 !EStatus.HasSideEffects;
5945}
5946
Richard Smith51f47082011-10-29 00:50:52 +00005947/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
5948/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00005949bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00005950 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00005951 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00005952}
Anders Carlsson51fe9962008-11-22 21:04:56 +00005953
Jay Foad4ba2a172011-01-12 09:06:06 +00005954bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00005955 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00005956}
5957
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005958APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005959 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00005960 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00005961 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00005962 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005963 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00005964
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005965 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00005966}
John McCalld905f5a2010-05-07 05:32:02 +00005967
Abramo Bagnarae17a6432010-05-14 17:07:14 +00005968 bool Expr::EvalResult::isGlobalLValue() const {
5969 assert(Val.isLValue());
5970 return IsGlobalLValue(Val.getLValueBase());
5971 }
5972
5973
John McCalld905f5a2010-05-07 05:32:02 +00005974/// isIntegerConstantExpr - this recursive routine will test if an expression is
5975/// an integer constant expression.
5976
5977/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
5978/// comma, etc
5979///
5980/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
5981/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
5982/// cast+dereference.
5983
5984// CheckICE - This function does the fundamental ICE checking: the returned
5985// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
5986// Note that to reduce code duplication, this helper does no evaluation
5987// itself; the caller checks whether the expression is evaluatable, and
5988// in the rare cases where CheckICE actually cares about the evaluated
5989// value, it calls into Evalute.
5990//
5991// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00005992// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00005993// 1: This expression is not an ICE, but if it isn't evaluated, it's
5994// a legal subexpression for an ICE. This return value is used to handle
5995// the comma operator in C99 mode.
5996// 2: This expression is not an ICE, and is not a legal subexpression for one.
5997
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005998namespace {
5999
John McCalld905f5a2010-05-07 05:32:02 +00006000struct ICEDiag {
6001 unsigned Val;
6002 SourceLocation Loc;
6003
6004 public:
6005 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6006 ICEDiag() : Val(0) {}
6007};
6008
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006009}
6010
6011static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00006012
6013static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6014 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006015 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00006016 !EVResult.Val.isInt()) {
6017 return ICEDiag(2, E->getLocStart());
6018 }
6019 return NoDiag();
6020}
6021
6022static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6023 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00006024 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00006025 return ICEDiag(2, E->getLocStart());
6026 }
6027
6028 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006029#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006030#define STMT(Node, Base) case Expr::Node##Class:
6031#define EXPR(Node, Base)
6032#include "clang/AST/StmtNodes.inc"
6033 case Expr::PredefinedExprClass:
6034 case Expr::FloatingLiteralClass:
6035 case Expr::ImaginaryLiteralClass:
6036 case Expr::StringLiteralClass:
6037 case Expr::ArraySubscriptExprClass:
6038 case Expr::MemberExprClass:
6039 case Expr::CompoundAssignOperatorClass:
6040 case Expr::CompoundLiteralExprClass:
6041 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006042 case Expr::DesignatedInitExprClass:
6043 case Expr::ImplicitValueInitExprClass:
6044 case Expr::ParenListExprClass:
6045 case Expr::VAArgExprClass:
6046 case Expr::AddrLabelExprClass:
6047 case Expr::StmtExprClass:
6048 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006049 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006050 case Expr::CXXDynamicCastExprClass:
6051 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006052 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006053 case Expr::CXXNullPtrLiteralExprClass:
6054 case Expr::CXXThisExprClass:
6055 case Expr::CXXThrowExprClass:
6056 case Expr::CXXNewExprClass:
6057 case Expr::CXXDeleteExprClass:
6058 case Expr::CXXPseudoDestructorExprClass:
6059 case Expr::UnresolvedLookupExprClass:
6060 case Expr::DependentScopeDeclRefExprClass:
6061 case Expr::CXXConstructExprClass:
6062 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006063 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006064 case Expr::CXXTemporaryObjectExprClass:
6065 case Expr::CXXUnresolvedConstructExprClass:
6066 case Expr::CXXDependentScopeMemberExprClass:
6067 case Expr::UnresolvedMemberExprClass:
6068 case Expr::ObjCStringLiteralClass:
6069 case Expr::ObjCEncodeExprClass:
6070 case Expr::ObjCMessageExprClass:
6071 case Expr::ObjCSelectorExprClass:
6072 case Expr::ObjCProtocolExprClass:
6073 case Expr::ObjCIvarRefExprClass:
6074 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006075 case Expr::ObjCIsaExprClass:
6076 case Expr::ShuffleVectorExprClass:
6077 case Expr::BlockExprClass:
6078 case Expr::BlockDeclRefExprClass:
6079 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006080 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006081 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006082 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006083 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006084 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006085 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006086 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006087 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006088 case Expr::InitListExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006089 return ICEDiag(2, E->getLocStart());
6090
Douglas Gregoree8aff02011-01-04 17:33:58 +00006091 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006092 case Expr::GNUNullExprClass:
6093 // GCC considers the GNU __null value to be an integral constant expression.
6094 return NoDiag();
6095
John McCall91a57552011-07-15 05:09:51 +00006096 case Expr::SubstNonTypeTemplateParmExprClass:
6097 return
6098 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6099
John McCalld905f5a2010-05-07 05:32:02 +00006100 case Expr::ParenExprClass:
6101 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006102 case Expr::GenericSelectionExprClass:
6103 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006104 case Expr::IntegerLiteralClass:
6105 case Expr::CharacterLiteralClass:
6106 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006107 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006108 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006109 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006110 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006111 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006112 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006113 return NoDiag();
6114 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006115 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006116 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6117 // constant expressions, but they can never be ICEs because an ICE cannot
6118 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006119 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006120 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006121 return CheckEvalInICE(E, Ctx);
6122 return ICEDiag(2, E->getLocStart());
6123 }
6124 case Expr::DeclRefExprClass:
6125 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6126 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00006127 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006128 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
6129
6130 // Parameter variables are never constants. Without this check,
6131 // getAnyInitializer() can find a default argument, which leads
6132 // to chaos.
6133 if (isa<ParmVarDecl>(D))
6134 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6135
6136 // C++ 7.1.5.1p2
6137 // A variable of non-volatile const-qualified integral or enumeration
6138 // type initialized by an ICE can be used in ICEs.
6139 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006140 if (!Dcl->getType()->isIntegralOrEnumerationType())
6141 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6142
Richard Smith099e7f62011-12-19 06:19:21 +00006143 const VarDecl *VD;
6144 // Look for a declaration of this variable that has an initializer, and
6145 // check whether it is an ICE.
6146 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6147 return NoDiag();
6148 else
6149 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006150 }
6151 }
6152 return ICEDiag(2, E->getLocStart());
6153 case Expr::UnaryOperatorClass: {
6154 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6155 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006156 case UO_PostInc:
6157 case UO_PostDec:
6158 case UO_PreInc:
6159 case UO_PreDec:
6160 case UO_AddrOf:
6161 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006162 // C99 6.6/3 allows increment and decrement within unevaluated
6163 // subexpressions of constant expressions, but they can never be ICEs
6164 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006165 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006166 case UO_Extension:
6167 case UO_LNot:
6168 case UO_Plus:
6169 case UO_Minus:
6170 case UO_Not:
6171 case UO_Real:
6172 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006173 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006174 }
6175
6176 // OffsetOf falls through here.
6177 }
6178 case Expr::OffsetOfExprClass: {
6179 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00006180 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00006181 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00006182 // compliance: we should warn earlier for offsetof expressions with
6183 // array subscripts that aren't ICEs, and if the array subscripts
6184 // are ICEs, the value of the offsetof must be an integer constant.
6185 return CheckEvalInICE(E, Ctx);
6186 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006187 case Expr::UnaryExprOrTypeTraitExprClass: {
6188 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6189 if ((Exp->getKind() == UETT_SizeOf) &&
6190 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00006191 return ICEDiag(2, E->getLocStart());
6192 return NoDiag();
6193 }
6194 case Expr::BinaryOperatorClass: {
6195 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6196 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006197 case BO_PtrMemD:
6198 case BO_PtrMemI:
6199 case BO_Assign:
6200 case BO_MulAssign:
6201 case BO_DivAssign:
6202 case BO_RemAssign:
6203 case BO_AddAssign:
6204 case BO_SubAssign:
6205 case BO_ShlAssign:
6206 case BO_ShrAssign:
6207 case BO_AndAssign:
6208 case BO_XorAssign:
6209 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006210 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6211 // constant expressions, but they can never be ICEs because an ICE cannot
6212 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006213 return ICEDiag(2, E->getLocStart());
6214
John McCall2de56d12010-08-25 11:45:40 +00006215 case BO_Mul:
6216 case BO_Div:
6217 case BO_Rem:
6218 case BO_Add:
6219 case BO_Sub:
6220 case BO_Shl:
6221 case BO_Shr:
6222 case BO_LT:
6223 case BO_GT:
6224 case BO_LE:
6225 case BO_GE:
6226 case BO_EQ:
6227 case BO_NE:
6228 case BO_And:
6229 case BO_Xor:
6230 case BO_Or:
6231 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006232 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6233 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006234 if (Exp->getOpcode() == BO_Div ||
6235 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006236 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006237 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006238 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006239 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006240 if (REval == 0)
6241 return ICEDiag(1, E->getLocStart());
6242 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006243 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006244 if (LEval.isMinSignedValue())
6245 return ICEDiag(1, E->getLocStart());
6246 }
6247 }
6248 }
John McCall2de56d12010-08-25 11:45:40 +00006249 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00006250 if (Ctx.getLangOptions().C99) {
6251 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6252 // if it isn't evaluated.
6253 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6254 return ICEDiag(1, E->getLocStart());
6255 } else {
6256 // In both C89 and C++, commas in ICEs are illegal.
6257 return ICEDiag(2, E->getLocStart());
6258 }
6259 }
6260 if (LHSResult.Val >= RHSResult.Val)
6261 return LHSResult;
6262 return RHSResult;
6263 }
John McCall2de56d12010-08-25 11:45:40 +00006264 case BO_LAnd:
6265 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006266 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6267 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6268 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6269 // Rare case where the RHS has a comma "side-effect"; we need
6270 // to actually check the condition to see whether the side
6271 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006272 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006273 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006274 return RHSResult;
6275 return NoDiag();
6276 }
6277
6278 if (LHSResult.Val >= RHSResult.Val)
6279 return LHSResult;
6280 return RHSResult;
6281 }
6282 }
6283 }
6284 case Expr::ImplicitCastExprClass:
6285 case Expr::CStyleCastExprClass:
6286 case Expr::CXXFunctionalCastExprClass:
6287 case Expr::CXXStaticCastExprClass:
6288 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006289 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006290 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006291 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006292 if (isa<ExplicitCastExpr>(E)) {
6293 if (const FloatingLiteral *FL
6294 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6295 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6296 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6297 APSInt IgnoredVal(DestWidth, !DestSigned);
6298 bool Ignored;
6299 // If the value does not fit in the destination type, the behavior is
6300 // undefined, so we are not required to treat it as a constant
6301 // expression.
6302 if (FL->getValue().convertToInteger(IgnoredVal,
6303 llvm::APFloat::rmTowardZero,
6304 &Ignored) & APFloat::opInvalidOp)
6305 return ICEDiag(2, E->getLocStart());
6306 return NoDiag();
6307 }
6308 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006309 switch (cast<CastExpr>(E)->getCastKind()) {
6310 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006311 case CK_AtomicToNonAtomic:
6312 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006313 case CK_NoOp:
6314 case CK_IntegralToBoolean:
6315 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006316 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006317 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006318 return ICEDiag(2, E->getLocStart());
6319 }
John McCalld905f5a2010-05-07 05:32:02 +00006320 }
John McCall56ca35d2011-02-17 10:25:35 +00006321 case Expr::BinaryConditionalOperatorClass: {
6322 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6323 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6324 if (CommonResult.Val == 2) return CommonResult;
6325 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6326 if (FalseResult.Val == 2) return FalseResult;
6327 if (CommonResult.Val == 1) return CommonResult;
6328 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006329 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006330 return FalseResult;
6331 }
John McCalld905f5a2010-05-07 05:32:02 +00006332 case Expr::ConditionalOperatorClass: {
6333 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6334 // If the condition (ignoring parens) is a __builtin_constant_p call,
6335 // then only the true side is actually considered in an integer constant
6336 // expression, and it is fully evaluated. This is an important GNU
6337 // extension. See GCC PR38377 for discussion.
6338 if (const CallExpr *CallCE
6339 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006340 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6341 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006342 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006343 if (CondResult.Val == 2)
6344 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006345
Richard Smithf48fdb02011-12-09 22:58:01 +00006346 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6347 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006348
John McCalld905f5a2010-05-07 05:32:02 +00006349 if (TrueResult.Val == 2)
6350 return TrueResult;
6351 if (FalseResult.Val == 2)
6352 return FalseResult;
6353 if (CondResult.Val == 1)
6354 return CondResult;
6355 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6356 return NoDiag();
6357 // Rare case where the diagnostics depend on which side is evaluated
6358 // Note that if we get here, CondResult is 0, and at least one of
6359 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006360 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006361 return FalseResult;
6362 }
6363 return TrueResult;
6364 }
6365 case Expr::CXXDefaultArgExprClass:
6366 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6367 case Expr::ChooseExprClass: {
6368 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6369 }
6370 }
6371
David Blaikie30263482012-01-20 21:50:17 +00006372 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006373}
6374
Richard Smithf48fdb02011-12-09 22:58:01 +00006375/// Evaluate an expression as a C++11 integral constant expression.
6376static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6377 const Expr *E,
6378 llvm::APSInt *Value,
6379 SourceLocation *Loc) {
6380 if (!E->getType()->isIntegralOrEnumerationType()) {
6381 if (Loc) *Loc = E->getExprLoc();
6382 return false;
6383 }
6384
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006385 APValue Result;
6386 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006387 return false;
6388
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006389 assert(Result.isInt() && "pointer cast to int is not an ICE");
6390 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006391 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006392}
6393
Richard Smithdd1f29b2011-12-12 09:28:41 +00006394bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00006395 if (Ctx.getLangOptions().CPlusPlus0x)
6396 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6397
John McCalld905f5a2010-05-07 05:32:02 +00006398 ICEDiag d = CheckICE(this, Ctx);
6399 if (d.Val != 0) {
6400 if (Loc) *Loc = d.Loc;
6401 return false;
6402 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006403 return true;
6404}
6405
6406bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6407 SourceLocation *Loc, bool isEvaluated) const {
6408 if (Ctx.getLangOptions().CPlusPlus0x)
6409 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6410
6411 if (!isIntegerConstantExpr(Ctx, Loc))
6412 return false;
6413 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006414 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006415 return true;
6416}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006417
6418bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6419 SourceLocation *Loc) const {
6420 // We support this checking in C++98 mode in order to diagnose compatibility
6421 // issues.
6422 assert(Ctx.getLangOptions().CPlusPlus);
6423
6424 Expr::EvalStatus Status;
6425 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6426 Status.Diag = &Diags;
6427 EvalInfo Info(Ctx, Status);
6428
6429 APValue Scratch;
6430 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6431
6432 if (!Diags.empty()) {
6433 IsConstExpr = false;
6434 if (Loc) *Loc = Diags[0].first;
6435 } else if (!IsConstExpr) {
6436 // FIXME: This shouldn't happen.
6437 if (Loc) *Loc = getExprLoc();
6438 }
6439
6440 return IsConstExpr;
6441}
Richard Smith745f5142012-01-27 01:14:48 +00006442
6443bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6444 llvm::SmallVectorImpl<
6445 PartialDiagnosticAt> &Diags) {
6446 // FIXME: It would be useful to check constexpr function templates, but at the
6447 // moment the constant expression evaluator cannot cope with the non-rigorous
6448 // ASTs which we build for dependent expressions.
6449 if (FD->isDependentContext())
6450 return true;
6451
6452 Expr::EvalStatus Status;
6453 Status.Diag = &Diags;
6454
6455 EvalInfo Info(FD->getASTContext(), Status);
6456 Info.CheckingPotentialConstantExpression = true;
6457
6458 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6459 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6460
6461 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6462 // is a temporary being used as the 'this' pointer.
6463 LValue This;
6464 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
6465 This.set(&VIE, Info.CurrentCall);
6466
6467 APValue Scratch;
6468 ArrayRef<const Expr*> Args;
6469
6470 SourceLocation Loc = FD->getLocation();
6471
6472 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
6473 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
6474 } else
6475 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6476 Args, FD->getBody(), Info, Scratch);
6477
6478 return Diags.empty();
6479}