blob: 1a396e142544150e1a13129ae2788a17de00b209 [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
Richard Smith745f5142012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
26// (under the C++11 rules only, at the moment), or, if folding failed too,
27// why the expression could not be folded.
28//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlssonc44eec62008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000038#include "clang/AST/CharUnits.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000039#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000040#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000041#include "clang/AST/TypeLoc.h"
Chris Lattner500d3292009-01-29 05:15:15 +000042#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000043#include "clang/AST/Expr.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000044#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000045#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000046#include "llvm/ADT/SmallString.h"
Mike Stump4572bab2009-05-30 03:56:50 +000047#include <cstring>
Richard Smith7b48a292012-02-01 05:53:12 +000048#include <functional>
Mike Stump4572bab2009-05-30 03:56:50 +000049
Anders Carlssonc44eec62008-07-03 04:20:39 +000050using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000051using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000052using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000053
Richard Smith83587db2012-02-15 02:18:13 +000054static bool IsGlobalLValue(APValue::LValueBase B);
55
John McCallf4cf1a12010-05-07 17:22:02 +000056namespace {
Richard Smith180f4792011-11-10 06:34:14 +000057 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000058 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000059 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000060
Richard Smith83587db2012-02-15 02:18:13 +000061 static QualType getType(APValue::LValueBase B) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +000062 if (!B) return QualType();
63 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
64 return D->getType();
65 return B.get<const Expr*>()->getType();
66 }
67
Richard Smith180f4792011-11-10 06:34:14 +000068 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smithf15fda02012-02-02 01:16:57 +000069 /// field or base class.
Richard Smith83587db2012-02-15 02:18:13 +000070 static
Richard Smithf15fda02012-02-02 01:16:57 +000071 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smith180f4792011-11-10 06:34:14 +000072 APValue::BaseOrMemberType Value;
73 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smithf15fda02012-02-02 01:16:57 +000074 return Value;
75 }
76
77 /// Get an LValue path entry, which is known to not be an array index, as a
78 /// field declaration.
Richard Smith83587db2012-02-15 02:18:13 +000079 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000080 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000081 }
82 /// Get an LValue path entry, which is known to not be an array index, as a
83 /// base class declaration.
Richard Smith83587db2012-02-15 02:18:13 +000084 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000085 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000086 }
87 /// Determine whether this LValue path entry for a base class names a virtual
88 /// base class.
Richard Smith83587db2012-02-15 02:18:13 +000089 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000090 return getAsBaseOrMember(E).getInt();
Richard Smith180f4792011-11-10 06:34:14 +000091 }
92
Richard Smithb4e85ed2012-01-06 16:39:00 +000093 /// Find the path length and type of the most-derived subobject in the given
94 /// path, and find the size of the containing array, if any.
95 static
96 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
97 ArrayRef<APValue::LValuePathEntry> Path,
98 uint64_t &ArraySize, QualType &Type) {
99 unsigned MostDerivedLength = 0;
100 Type = Base;
Richard Smith9a17a682011-11-07 05:07:52 +0000101 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000102 if (Type->isArrayType()) {
103 const ConstantArrayType *CAT =
104 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
105 Type = CAT->getElementType();
106 ArraySize = CAT->getSize().getZExtValue();
107 MostDerivedLength = I + 1;
108 } else if (const FieldDecl *FD = getAsField(Path[I])) {
109 Type = FD->getType();
110 ArraySize = 0;
111 MostDerivedLength = I + 1;
112 } else {
Richard Smith9a17a682011-11-07 05:07:52 +0000113 // Path[I] describes a base class.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000114 ArraySize = 0;
115 }
Richard Smith9a17a682011-11-07 05:07:52 +0000116 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000117 return MostDerivedLength;
Richard Smith9a17a682011-11-07 05:07:52 +0000118 }
119
Richard Smithb4e85ed2012-01-06 16:39:00 +0000120 // The order of this enum is important for diagnostics.
121 enum CheckSubobjectKind {
Richard Smithb04035a2012-02-01 02:39:43 +0000122 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
123 CSK_This
Richard Smithb4e85ed2012-01-06 16:39:00 +0000124 };
125
Richard Smith0a3bdb62011-11-04 02:25:55 +0000126 /// A path from a glvalue to a subobject of that glvalue.
127 struct SubobjectDesignator {
128 /// True if the subobject was named in a manner not supported by C++11. Such
129 /// lvalues can still be folded, but they are not core constant expressions
130 /// and we cannot perform lvalue-to-rvalue conversions on them.
131 bool Invalid : 1;
132
Richard Smithb4e85ed2012-01-06 16:39:00 +0000133 /// Is this a pointer one past the end of an object?
134 bool IsOnePastTheEnd : 1;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000135
Richard Smithb4e85ed2012-01-06 16:39:00 +0000136 /// The length of the path to the most-derived object of which this is a
137 /// subobject.
138 unsigned MostDerivedPathLength : 30;
139
140 /// The size of the array of which the most-derived object is an element, or
141 /// 0 if the most-derived object is not an array element.
142 uint64_t MostDerivedArraySize;
143
144 /// The type of the most derived object referred to by this address.
145 QualType MostDerivedType;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000146
Richard Smith9a17a682011-11-07 05:07:52 +0000147 typedef APValue::LValuePathEntry PathEntry;
148
Richard Smith0a3bdb62011-11-04 02:25:55 +0000149 /// The entries on the path from the glvalue to the designated subobject.
150 SmallVector<PathEntry, 8> Entries;
151
Richard Smithb4e85ed2012-01-06 16:39:00 +0000152 SubobjectDesignator() : Invalid(true) {}
Richard Smith0a3bdb62011-11-04 02:25:55 +0000153
Richard Smithb4e85ed2012-01-06 16:39:00 +0000154 explicit SubobjectDesignator(QualType T)
155 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
156 MostDerivedArraySize(0), MostDerivedType(T) {}
157
158 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
159 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
160 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith9a17a682011-11-07 05:07:52 +0000161 if (!Invalid) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000162 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000163 ArrayRef<PathEntry> VEntries = V.getLValuePath();
164 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
165 if (V.getLValueBase())
Richard Smithb4e85ed2012-01-06 16:39:00 +0000166 MostDerivedPathLength =
167 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
168 V.getLValuePath(), MostDerivedArraySize,
169 MostDerivedType);
Richard Smith9a17a682011-11-07 05:07:52 +0000170 }
171 }
172
Richard Smith0a3bdb62011-11-04 02:25:55 +0000173 void setInvalid() {
174 Invalid = true;
175 Entries.clear();
176 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000177
178 /// Determine whether this is a one-past-the-end pointer.
179 bool isOnePastTheEnd() const {
180 if (IsOnePastTheEnd)
181 return true;
182 if (MostDerivedArraySize &&
183 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
184 return true;
185 return false;
186 }
187
188 /// Check that this refers to a valid subobject.
189 bool isValidSubobject() const {
190 if (Invalid)
191 return false;
192 return !isOnePastTheEnd();
193 }
194 /// Check that this refers to a valid subobject, and if not, produce a
195 /// relevant diagnostic and set the designator as invalid.
196 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
197
198 /// Update this designator to refer to the first element within this array.
199 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000200 PathEntry Entry;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000201 Entry.ArrayIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000202 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000203
204 // This is a most-derived object.
205 MostDerivedType = CAT->getElementType();
206 MostDerivedArraySize = CAT->getSize().getZExtValue();
207 MostDerivedPathLength = Entries.size();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000208 }
209 /// Update this designator to refer to the given base or member of this
210 /// object.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000211 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000212 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000213 APValue::BaseOrMemberType Value(D, Virtual);
214 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000215 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000216
217 // If this isn't a base class, it's a new most-derived object.
218 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
219 MostDerivedType = FD->getType();
220 MostDerivedArraySize = 0;
221 MostDerivedPathLength = Entries.size();
222 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000223 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000224 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000225 /// Add N to the address of this subobject.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000226 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000227 if (Invalid) return;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000228 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith9a17a682011-11-07 05:07:52 +0000229 Entries.back().ArrayIndex += N;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000230 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
231 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
232 setInvalid();
233 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000234 return;
235 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000236 // [expr.add]p4: For the purposes of these operators, a pointer to a
237 // nonarray object behaves the same as a pointer to the first element of
238 // an array of length one with the type of the object as its element type.
239 if (IsOnePastTheEnd && N == (uint64_t)-1)
240 IsOnePastTheEnd = false;
241 else if (!IsOnePastTheEnd && N == 1)
242 IsOnePastTheEnd = true;
243 else if (N != 0) {
244 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000245 setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000246 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000247 }
248 };
249
Richard Smith47a1eed2011-10-29 20:57:55 +0000250 /// A core constant value. This can be the value of any constant expression,
251 /// or a pointer or reference to a non-static object or function parameter.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000252 ///
253 /// For an LValue, the base and offset are stored in the APValue subobject,
254 /// but the other information is stored in the SubobjectDesignator. For all
255 /// other value kinds, the value is stored directly in the APValue subobject.
Richard Smith47a1eed2011-10-29 20:57:55 +0000256 class CCValue : public APValue {
257 typedef llvm::APSInt APSInt;
258 typedef llvm::APFloat APFloat;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000259 /// If the value is a reference or pointer, this is a description of how the
260 /// subobject was specified.
261 SubobjectDesignator Designator;
Richard Smith47a1eed2011-10-29 20:57:55 +0000262 public:
Richard Smith177dce72011-11-01 16:57:24 +0000263 struct GlobalValue {};
264
Richard Smith47a1eed2011-10-29 20:57:55 +0000265 CCValue() {}
266 explicit CCValue(const APSInt &I) : APValue(I) {}
267 explicit CCValue(const APFloat &F) : APValue(F) {}
268 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
269 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
270 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smith83587db2012-02-15 02:18:13 +0000271 CCValue(const CCValue &V) : APValue(V), Designator(V.Designator) {}
272 CCValue(LValueBase B, const CharUnits &O, unsigned I,
Richard Smith0a3bdb62011-11-04 02:25:55 +0000273 const SubobjectDesignator &D) :
Richard Smith83587db2012-02-15 02:18:13 +0000274 APValue(B, O, APValue::NoLValuePath(), I), Designator(D) {}
Richard Smithb4e85ed2012-01-06 16:39:00 +0000275 CCValue(ASTContext &Ctx, const APValue &V, GlobalValue) :
Richard Smith83587db2012-02-15 02:18:13 +0000276 APValue(V), Designator(Ctx, V) {
277 }
Richard Smithe24f5fc2011-11-17 22:56:20 +0000278 CCValue(const ValueDecl *D, bool IsDerivedMember,
279 ArrayRef<const CXXRecordDecl*> Path) :
280 APValue(D, IsDerivedMember, Path) {}
Eli Friedman65639282012-01-04 23:13:47 +0000281 CCValue(const AddrLabelExpr* LHSExpr, const AddrLabelExpr* RHSExpr) :
282 APValue(LHSExpr, RHSExpr) {}
Richard Smith47a1eed2011-10-29 20:57:55 +0000283
Richard Smith0a3bdb62011-11-04 02:25:55 +0000284 SubobjectDesignator &getLValueDesignator() {
285 assert(getKind() == LValue);
286 return Designator;
287 }
288 const SubobjectDesignator &getLValueDesignator() const {
289 return const_cast<CCValue*>(this)->getLValueDesignator();
290 }
Richard Smith83587db2012-02-15 02:18:13 +0000291 APValue toAPValue() const {
292 if (!isLValue())
293 return *this;
294
295 if (Designator.Invalid) {
296 // This is not a core constant expression. An appropriate diagnostic
297 // will have already been produced.
298 return APValue(getLValueBase(), getLValueOffset(),
299 APValue::NoLValuePath(), getLValueCallIndex());
300 }
301
302 return APValue(getLValueBase(), getLValueOffset(),
303 Designator.Entries, Designator.IsOnePastTheEnd,
304 getLValueCallIndex());
305 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000306 };
307
Richard Smithd0dccea2011-10-28 22:34:42 +0000308 /// A stack frame in the constexpr call stack.
309 struct CallStackFrame {
310 EvalInfo &Info;
311
312 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000313 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000314
Richard Smith08d6e032011-12-16 19:06:07 +0000315 /// CallLoc - The location of the call expression for this call.
316 SourceLocation CallLoc;
317
318 /// Callee - The function which was called.
319 const FunctionDecl *Callee;
320
Richard Smith83587db2012-02-15 02:18:13 +0000321 /// Index - The call index of this call.
322 unsigned Index;
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 Smith83587db2012-02-15 02:18:13 +0000376 /// EvalInfo - This is a private struct used by the evaluator to capture
377 /// information about a subexpression as it is folded. It retains information
378 /// about the AST context, but also maintains information about the folded
379 /// expression.
380 ///
381 /// If an expression could be evaluated, it is still possible it is not a C
382 /// "integer constant expression" or constant expression. If not, this struct
383 /// captures information about how and why not.
384 ///
385 /// One bit of information passed *into* the request for constant folding
386 /// indicates whether the subexpression is "evaluated" or not according to C
387 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
388 /// evaluate the expression regardless of what the RHS is, but C only allows
389 /// certain things in certain situations.
Richard Smithbd552ef2011-10-31 05:52:43 +0000390 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000391 ASTContext &Ctx;
Richard Smithbd552ef2011-10-31 05:52:43 +0000392
393 /// EvalStatus - Contains information about the evaluation.
394 Expr::EvalStatus &EvalStatus;
395
396 /// CurrentCall - The top of the constexpr call stack.
397 CallStackFrame *CurrentCall;
398
Richard Smithbd552ef2011-10-31 05:52:43 +0000399 /// CallStackDepth - The number of calls in the call stack right now.
400 unsigned CallStackDepth;
401
Richard Smith83587db2012-02-15 02:18:13 +0000402 /// NextCallIndex - The next call index to assign.
403 unsigned NextCallIndex;
404
Richard Smithbd552ef2011-10-31 05:52:43 +0000405 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
406 /// OpaqueValues - Values used as the common expression in a
407 /// BinaryConditionalOperator.
408 MapTy OpaqueValues;
409
410 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000411 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000412 CallStackFrame BottomFrame;
413
Richard Smith180f4792011-11-10 06:34:14 +0000414 /// EvaluatingDecl - This is the declaration whose initializer is being
415 /// evaluated, if any.
416 const VarDecl *EvaluatingDecl;
417
418 /// EvaluatingDeclValue - This is the value being constructed for the
419 /// declaration whose initializer is being evaluated, if any.
420 APValue *EvaluatingDeclValue;
421
Richard Smithc1c5f272011-12-13 06:39:58 +0000422 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
423 /// notes attached to it will also be stored, otherwise they will not be.
424 bool HasActiveDiagnostic;
425
Richard Smith745f5142012-01-27 01:14:48 +0000426 /// CheckingPotentialConstantExpression - Are we checking whether the
427 /// expression is a potential constant expression? If so, some diagnostics
428 /// are suppressed.
429 bool CheckingPotentialConstantExpression;
430
Richard Smithbd552ef2011-10-31 05:52:43 +0000431
432 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000433 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith83587db2012-02-15 02:18:13 +0000434 CallStackDepth(0), NextCallIndex(1),
435 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith745f5142012-01-27 01:14:48 +0000436 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
437 CheckingPotentialConstantExpression(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000438
Richard Smithbd552ef2011-10-31 05:52:43 +0000439 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
440 MapTy::const_iterator i = OpaqueValues.find(e);
441 if (i == OpaqueValues.end()) return 0;
442 return &i->second;
443 }
444
Richard Smith180f4792011-11-10 06:34:14 +0000445 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
446 EvaluatingDecl = VD;
447 EvaluatingDeclValue = &Value;
448 }
449
Richard Smithc18c4232011-11-21 19:36:32 +0000450 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
451
Richard Smithc1c5f272011-12-13 06:39:58 +0000452 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000453 // Don't perform any constexpr calls (other than the call we're checking)
454 // when checking a potential constant expression.
455 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
456 return false;
Richard Smith83587db2012-02-15 02:18:13 +0000457 if (NextCallIndex == 0) {
458 // NextCallIndex has wrapped around.
459 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
460 return false;
461 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000462 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
463 return true;
464 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
465 << getLangOpts().ConstexprCallDepth;
466 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000467 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000468
Richard Smith83587db2012-02-15 02:18:13 +0000469 CallStackFrame *getCallFrame(unsigned CallIndex) {
470 assert(CallIndex && "no call index in getCallFrame");
471 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
472 // be null in this loop.
473 CallStackFrame *Frame = CurrentCall;
474 while (Frame->Index > CallIndex)
475 Frame = Frame->Caller;
476 return (Frame->Index == CallIndex) ? Frame : 0;
477 }
478
Richard Smithc1c5f272011-12-13 06:39:58 +0000479 private:
480 /// Add a diagnostic to the diagnostics list.
481 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
482 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
483 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
484 return EvalStatus.Diag->back().second;
485 }
486
Richard Smith08d6e032011-12-16 19:06:07 +0000487 /// Add notes containing a call stack to the current point of evaluation.
488 void addCallStack(unsigned Limit);
489
Richard Smithc1c5f272011-12-13 06:39:58 +0000490 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000491 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000492 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
493 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000494 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000495 // If we have a prior diagnostic, it will be noting that the expression
496 // isn't a constant expression. This diagnostic is more important.
497 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000498 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000499 unsigned CallStackNotes = CallStackDepth - 1;
500 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
501 if (Limit)
502 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000503 if (CheckingPotentialConstantExpression)
504 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000505
Richard Smithc1c5f272011-12-13 06:39:58 +0000506 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000507 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000508 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
509 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000510 if (!CheckingPotentialConstantExpression)
511 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000512 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000513 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000514 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000515 return OptionalDiagnostic();
516 }
517
518 /// Diagnose that the evaluation does not produce a C++11 core constant
519 /// expression.
Richard Smith7098cbd2011-12-21 05:04:46 +0000520 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
521 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000522 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000523 // Don't override a previous diagnostic.
524 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
525 return OptionalDiagnostic();
Richard Smithc1c5f272011-12-13 06:39:58 +0000526 return Diag(Loc, DiagId, ExtraNotes);
527 }
528
529 /// Add a note to a prior diagnostic.
530 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
531 if (!HasActiveDiagnostic)
532 return OptionalDiagnostic();
533 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000534 }
Richard Smith099e7f62011-12-19 06:19:21 +0000535
536 /// Add a stack of notes to a prior diagnostic.
537 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
538 if (HasActiveDiagnostic) {
539 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
540 Diags.begin(), Diags.end());
541 }
542 }
Richard Smith745f5142012-01-27 01:14:48 +0000543
544 /// Should we continue evaluation as much as possible after encountering a
545 /// construct which can't be folded?
546 bool keepEvaluatingAfterFailure() {
Richard Smith74e1ad92012-02-16 02:46:34 +0000547 return CheckingPotentialConstantExpression &&
548 EvalStatus.Diag && EvalStatus.Diag->empty();
Richard Smith745f5142012-01-27 01:14:48 +0000549 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000550 };
Richard Smithf15fda02012-02-02 01:16:57 +0000551
552 /// Object used to treat all foldable expressions as constant expressions.
553 struct FoldConstant {
554 bool Enabled;
555
556 explicit FoldConstant(EvalInfo &Info)
557 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
558 !Info.EvalStatus.HasSideEffects) {
559 }
560 // Treat the value we've computed since this object was created as constant.
561 void Fold(EvalInfo &Info) {
562 if (Enabled && !Info.EvalStatus.Diag->empty() &&
563 !Info.EvalStatus.HasSideEffects)
564 Info.EvalStatus.Diag->clear();
565 }
566 };
Richard Smith74e1ad92012-02-16 02:46:34 +0000567
568 /// RAII object used to suppress diagnostics and side-effects from a
569 /// speculative evaluation.
570 class SpeculativeEvaluationRAII {
571 EvalInfo &Info;
572 Expr::EvalStatus Old;
573
574 public:
575 SpeculativeEvaluationRAII(EvalInfo &Info,
576 llvm::SmallVectorImpl<PartialDiagnosticAt>
577 *NewDiag = 0)
578 : Info(Info), Old(Info.EvalStatus) {
579 Info.EvalStatus.Diag = NewDiag;
580 }
581 ~SpeculativeEvaluationRAII() {
582 Info.EvalStatus = Old;
583 }
584 };
Richard Smith08d6e032011-12-16 19:06:07 +0000585}
Richard Smithbd552ef2011-10-31 05:52:43 +0000586
Richard Smithb4e85ed2012-01-06 16:39:00 +0000587bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
588 CheckSubobjectKind CSK) {
589 if (Invalid)
590 return false;
591 if (isOnePastTheEnd()) {
592 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_past_end_subobject)
593 << CSK;
594 setInvalid();
595 return false;
596 }
597 return true;
598}
599
600void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
601 const Expr *E, uint64_t N) {
602 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
603 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
604 << static_cast<int>(N) << /*array*/ 0
605 << static_cast<unsigned>(MostDerivedArraySize);
606 else
607 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
608 << static_cast<int>(N) << /*non-array*/ 1;
609 setInvalid();
610}
611
Richard Smith08d6e032011-12-16 19:06:07 +0000612CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
613 const FunctionDecl *Callee, const LValue *This,
614 const CCValue *Arguments)
615 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smith83587db2012-02-15 02:18:13 +0000616 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smith08d6e032011-12-16 19:06:07 +0000617 Info.CurrentCall = this;
618 ++Info.CallStackDepth;
619}
620
621CallStackFrame::~CallStackFrame() {
622 assert(Info.CurrentCall == this && "calls retired out of order");
623 --Info.CallStackDepth;
624 Info.CurrentCall = Caller;
625}
626
627/// Produce a string describing the given constexpr call.
628static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
629 unsigned ArgIndex = 0;
630 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith5ba73e12012-02-04 00:33:54 +0000631 !isa<CXXConstructorDecl>(Frame->Callee) &&
632 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smith08d6e032011-12-16 19:06:07 +0000633
634 if (!IsMemberCall)
635 Out << *Frame->Callee << '(';
636
637 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
638 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumi5fe31222012-01-26 09:37:36 +0000639 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smith08d6e032011-12-16 19:06:07 +0000640 Out << ", ";
641
642 const ParmVarDecl *Param = *I;
643 const CCValue &Arg = Frame->Arguments[ArgIndex];
644 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
645 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
646 else {
Richard Smith83587db2012-02-15 02:18:13 +0000647 // Convert the CCValue to an APValue without checking for constantness.
Richard Smith08d6e032011-12-16 19:06:07 +0000648 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
649 Arg.getLValueDesignator().Entries,
Richard Smith83587db2012-02-15 02:18:13 +0000650 Arg.getLValueDesignator().IsOnePastTheEnd,
651 Arg.getLValueCallIndex());
Richard Smith08d6e032011-12-16 19:06:07 +0000652 Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
653 }
654
655 if (ArgIndex == 0 && IsMemberCall)
656 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000657 }
658
Richard Smith08d6e032011-12-16 19:06:07 +0000659 Out << ')';
660}
661
662void EvalInfo::addCallStack(unsigned Limit) {
663 // Determine which calls to skip, if any.
664 unsigned ActiveCalls = CallStackDepth - 1;
665 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
666 if (Limit && Limit < ActiveCalls) {
667 SkipStart = Limit / 2 + Limit % 2;
668 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000669 }
670
Richard Smith08d6e032011-12-16 19:06:07 +0000671 // Walk the call stack and add the diagnostics.
672 unsigned CallIdx = 0;
673 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
674 Frame = Frame->Caller, ++CallIdx) {
675 // Skip this call?
676 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
677 if (CallIdx == SkipStart) {
678 // Note that we're skipping calls.
679 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
680 << unsigned(ActiveCalls - Limit);
681 }
682 continue;
683 }
684
685 llvm::SmallVector<char, 128> Buffer;
686 llvm::raw_svector_ostream Out(Buffer);
687 describeCall(Frame, Out);
688 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
689 }
690}
691
692namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000693 struct ComplexValue {
694 private:
695 bool IsInt;
696
697 public:
698 APSInt IntReal, IntImag;
699 APFloat FloatReal, FloatImag;
700
701 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
702
703 void makeComplexFloat() { IsInt = false; }
704 bool isComplexFloat() const { return !IsInt; }
705 APFloat &getComplexFloatReal() { return FloatReal; }
706 APFloat &getComplexFloatImag() { return FloatImag; }
707
708 void makeComplexInt() { IsInt = true; }
709 bool isComplexInt() const { return IsInt; }
710 APSInt &getComplexIntReal() { return IntReal; }
711 APSInt &getComplexIntImag() { return IntImag; }
712
Richard Smith47a1eed2011-10-29 20:57:55 +0000713 void moveInto(CCValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000714 if (isComplexFloat())
Richard Smith47a1eed2011-10-29 20:57:55 +0000715 v = CCValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000716 else
Richard Smith47a1eed2011-10-29 20:57:55 +0000717 v = CCValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000718 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000719 void setFrom(const CCValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000720 assert(v.isComplexFloat() || v.isComplexInt());
721 if (v.isComplexFloat()) {
722 makeComplexFloat();
723 FloatReal = v.getComplexFloatReal();
724 FloatImag = v.getComplexFloatImag();
725 } else {
726 makeComplexInt();
727 IntReal = v.getComplexIntReal();
728 IntImag = v.getComplexIntImag();
729 }
730 }
John McCallf4cf1a12010-05-07 17:22:02 +0000731 };
John McCallefdb83e2010-05-07 21:00:08 +0000732
733 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000734 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000735 CharUnits Offset;
Richard Smith83587db2012-02-15 02:18:13 +0000736 unsigned CallIndex;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000737 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000738
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000739 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000740 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000741 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith83587db2012-02-15 02:18:13 +0000742 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000743 SubobjectDesignator &getLValueDesignator() { return Designator; }
744 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000745
Richard Smith47a1eed2011-10-29 20:57:55 +0000746 void moveInto(CCValue &V) const {
Richard Smith83587db2012-02-15 02:18:13 +0000747 V = CCValue(Base, Offset, CallIndex, Designator);
John McCallefdb83e2010-05-07 21:00:08 +0000748 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000749 void setFrom(const CCValue &V) {
750 assert(V.isLValue());
751 Base = V.getLValueBase();
752 Offset = V.getLValueOffset();
Richard Smith83587db2012-02-15 02:18:13 +0000753 CallIndex = V.getLValueCallIndex();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000754 Designator = V.getLValueDesignator();
755 }
756
Richard Smith83587db2012-02-15 02:18:13 +0000757 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000758 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000759 Offset = CharUnits::Zero();
Richard Smith83587db2012-02-15 02:18:13 +0000760 CallIndex = I;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000761 Designator = SubobjectDesignator(getType(B));
762 }
763
764 // Check that this LValue is not based on a null pointer. If it is, produce
765 // a diagnostic and mark the designator as invalid.
766 bool checkNullPointer(EvalInfo &Info, const Expr *E,
767 CheckSubobjectKind CSK) {
768 if (Designator.Invalid)
769 return false;
770 if (!Base) {
771 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_null_subobject)
772 << CSK;
773 Designator.setInvalid();
774 return false;
775 }
776 return true;
777 }
778
779 // Check this LValue refers to an object. If not, set the designator to be
780 // invalid and emit a diagnostic.
781 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
782 return checkNullPointer(Info, E, CSK) &&
783 Designator.checkSubobject(Info, E, CSK);
784 }
785
786 void addDecl(EvalInfo &Info, const Expr *E,
787 const Decl *D, bool Virtual = false) {
788 checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base);
789 Designator.addDeclUnchecked(D, Virtual);
790 }
791 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
792 checkSubobject(Info, E, CSK_ArrayToPointer);
793 Designator.addArrayUnchecked(CAT);
794 }
795 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
796 if (!checkNullPointer(Info, E, CSK_ArrayIndex))
797 return;
798 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000799 }
John McCallefdb83e2010-05-07 21:00:08 +0000800 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000801
802 struct MemberPtr {
803 MemberPtr() {}
804 explicit MemberPtr(const ValueDecl *Decl) :
805 DeclAndIsDerivedMember(Decl, false), Path() {}
806
807 /// The member or (direct or indirect) field referred to by this member
808 /// pointer, or 0 if this is a null member pointer.
809 const ValueDecl *getDecl() const {
810 return DeclAndIsDerivedMember.getPointer();
811 }
812 /// Is this actually a member of some type derived from the relevant class?
813 bool isDerivedMember() const {
814 return DeclAndIsDerivedMember.getInt();
815 }
816 /// Get the class which the declaration actually lives in.
817 const CXXRecordDecl *getContainingRecord() const {
818 return cast<CXXRecordDecl>(
819 DeclAndIsDerivedMember.getPointer()->getDeclContext());
820 }
821
822 void moveInto(CCValue &V) const {
823 V = CCValue(getDecl(), isDerivedMember(), Path);
824 }
825 void setFrom(const CCValue &V) {
826 assert(V.isMemberPointer());
827 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
828 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
829 Path.clear();
830 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
831 Path.insert(Path.end(), P.begin(), P.end());
832 }
833
834 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
835 /// whether the member is a member of some class derived from the class type
836 /// of the member pointer.
837 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
838 /// Path - The path of base/derived classes from the member declaration's
839 /// class (exclusive) to the class type of the member pointer (inclusive).
840 SmallVector<const CXXRecordDecl*, 4> Path;
841
842 /// Perform a cast towards the class of the Decl (either up or down the
843 /// hierarchy).
844 bool castBack(const CXXRecordDecl *Class) {
845 assert(!Path.empty());
846 const CXXRecordDecl *Expected;
847 if (Path.size() >= 2)
848 Expected = Path[Path.size() - 2];
849 else
850 Expected = getContainingRecord();
851 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
852 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
853 // if B does not contain the original member and is not a base or
854 // derived class of the class containing the original member, the result
855 // of the cast is undefined.
856 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
857 // (D::*). We consider that to be a language defect.
858 return false;
859 }
860 Path.pop_back();
861 return true;
862 }
863 /// Perform a base-to-derived member pointer cast.
864 bool castToDerived(const CXXRecordDecl *Derived) {
865 if (!getDecl())
866 return true;
867 if (!isDerivedMember()) {
868 Path.push_back(Derived);
869 return true;
870 }
871 if (!castBack(Derived))
872 return false;
873 if (Path.empty())
874 DeclAndIsDerivedMember.setInt(false);
875 return true;
876 }
877 /// Perform a derived-to-base member pointer cast.
878 bool castToBase(const CXXRecordDecl *Base) {
879 if (!getDecl())
880 return true;
881 if (Path.empty())
882 DeclAndIsDerivedMember.setInt(true);
883 if (isDerivedMember()) {
884 Path.push_back(Base);
885 return true;
886 }
887 return castBack(Base);
888 }
889 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000890
Richard Smithb02e4622012-02-01 01:42:44 +0000891 /// Compare two member pointers, which are assumed to be of the same type.
892 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
893 if (!LHS.getDecl() || !RHS.getDecl())
894 return !LHS.getDecl() && !RHS.getDecl();
895 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
896 return false;
897 return LHS.Path == RHS.Path;
898 }
899
Richard Smithc1c5f272011-12-13 06:39:58 +0000900 /// Kinds of constant expression checking, for diagnostics.
901 enum CheckConstantExpressionKind {
902 CCEK_Constant, ///< A normal constant.
903 CCEK_ReturnValue, ///< A constexpr function return value.
904 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
905 };
John McCallf4cf1a12010-05-07 17:22:02 +0000906}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000907
Richard Smith47a1eed2011-10-29 20:57:55 +0000908static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith83587db2012-02-15 02:18:13 +0000909static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
910 const LValue &This, const Expr *E,
911 CheckConstantExpressionKind CCEK = CCEK_Constant,
912 bool AllowNonLiteralTypes = false);
John McCallefdb83e2010-05-07 21:00:08 +0000913static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
914static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000915static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
916 EvalInfo &Info);
917static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000918static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith47a1eed2011-10-29 20:57:55 +0000919static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000920 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000921static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000922static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000923
924//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000925// Misc utilities
926//===----------------------------------------------------------------------===//
927
Richard Smith180f4792011-11-10 06:34:14 +0000928/// Should this call expression be treated as a string literal?
929static bool IsStringLiteralCall(const CallExpr *E) {
930 unsigned Builtin = E->isBuiltinCall();
931 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
932 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
933}
934
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000935static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000936 // C++11 [expr.const]p3 An address constant expression is a prvalue core
937 // constant expression of pointer type that evaluates to...
938
939 // ... a null pointer value, or a prvalue core constant expression of type
940 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000941 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000942
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000943 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
944 // ... the address of an object with static storage duration,
945 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
946 return VD->hasGlobalStorage();
947 // ... the address of a function,
948 return isa<FunctionDecl>(D);
949 }
950
951 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000952 switch (E->getStmtClass()) {
953 default:
954 return false;
Richard Smith180f4792011-11-10 06:34:14 +0000955 case Expr::CompoundLiteralExprClass:
956 return cast<CompoundLiteralExpr>(E)->isFileScope();
957 // A string literal has static storage duration.
958 case Expr::StringLiteralClass:
959 case Expr::PredefinedExprClass:
960 case Expr::ObjCStringLiteralClass:
961 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000962 case Expr::CXXTypeidExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000963 return true;
964 case Expr::CallExprClass:
965 return IsStringLiteralCall(cast<CallExpr>(E));
966 // For GCC compatibility, &&label has static storage duration.
967 case Expr::AddrLabelExprClass:
968 return true;
969 // A Block literal expression may be used as the initialization value for
970 // Block variables at global or local static scope.
971 case Expr::BlockExprClass:
972 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000973 case Expr::ImplicitValueInitExprClass:
974 // FIXME:
975 // We can never form an lvalue with an implicit value initialization as its
976 // base through expression evaluation, so these only appear in one case: the
977 // implicit variable declaration we invent when checking whether a constexpr
978 // constructor can produce a constant expression. We must assume that such
979 // an expression might be a global lvalue.
980 return true;
Richard Smith180f4792011-11-10 06:34:14 +0000981 }
John McCall42c8f872010-05-10 23:27:23 +0000982}
983
Richard Smith83587db2012-02-15 02:18:13 +0000984static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
985 assert(Base && "no location for a null lvalue");
986 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
987 if (VD)
988 Info.Note(VD->getLocation(), diag::note_declared_at);
989 else
990 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
991 diag::note_constexpr_temporary_here);
992}
993
Richard Smith9a17a682011-11-07 05:07:52 +0000994/// Check that this reference or pointer core constant expression is a valid
Richard Smithb4e85ed2012-01-06 16:39:00 +0000995/// value for an address or reference constant expression. Type T should be
Richard Smith61e61622012-01-12 06:08:57 +0000996/// either LValue or CCValue. Return true if we can fold this expression,
997/// whether or not it's a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +0000998static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
999 QualType Type, const LValue &LVal) {
1000 bool IsReferenceType = Type->isReferenceType();
1001
Richard Smithc1c5f272011-12-13 06:39:58 +00001002 APValue::LValueBase Base = LVal.getLValueBase();
1003 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1004
1005 if (!IsGlobalLValue(Base)) {
1006 if (Info.getLangOpts().CPlusPlus0x) {
1007 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001008 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1009 << IsReferenceType << !Designator.Entries.empty()
1010 << !!VD << VD;
1011 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001012 } else {
Richard Smith83587db2012-02-15 02:18:13 +00001013 Info.Diag(Loc);
Richard Smithc1c5f272011-12-13 06:39:58 +00001014 }
Richard Smith61e61622012-01-12 06:08:57 +00001015 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +00001016 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001017 }
Richard Smith83587db2012-02-15 02:18:13 +00001018 assert((Info.CheckingPotentialConstantExpression ||
1019 LVal.getLValueCallIndex() == 0) &&
1020 "have call index for global lvalue");
Richard Smithb4e85ed2012-01-06 16:39:00 +00001021
1022 // Allow address constant expressions to be past-the-end pointers. This is
1023 // an extension: the standard requires them to point to an object.
1024 if (!IsReferenceType)
1025 return true;
1026
1027 // A reference constant expression must refer to an object.
1028 if (!Base) {
1029 // FIXME: diagnostic
Richard Smith83587db2012-02-15 02:18:13 +00001030 Info.CCEDiag(Loc);
Richard Smith61e61622012-01-12 06:08:57 +00001031 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001032 }
1033
Richard Smithc1c5f272011-12-13 06:39:58 +00001034 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +00001035 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001036 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001037 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smithc1c5f272011-12-13 06:39:58 +00001038 << !Designator.Entries.empty() << !!VD << VD;
Richard Smith83587db2012-02-15 02:18:13 +00001039 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001040 }
1041
Richard Smith9a17a682011-11-07 05:07:52 +00001042 return true;
1043}
1044
Richard Smith51201882011-12-30 21:15:51 +00001045/// Check that this core constant expression is of literal type, and if not,
1046/// produce an appropriate diagnostic.
1047static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1048 if (!E->isRValue() || E->getType()->isLiteralType())
1049 return true;
1050
1051 // Prvalue constant expressions must be of literal types.
1052 if (Info.getLangOpts().CPlusPlus0x)
1053 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
1054 << E->getType();
1055 else
1056 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1057 return false;
1058}
1059
Richard Smith47a1eed2011-10-29 20:57:55 +00001060/// Check that this core constant expression value is a valid value for a
Richard Smith83587db2012-02-15 02:18:13 +00001061/// constant expression. If not, report an appropriate diagnostic. Does not
1062/// check that the expression is of literal type.
1063static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1064 QualType Type, const APValue &Value) {
1065 // Core issue 1454: For a literal constant expression of array or class type,
1066 // each subobject of its value shall have been initialized by a constant
1067 // expression.
1068 if (Value.isArray()) {
1069 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1070 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1071 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1072 Value.getArrayInitializedElt(I)))
1073 return false;
1074 }
1075 if (!Value.hasArrayFiller())
1076 return true;
1077 return CheckConstantExpression(Info, DiagLoc, EltTy,
1078 Value.getArrayFiller());
Richard Smith9a17a682011-11-07 05:07:52 +00001079 }
Richard Smith83587db2012-02-15 02:18:13 +00001080 if (Value.isUnion() && Value.getUnionField()) {
1081 return CheckConstantExpression(Info, DiagLoc,
1082 Value.getUnionField()->getType(),
1083 Value.getUnionValue());
1084 }
1085 if (Value.isStruct()) {
1086 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1087 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1088 unsigned BaseIndex = 0;
1089 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1090 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1091 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1092 Value.getStructBase(BaseIndex)))
1093 return false;
1094 }
1095 }
1096 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1097 I != E; ++I) {
1098 if (!CheckConstantExpression(Info, DiagLoc, (*I)->getType(),
1099 Value.getStructField((*I)->getFieldIndex())))
1100 return false;
1101 }
1102 }
1103
1104 if (Value.isLValue()) {
1105 CCValue Val(Info.Ctx, Value, CCValue::GlobalValue());
1106 LValue LVal;
1107 LVal.setFrom(Val);
1108 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1109 }
1110
1111 // Everything else is fine.
1112 return true;
Richard Smith47a1eed2011-10-29 20:57:55 +00001113}
1114
Richard Smith9e36b532011-10-31 05:11:32 +00001115const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001116 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001117}
1118
1119static bool IsLiteralLValue(const LValue &Value) {
Richard Smith83587db2012-02-15 02:18:13 +00001120 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith9e36b532011-10-31 05:11:32 +00001121}
1122
Richard Smith65ac5982011-11-01 21:06:14 +00001123static bool IsWeakLValue(const LValue &Value) {
1124 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001125 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001126}
1127
Richard Smithe24f5fc2011-11-17 22:56:20 +00001128static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001129 // A null base expression indicates a null pointer. These are always
1130 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001131 if (!Value.getLValueBase()) {
1132 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001133 return true;
1134 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001135
Richard Smithe24f5fc2011-11-17 22:56:20 +00001136 // We have a non-null base. These are generally known to be true, but if it's
1137 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001138 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001139 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001140 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001141}
1142
Richard Smith47a1eed2011-10-29 20:57:55 +00001143static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001144 switch (Val.getKind()) {
1145 case APValue::Uninitialized:
1146 return false;
1147 case APValue::Int:
1148 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001149 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001150 case APValue::Float:
1151 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001152 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001153 case APValue::ComplexInt:
1154 Result = Val.getComplexIntReal().getBoolValue() ||
1155 Val.getComplexIntImag().getBoolValue();
1156 return true;
1157 case APValue::ComplexFloat:
1158 Result = !Val.getComplexFloatReal().isZero() ||
1159 !Val.getComplexFloatImag().isZero();
1160 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001161 case APValue::LValue:
1162 return EvalPointerValueAsBool(Val, Result);
1163 case APValue::MemberPointer:
1164 Result = Val.getMemberPointerDecl();
1165 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001166 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001167 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001168 case APValue::Struct:
1169 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001170 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001171 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001172 }
1173
Richard Smithc49bd112011-10-28 17:51:58 +00001174 llvm_unreachable("unknown APValue kind");
1175}
1176
1177static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1178 EvalInfo &Info) {
1179 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith47a1eed2011-10-29 20:57:55 +00001180 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +00001181 if (!Evaluate(Val, Info, E))
1182 return false;
1183 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001184}
1185
Richard Smithc1c5f272011-12-13 06:39:58 +00001186template<typename T>
1187static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1188 const T &SrcValue, QualType DestType) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001189 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001190 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001191 return false;
1192}
1193
1194static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1195 QualType SrcType, const APFloat &Value,
1196 QualType DestType, APSInt &Result) {
1197 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001198 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001199 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001200
Richard Smithc1c5f272011-12-13 06:39:58 +00001201 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001202 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001203 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1204 & APFloat::opInvalidOp)
1205 return HandleOverflow(Info, E, Value, DestType);
1206 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001207}
1208
Richard Smithc1c5f272011-12-13 06:39:58 +00001209static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1210 QualType SrcType, QualType DestType,
1211 APFloat &Result) {
1212 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001213 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001214 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1215 APFloat::rmNearestTiesToEven, &ignored)
1216 & APFloat::opOverflow)
1217 return HandleOverflow(Info, E, Value, DestType);
1218 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001219}
1220
Richard Smithf72fccf2012-01-30 22:27:01 +00001221static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1222 QualType DestType, QualType SrcType,
1223 APSInt &Value) {
1224 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001225 APSInt Result = Value;
1226 // Figure out if this is a truncate, extend or noop cast.
1227 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001228 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001229 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001230 return Result;
1231}
1232
Richard Smithc1c5f272011-12-13 06:39:58 +00001233static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1234 QualType SrcType, const APSInt &Value,
1235 QualType DestType, APFloat &Result) {
1236 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1237 if (Result.convertFromAPInt(Value, Value.isSigned(),
1238 APFloat::rmNearestTiesToEven)
1239 & APFloat::opOverflow)
1240 return HandleOverflow(Info, E, Value, DestType);
1241 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001242}
1243
Eli Friedmane6a24e82011-12-22 03:51:45 +00001244static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1245 llvm::APInt &Res) {
1246 CCValue SVal;
1247 if (!Evaluate(SVal, Info, E))
1248 return false;
1249 if (SVal.isInt()) {
1250 Res = SVal.getInt();
1251 return true;
1252 }
1253 if (SVal.isFloat()) {
1254 Res = SVal.getFloat().bitcastToAPInt();
1255 return true;
1256 }
1257 if (SVal.isVector()) {
1258 QualType VecTy = E->getType();
1259 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1260 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1261 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1262 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1263 Res = llvm::APInt::getNullValue(VecSize);
1264 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1265 APValue &Elt = SVal.getVectorElt(i);
1266 llvm::APInt EltAsInt;
1267 if (Elt.isInt()) {
1268 EltAsInt = Elt.getInt();
1269 } else if (Elt.isFloat()) {
1270 EltAsInt = Elt.getFloat().bitcastToAPInt();
1271 } else {
1272 // Don't try to handle vectors of anything other than int or float
1273 // (not sure if it's possible to hit this case).
1274 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1275 return false;
1276 }
1277 unsigned BaseEltSize = EltAsInt.getBitWidth();
1278 if (BigEndian)
1279 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1280 else
1281 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1282 }
1283 return true;
1284 }
1285 // Give up if the input isn't an int, float, or vector. For example, we
1286 // reject "(v4i16)(intptr_t)&a".
1287 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1288 return false;
1289}
1290
Richard Smithb4e85ed2012-01-06 16:39:00 +00001291/// Cast an lvalue referring to a base subobject to a derived class, by
1292/// truncating the lvalue's path to the given length.
1293static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1294 const RecordDecl *TruncatedType,
1295 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001296 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001297
1298 // Check we actually point to a derived class object.
1299 if (TruncatedElements == D.Entries.size())
1300 return true;
1301 assert(TruncatedElements >= D.MostDerivedPathLength &&
1302 "not casting to a derived class");
1303 if (!Result.checkSubobject(Info, E, CSK_Derived))
1304 return false;
1305
1306 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001307 const RecordDecl *RD = TruncatedType;
1308 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +00001309 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1310 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001311 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001312 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001313 else
Richard Smith180f4792011-11-10 06:34:14 +00001314 Result.Offset -= Layout.getBaseClassOffset(Base);
1315 RD = Base;
1316 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001317 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001318 return true;
1319}
1320
Richard Smithb4e85ed2012-01-06 16:39:00 +00001321static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001322 const CXXRecordDecl *Derived,
1323 const CXXRecordDecl *Base,
1324 const ASTRecordLayout *RL = 0) {
1325 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1326 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001327 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
Richard Smith180f4792011-11-10 06:34:14 +00001328}
1329
Richard Smithb4e85ed2012-01-06 16:39:00 +00001330static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001331 const CXXRecordDecl *DerivedDecl,
1332 const CXXBaseSpecifier *Base) {
1333 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1334
1335 if (!Base->isVirtual()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001336 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001337 return true;
1338 }
1339
Richard Smithb4e85ed2012-01-06 16:39:00 +00001340 SubobjectDesignator &D = Obj.Designator;
1341 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001342 return false;
1343
Richard Smithb4e85ed2012-01-06 16:39:00 +00001344 // Extract most-derived object and corresponding type.
1345 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1346 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1347 return false;
1348
1349 // Find the virtual base class.
Richard Smith180f4792011-11-10 06:34:14 +00001350 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1351 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001352 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001353 return true;
1354}
1355
1356/// Update LVal to refer to the given field, which must be a member of the type
1357/// currently described by LVal.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001358static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001359 const FieldDecl *FD,
1360 const ASTRecordLayout *RL = 0) {
1361 if (!RL)
1362 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1363
1364 unsigned I = FD->getFieldIndex();
1365 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001366 LVal.addDecl(Info, E, FD);
Richard Smith180f4792011-11-10 06:34:14 +00001367}
1368
Richard Smithd9b02e72012-01-25 22:15:11 +00001369/// Update LVal to refer to the given indirect field.
1370static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1371 LValue &LVal,
1372 const IndirectFieldDecl *IFD) {
1373 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1374 CE = IFD->chain_end(); C != CE; ++C)
1375 HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
1376}
1377
Richard Smith180f4792011-11-10 06:34:14 +00001378/// Get the size of the given type in char units.
Richard Smith74e1ad92012-02-16 02:46:34 +00001379static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1380 QualType Type, CharUnits &Size) {
Richard Smith180f4792011-11-10 06:34:14 +00001381 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1382 // extension.
1383 if (Type->isVoidType() || Type->isFunctionType()) {
1384 Size = CharUnits::One();
1385 return true;
1386 }
1387
1388 if (!Type->isConstantSizeType()) {
1389 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith74e1ad92012-02-16 02:46:34 +00001390 // FIXME: Better diagnostic.
1391 Info.Diag(Loc);
Richard Smith180f4792011-11-10 06:34:14 +00001392 return false;
1393 }
1394
1395 Size = Info.Ctx.getTypeSizeInChars(Type);
1396 return true;
1397}
1398
1399/// Update a pointer value to model pointer arithmetic.
1400/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001401/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001402/// \param LVal - The pointer value to be updated.
1403/// \param EltTy - The pointee type represented by LVal.
1404/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001405static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1406 LValue &LVal, QualType EltTy,
1407 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001408 CharUnits SizeOfPointee;
Richard Smith74e1ad92012-02-16 02:46:34 +00001409 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smith180f4792011-11-10 06:34:14 +00001410 return false;
1411
1412 // Compute the new offset in the appropriate width.
1413 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001414 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001415 return true;
1416}
1417
Richard Smith03f96112011-10-24 17:54:18 +00001418/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001419static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1420 const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +00001421 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001422 // If this is a parameter to an active constexpr function call, perform
1423 // argument substitution.
1424 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001425 // Assume arguments of a potential constant expression are unknown
1426 // constant expressions.
1427 if (Info.CheckingPotentialConstantExpression)
1428 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001429 if (!Frame || !Frame->Arguments) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001430 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001431 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001432 }
Richard Smith177dce72011-11-01 16:57:24 +00001433 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1434 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001435 }
Richard Smith03f96112011-10-24 17:54:18 +00001436
Richard Smith099e7f62011-12-19 06:19:21 +00001437 // Dig out the initializer, and use the declaration which it's attached to.
1438 const Expr *Init = VD->getAnyInitializer(VD);
1439 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001440 // If we're checking a potential constant expression, the variable could be
1441 // initialized later.
1442 if (!Info.CheckingPotentialConstantExpression)
1443 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001444 return false;
1445 }
1446
Richard Smith180f4792011-11-10 06:34:14 +00001447 // If we're currently evaluating the initializer of this declaration, use that
1448 // in-flight value.
1449 if (Info.EvaluatingDecl == VD) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001450 Result = CCValue(Info.Ctx, *Info.EvaluatingDeclValue,
1451 CCValue::GlobalValue());
Richard Smith180f4792011-11-10 06:34:14 +00001452 return !Result.isUninit();
1453 }
1454
Richard Smith65ac5982011-11-01 21:06:14 +00001455 // Never evaluate the initializer of a weak variable. We can't be sure that
1456 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001457 if (VD->isWeak()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001458 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001459 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001460 }
Richard Smith65ac5982011-11-01 21:06:14 +00001461
Richard Smith099e7f62011-12-19 06:19:21 +00001462 // Check that we can fold the initializer. In C++, we will have already done
1463 // this in the cases where it matters for conformance.
1464 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1465 if (!VD->evaluateValue(Notes)) {
1466 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1467 Notes.size() + 1) << VD;
1468 Info.Note(VD->getLocation(), diag::note_declared_at);
1469 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001470 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001471 } else if (!VD->checkInitIsICE()) {
1472 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1473 Notes.size() + 1) << VD;
1474 Info.Note(VD->getLocation(), diag::note_declared_at);
1475 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001476 }
Richard Smith03f96112011-10-24 17:54:18 +00001477
Richard Smithb4e85ed2012-01-06 16:39:00 +00001478 Result = CCValue(Info.Ctx, *VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +00001479 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001480}
1481
Richard Smithc49bd112011-10-28 17:51:58 +00001482static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001483 Qualifiers Quals = T.getQualifiers();
1484 return Quals.hasConst() && !Quals.hasVolatile();
1485}
1486
Richard Smith59efe262011-11-11 04:05:33 +00001487/// Get the base index of the given base class within an APValue representing
1488/// the given derived class.
1489static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1490 const CXXRecordDecl *Base) {
1491 Base = Base->getCanonicalDecl();
1492 unsigned Index = 0;
1493 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1494 E = Derived->bases_end(); I != E; ++I, ++Index) {
1495 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1496 return Index;
1497 }
1498
1499 llvm_unreachable("base class missing from derived class's bases list");
1500}
1501
Richard Smithcc5d4f62011-11-07 09:22:26 +00001502/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001503static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1504 CCValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001505 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001506 if (Sub.Invalid)
1507 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001508 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001509 if (Sub.isOnePastTheEnd()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001510 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001511 (unsigned)diag::note_constexpr_read_past_end :
1512 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001513 return false;
1514 }
Richard Smithf64699e2011-11-11 08:28:03 +00001515 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001516 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001517 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1518 // This object might be initialized later.
1519 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001520
1521 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1522 const APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001523 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001524 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001525 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001526 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001527 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001528 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001529 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001530 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001531 // Note, it should not be possible to form a pointer with a valid
1532 // designator which points more than one past the end of the array.
1533 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001534 (unsigned)diag::note_constexpr_read_past_end :
1535 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001536 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001537 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001538 if (O->getArrayInitializedElts() > Index)
1539 O = &O->getArrayInitializedElt(Index);
1540 else
1541 O = &O->getArrayFiller();
1542 ObjType = CAT->getElementType();
Richard Smith180f4792011-11-10 06:34:14 +00001543 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithb4e5e282012-02-09 03:29:58 +00001544 if (Field->isMutable()) {
1545 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_mutable, 1)
1546 << Field;
1547 Info.Note(Field->getLocation(), diag::note_declared_at);
1548 return false;
1549 }
1550
Richard Smith180f4792011-11-10 06:34:14 +00001551 // Next subobject is a class, struct or union field.
1552 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1553 if (RD->isUnion()) {
1554 const FieldDecl *UnionField = O->getUnionField();
1555 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001556 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001557 Info.Diag(E->getExprLoc(),
1558 diag::note_constexpr_read_inactive_union_member)
1559 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001560 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001561 }
Richard Smith180f4792011-11-10 06:34:14 +00001562 O = &O->getUnionValue();
1563 } else
1564 O = &O->getStructField(Field->getFieldIndex());
1565 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001566
1567 if (ObjType.isVolatileQualified()) {
1568 if (Info.getLangOpts().CPlusPlus) {
1569 // FIXME: Include a description of the path to the volatile subobject.
1570 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1571 << 2 << Field;
1572 Info.Note(Field->getLocation(), diag::note_declared_at);
1573 } else {
1574 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1575 }
1576 return false;
1577 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001578 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001579 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001580 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1581 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1582 O = &O->getStructBase(getBaseIndex(Derived, Base));
1583 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001584 }
Richard Smith180f4792011-11-10 06:34:14 +00001585
Richard Smithf48fdb02011-12-09 22:58:01 +00001586 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001587 if (!Info.CheckingPotentialConstantExpression)
1588 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001589 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001590 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001591 }
1592
Richard Smithb4e85ed2012-01-06 16:39:00 +00001593 Obj = CCValue(Info.Ctx, *O, CCValue::GlobalValue());
Richard Smithcc5d4f62011-11-07 09:22:26 +00001594 return true;
1595}
1596
Richard Smithf15fda02012-02-02 01:16:57 +00001597/// Find the position where two subobject designators diverge, or equivalently
1598/// the length of the common initial subsequence.
1599static unsigned FindDesignatorMismatch(QualType ObjType,
1600 const SubobjectDesignator &A,
1601 const SubobjectDesignator &B,
1602 bool &WasArrayIndex) {
1603 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1604 for (/**/; I != N; ++I) {
1605 if (!ObjType.isNull() && ObjType->isArrayType()) {
1606 // Next subobject is an array element.
1607 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1608 WasArrayIndex = true;
1609 return I;
1610 }
1611 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
1612 } else {
1613 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1614 WasArrayIndex = false;
1615 return I;
1616 }
1617 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1618 // Next subobject is a field.
1619 ObjType = FD->getType();
1620 else
1621 // Next subobject is a base class.
1622 ObjType = QualType();
1623 }
1624 }
1625 WasArrayIndex = false;
1626 return I;
1627}
1628
1629/// Determine whether the given subobject designators refer to elements of the
1630/// same array object.
1631static bool AreElementsOfSameArray(QualType ObjType,
1632 const SubobjectDesignator &A,
1633 const SubobjectDesignator &B) {
1634 if (A.Entries.size() != B.Entries.size())
1635 return false;
1636
1637 bool IsArray = A.MostDerivedArraySize != 0;
1638 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1639 // A is a subobject of the array element.
1640 return false;
1641
1642 // If A (and B) designates an array element, the last entry will be the array
1643 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1644 // of length 1' case, and the entire path must match.
1645 bool WasArrayIndex;
1646 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1647 return CommonLength >= A.Entries.size() - IsArray;
1648}
1649
Richard Smith180f4792011-11-10 06:34:14 +00001650/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1651/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1652/// for looking up the glvalue referred to by an entity of reference type.
1653///
1654/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001655/// \param Conv - The expression for which we are performing the conversion.
1656/// Used for diagnostics.
Richard Smith9ec71972012-02-05 01:23:16 +00001657/// \param Type - The type we expect this conversion to produce, before
1658/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smith180f4792011-11-10 06:34:14 +00001659/// \param LVal - The glvalue on which we are attempting to perform this action.
1660/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001661static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1662 QualType Type,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001663 const LValue &LVal, CCValue &RVal) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001664 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1665 if (!Info.getLangOpts().CPlusPlus)
1666 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1667
Richard Smithb4e85ed2012-01-06 16:39:00 +00001668 if (LVal.Designator.Invalid)
1669 // A diagnostic will have already been produced.
1670 return false;
1671
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001672 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith7098cbd2011-12-21 05:04:46 +00001673 SourceLocation Loc = Conv->getExprLoc();
Richard Smithc49bd112011-10-28 17:51:58 +00001674
Richard Smithf48fdb02011-12-09 22:58:01 +00001675 if (!LVal.Base) {
1676 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith7098cbd2011-12-21 05:04:46 +00001677 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1678 return false;
1679 }
1680
Richard Smith83587db2012-02-15 02:18:13 +00001681 CallStackFrame *Frame = 0;
1682 if (LVal.CallIndex) {
1683 Frame = Info.getCallFrame(LVal.CallIndex);
1684 if (!Frame) {
1685 Info.Diag(Loc, diag::note_constexpr_lifetime_ended, 1) << !Base;
1686 NoteLValueLocation(Info, LVal.Base);
1687 return false;
1688 }
1689 }
1690
Richard Smith7098cbd2011-12-21 05:04:46 +00001691 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1692 // is not a constant expression (even if the object is non-volatile). We also
1693 // apply this rule to C++98, in order to conform to the expected 'volatile'
1694 // semantics.
1695 if (Type.isVolatileQualified()) {
1696 if (Info.getLangOpts().CPlusPlus)
1697 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1698 else
1699 Info.Diag(Loc);
Richard Smithc49bd112011-10-28 17:51:58 +00001700 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001701 }
Richard Smithc49bd112011-10-28 17:51:58 +00001702
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001703 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001704 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1705 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001706 // expressions are constant expressions too. Inside constexpr functions,
1707 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001708 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001709 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf15fda02012-02-02 01:16:57 +00001710 if (const VarDecl *VDef = VD->getDefinition())
1711 VD = VDef;
Richard Smithf48fdb02011-12-09 22:58:01 +00001712 if (!VD || VD->isInvalidDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001713 Info.Diag(Loc);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001714 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001715 }
1716
Richard Smith7098cbd2011-12-21 05:04:46 +00001717 // DR1313: If the object is volatile-qualified but the glvalue was not,
1718 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001719 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001720 if (VT.isVolatileQualified()) {
1721 if (Info.getLangOpts().CPlusPlus) {
1722 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1723 Info.Note(VD->getLocation(), diag::note_declared_at);
1724 } else {
1725 Info.Diag(Loc);
Richard Smithf48fdb02011-12-09 22:58:01 +00001726 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001727 return false;
1728 }
1729
1730 if (!isa<ParmVarDecl>(VD)) {
1731 if (VD->isConstexpr()) {
1732 // OK, we can read this variable.
1733 } else if (VT->isIntegralOrEnumerationType()) {
1734 if (!VT.isConstQualified()) {
1735 if (Info.getLangOpts().CPlusPlus) {
1736 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1737 Info.Note(VD->getLocation(), diag::note_declared_at);
1738 } else {
1739 Info.Diag(Loc);
1740 }
1741 return false;
1742 }
1743 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1744 // We support folding of const floating-point types, in order to make
1745 // static const data members of such types (supported as an extension)
1746 // more useful.
1747 if (Info.getLangOpts().CPlusPlus0x) {
1748 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1749 Info.Note(VD->getLocation(), diag::note_declared_at);
1750 } else {
1751 Info.CCEDiag(Loc);
1752 }
1753 } else {
1754 // FIXME: Allow folding of values of any literal type in all languages.
1755 if (Info.getLangOpts().CPlusPlus0x) {
1756 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1757 Info.Note(VD->getLocation(), diag::note_declared_at);
1758 } else {
1759 Info.Diag(Loc);
1760 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001761 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001762 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001763 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001764
Richard Smithf48fdb02011-12-09 22:58:01 +00001765 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001766 return false;
1767
Richard Smith47a1eed2011-10-29 20:57:55 +00001768 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001769 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001770
1771 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1772 // conversion. This happens when the declaration and the lvalue should be
1773 // considered synonymous, for instance when initializing an array of char
1774 // from a string literal. Continue as if the initializer lvalue was the
1775 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001776 assert(RVal.getLValueOffset().isZero() &&
1777 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001778 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith83587db2012-02-15 02:18:13 +00001779
1780 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1781 Frame = Info.getCallFrame(CallIndex);
1782 if (!Frame) {
1783 Info.Diag(Loc, diag::note_constexpr_lifetime_ended, 1) << !Base;
1784 NoteLValueLocation(Info, RVal.getLValueBase());
1785 return false;
1786 }
1787 } else {
1788 Frame = 0;
1789 }
Richard Smithc49bd112011-10-28 17:51:58 +00001790 }
1791
Richard Smith7098cbd2011-12-21 05:04:46 +00001792 // Volatile temporary objects cannot be read in constant expressions.
1793 if (Base->getType().isVolatileQualified()) {
1794 if (Info.getLangOpts().CPlusPlus) {
1795 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1796 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1797 } else {
1798 Info.Diag(Loc);
1799 }
1800 return false;
1801 }
1802
Richard Smith0a3bdb62011-11-04 02:25:55 +00001803 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1804 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1805 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf48fdb02011-12-09 22:58:01 +00001806 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001807 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001808 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001809 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001810
1811 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith9a17a682011-11-07 05:07:52 +00001812 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smith7098cbd2011-12-21 05:04:46 +00001813 const ConstantArrayType *CAT =
1814 Info.Ctx.getAsConstantArrayType(S->getType());
1815 if (Index >= CAT->getSize().getZExtValue()) {
1816 // Note, it should not be possible to form a pointer which points more
1817 // than one past the end of the array without producing a prior const expr
1818 // diagnostic.
1819 Info.Diag(Loc, diag::note_constexpr_read_past_end);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001820 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001821 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001822 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1823 Type->isUnsignedIntegerType());
1824 if (Index < S->getLength())
1825 Value = S->getCodeUnit(Index);
1826 RVal = CCValue(Value);
1827 return true;
1828 }
1829
Richard Smithcc5d4f62011-11-07 09:22:26 +00001830 if (Frame) {
1831 // If this is a temporary expression with a nontrivial initializer, grab the
1832 // value from the relevant stack frame.
1833 RVal = Frame->Temporaries[Base];
1834 } else if (const CompoundLiteralExpr *CLE
1835 = dyn_cast<CompoundLiteralExpr>(Base)) {
1836 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1837 // initializer until now for such expressions. Such an expression can't be
1838 // an ICE in C, so this only matters for fold.
1839 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1840 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1841 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001842 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001843 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001844 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001845 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001846
Richard Smithf48fdb02011-12-09 22:58:01 +00001847 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1848 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001849}
1850
Richard Smith59efe262011-11-11 04:05:33 +00001851/// Build an lvalue for the object argument of a member function call.
1852static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1853 LValue &This) {
1854 if (Object->getType()->isPointerType())
1855 return EvaluatePointer(Object, This, Info);
1856
1857 if (Object->isGLValue())
1858 return EvaluateLValue(Object, This, Info);
1859
Richard Smithe24f5fc2011-11-17 22:56:20 +00001860 if (Object->getType()->isLiteralType())
1861 return EvaluateTemporary(Object, This, Info);
1862
1863 return false;
1864}
1865
1866/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1867/// lvalue referring to the result.
1868///
1869/// \param Info - Information about the ongoing evaluation.
1870/// \param BO - The member pointer access operation.
1871/// \param LV - Filled in with a reference to the resulting object.
1872/// \param IncludeMember - Specifies whether the member itself is included in
1873/// the resulting LValue subobject designator. This is not possible when
1874/// creating a bound member function.
1875/// \return The field or method declaration to which the member pointer refers,
1876/// or 0 if evaluation fails.
1877static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1878 const BinaryOperator *BO,
1879 LValue &LV,
1880 bool IncludeMember = true) {
1881 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1882
Richard Smith745f5142012-01-27 01:14:48 +00001883 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1884 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001885 return 0;
1886
1887 MemberPtr MemPtr;
1888 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1889 return 0;
1890
1891 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1892 // member value, the behavior is undefined.
1893 if (!MemPtr.getDecl())
1894 return 0;
1895
Richard Smith745f5142012-01-27 01:14:48 +00001896 if (!EvalObjOK)
1897 return 0;
1898
Richard Smithe24f5fc2011-11-17 22:56:20 +00001899 if (MemPtr.isDerivedMember()) {
1900 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001901 // The end of the derived-to-base path for the base object must match the
1902 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001903 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001904 LV.Designator.Entries.size())
1905 return 0;
1906 unsigned PathLengthToMember =
1907 LV.Designator.Entries.size() - MemPtr.Path.size();
1908 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1909 const CXXRecordDecl *LVDecl = getAsBaseClass(
1910 LV.Designator.Entries[PathLengthToMember + I]);
1911 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1912 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1913 return 0;
1914 }
1915
1916 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001917 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1918 PathLengthToMember))
1919 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001920 } else if (!MemPtr.Path.empty()) {
1921 // Extend the LValue path with the member pointer's path.
1922 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1923 MemPtr.Path.size() + IncludeMember);
1924
1925 // Walk down to the appropriate base class.
1926 QualType LVType = BO->getLHS()->getType();
1927 if (const PointerType *PT = LVType->getAs<PointerType>())
1928 LVType = PT->getPointeeType();
1929 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1930 assert(RD && "member pointer access on non-class-type expression");
1931 // The first class in the path is that of the lvalue.
1932 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1933 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smithb4e85ed2012-01-06 16:39:00 +00001934 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001935 RD = Base;
1936 }
1937 // Finally cast to the class containing the member.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001938 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smithe24f5fc2011-11-17 22:56:20 +00001939 }
1940
1941 // Add the member. Note that we cannot build bound member functions here.
1942 if (IncludeMember) {
Richard Smithd9b02e72012-01-25 22:15:11 +00001943 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
1944 HandleLValueMember(Info, BO, LV, FD);
1945 else if (const IndirectFieldDecl *IFD =
1946 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
1947 HandleLValueIndirectMember(Info, BO, LV, IFD);
1948 else
1949 llvm_unreachable("can't construct reference to bound member function");
Richard Smithe24f5fc2011-11-17 22:56:20 +00001950 }
1951
1952 return MemPtr.getDecl();
1953}
1954
1955/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1956/// the provided lvalue, which currently refers to the base object.
1957static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1958 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001959 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001960 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001961 return false;
1962
Richard Smithb4e85ed2012-01-06 16:39:00 +00001963 QualType TargetQT = E->getType();
1964 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1965 TargetQT = PT->getPointeeType();
1966
1967 // Check this cast lands within the final derived-to-base subobject path.
1968 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
1969 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1970 << D.MostDerivedType << TargetQT;
1971 return false;
1972 }
1973
Richard Smithe24f5fc2011-11-17 22:56:20 +00001974 // Check the type of the final cast. We don't need to check the path,
1975 // since a cast can only be formed if the path is unique.
1976 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001977 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1978 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001979 if (NewEntriesSize == D.MostDerivedPathLength)
1980 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
1981 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00001982 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001983 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
1984 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1985 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001986 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001987 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001988
1989 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001990 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00001991}
1992
Mike Stumpc4c90452009-10-27 22:09:17 +00001993namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00001994enum EvalStmtResult {
1995 /// Evaluation failed.
1996 ESR_Failed,
1997 /// Hit a 'return' statement.
1998 ESR_Returned,
1999 /// Evaluation succeeded.
2000 ESR_Succeeded
2001};
2002}
2003
2004// Evaluate a statement.
Richard Smith83587db2012-02-15 02:18:13 +00002005static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00002006 const Stmt *S) {
2007 switch (S->getStmtClass()) {
2008 default:
2009 return ESR_Failed;
2010
2011 case Stmt::NullStmtClass:
2012 case Stmt::DeclStmtClass:
2013 return ESR_Succeeded;
2014
Richard Smithc1c5f272011-12-13 06:39:58 +00002015 case Stmt::ReturnStmtClass: {
Richard Smithc1c5f272011-12-13 06:39:58 +00002016 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith83587db2012-02-15 02:18:13 +00002017 if (!Evaluate(Result, Info, RetExpr))
Richard Smithc1c5f272011-12-13 06:39:58 +00002018 return ESR_Failed;
2019 return ESR_Returned;
2020 }
Richard Smithd0dccea2011-10-28 22:34:42 +00002021
2022 case Stmt::CompoundStmtClass: {
2023 const CompoundStmt *CS = cast<CompoundStmt>(S);
2024 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2025 BE = CS->body_end(); BI != BE; ++BI) {
2026 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2027 if (ESR != ESR_Succeeded)
2028 return ESR;
2029 }
2030 return ESR_Succeeded;
2031 }
2032 }
2033}
2034
Richard Smith61802452011-12-22 02:22:31 +00002035/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2036/// default constructor. If so, we'll fold it whether or not it's marked as
2037/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2038/// so we need special handling.
2039static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00002040 const CXXConstructorDecl *CD,
2041 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002042 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2043 return false;
2044
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002045 // Value-initialization does not call a trivial default constructor, so such a
2046 // call is a core constant expression whether or not the constructor is
2047 // constexpr.
2048 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002049 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002050 // FIXME: If DiagDecl is an implicitly-declared special member function,
2051 // we should be much more explicit about why it's not constexpr.
2052 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2053 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2054 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00002055 } else {
2056 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2057 }
2058 }
2059 return true;
2060}
2061
Richard Smithc1c5f272011-12-13 06:39:58 +00002062/// CheckConstexprFunction - Check that a function can be called in a constant
2063/// expression.
2064static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2065 const FunctionDecl *Declaration,
2066 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00002067 // Potential constant expressions can contain calls to declared, but not yet
2068 // defined, constexpr functions.
2069 if (Info.CheckingPotentialConstantExpression && !Definition &&
2070 Declaration->isConstexpr())
2071 return false;
2072
Richard Smithc1c5f272011-12-13 06:39:58 +00002073 // Can we evaluate this function call?
2074 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2075 return true;
2076
2077 if (Info.getLangOpts().CPlusPlus0x) {
2078 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00002079 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2080 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00002081 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2082 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2083 << DiagDecl;
2084 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2085 } else {
2086 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2087 }
2088 return false;
2089}
2090
Richard Smith180f4792011-11-10 06:34:14 +00002091namespace {
Richard Smithcd99b072011-11-11 05:48:57 +00002092typedef SmallVector<CCValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00002093}
2094
2095/// EvaluateArgs - Evaluate the arguments to a function call.
2096static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2097 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00002098 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002099 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00002100 I != E; ++I) {
2101 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2102 // If we're checking for a potential constant expression, evaluate all
2103 // initializers even if some of them fail.
2104 if (!Info.keepEvaluatingAfterFailure())
2105 return false;
2106 Success = false;
2107 }
2108 }
2109 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002110}
2111
Richard Smithd0dccea2011-10-28 22:34:42 +00002112/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002113static bool HandleFunctionCall(SourceLocation CallLoc,
2114 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002115 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith83587db2012-02-15 02:18:13 +00002116 EvalInfo &Info, CCValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002117 ArgVector ArgValues(Args.size());
2118 if (!EvaluateArgs(Args, ArgValues, Info))
2119 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00002120
Richard Smith745f5142012-01-27 01:14:48 +00002121 if (!Info.CheckCallLimit(CallLoc))
2122 return false;
2123
2124 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002125 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2126}
2127
Richard Smith180f4792011-11-10 06:34:14 +00002128/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002129static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002130 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002131 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002132 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002133 ArgVector ArgValues(Args.size());
2134 if (!EvaluateArgs(Args, ArgValues, Info))
2135 return false;
2136
Richard Smith745f5142012-01-27 01:14:48 +00002137 if (!Info.CheckCallLimit(CallLoc))
2138 return false;
2139
Richard Smith86c3ae42012-02-13 03:54:03 +00002140 const CXXRecordDecl *RD = Definition->getParent();
2141 if (RD->getNumVBases()) {
2142 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2143 return false;
2144 }
2145
Richard Smith745f5142012-01-27 01:14:48 +00002146 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002147
2148 // If it's a delegating constructor, just delegate.
2149 if (Definition->isDelegatingConstructor()) {
2150 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith83587db2012-02-15 02:18:13 +00002151 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
Richard Smith180f4792011-11-10 06:34:14 +00002152 }
2153
Richard Smith610a60c2012-01-10 04:32:03 +00002154 // For a trivial copy or move constructor, perform an APValue copy. This is
2155 // essential for unions, where the operations performed by the constructor
2156 // cannot be represented by ctor-initializers.
Richard Smith610a60c2012-01-10 04:32:03 +00002157 if (Definition->isDefaulted() &&
2158 ((Definition->isCopyConstructor() && RD->hasTrivialCopyConstructor()) ||
2159 (Definition->isMoveConstructor() && RD->hasTrivialMoveConstructor()))) {
2160 LValue RHS;
2161 RHS.setFrom(ArgValues[0]);
2162 CCValue Value;
Richard Smith745f5142012-01-27 01:14:48 +00002163 if (!HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2164 RHS, Value))
2165 return false;
2166 assert((Value.isStruct() || Value.isUnion()) &&
2167 "trivial copy/move from non-class type?");
2168 // Any CCValue of class type must already be a constant expression.
2169 Result = Value;
2170 return true;
Richard Smith610a60c2012-01-10 04:32:03 +00002171 }
2172
2173 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002174 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002175 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2176 std::distance(RD->field_begin(), RD->field_end()));
2177
2178 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2179
Richard Smith745f5142012-01-27 01:14:48 +00002180 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002181 unsigned BasesSeen = 0;
2182#ifndef NDEBUG
2183 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2184#endif
2185 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2186 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002187 LValue Subobject = This;
2188 APValue *Value = &Result;
2189
2190 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002191 if ((*I)->isBaseInitializer()) {
2192 QualType BaseType((*I)->getBaseClass(), 0);
2193#ifndef NDEBUG
2194 // Non-virtual base classes are initialized in the order in the class
Richard Smith86c3ae42012-02-13 03:54:03 +00002195 // definition. We have already checked for virtual base classes.
Richard Smith180f4792011-11-10 06:34:14 +00002196 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2197 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2198 "base class initializers not in expected order");
2199 ++BaseIt;
2200#endif
Richard Smithb4e85ed2012-01-06 16:39:00 +00002201 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smith180f4792011-11-10 06:34:14 +00002202 BaseType->getAsCXXRecordDecl(), &Layout);
Richard Smith745f5142012-01-27 01:14:48 +00002203 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002204 } else if (FieldDecl *FD = (*I)->getMember()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002205 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00002206 if (RD->isUnion()) {
2207 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002208 Value = &Result.getUnionValue();
2209 } else {
2210 Value = &Result.getStructField(FD->getFieldIndex());
2211 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002212 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002213 // Walk the indirect field decl's chain to find the object to initialize,
2214 // and make sure we've initialized every step along it.
2215 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2216 CE = IFD->chain_end();
2217 C != CE; ++C) {
2218 FieldDecl *FD = cast<FieldDecl>(*C);
2219 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2220 // Switch the union field if it differs. This happens if we had
2221 // preceding zero-initialization, and we're now initializing a union
2222 // subobject other than the first.
2223 // FIXME: In this case, the values of the other subobjects are
2224 // specified, since zero-initialization sets all padding bits to zero.
2225 if (Value->isUninit() ||
2226 (Value->isUnion() && Value->getUnionField() != FD)) {
2227 if (CD->isUnion())
2228 *Value = APValue(FD);
2229 else
2230 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2231 std::distance(CD->field_begin(), CD->field_end()));
2232 }
Richard Smith745f5142012-01-27 01:14:48 +00002233 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
Richard Smithd9b02e72012-01-25 22:15:11 +00002234 if (CD->isUnion())
2235 Value = &Value->getUnionValue();
2236 else
2237 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002238 }
Richard Smith180f4792011-11-10 06:34:14 +00002239 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002240 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002241 }
Richard Smith745f5142012-01-27 01:14:48 +00002242
Richard Smith83587db2012-02-15 02:18:13 +00002243 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2244 (*I)->isBaseInitializer()
Richard Smith745f5142012-01-27 01:14:48 +00002245 ? CCEK_Constant : CCEK_MemberInit)) {
2246 // If we're checking for a potential constant expression, evaluate all
2247 // initializers even if some of them fail.
2248 if (!Info.keepEvaluatingAfterFailure())
2249 return false;
2250 Success = false;
2251 }
Richard Smith180f4792011-11-10 06:34:14 +00002252 }
2253
Richard Smith745f5142012-01-27 01:14:48 +00002254 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002255}
2256
Richard Smithd0dccea2011-10-28 22:34:42 +00002257namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002258class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002259 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002260 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002261public:
2262
Richard Smith1e12c592011-10-16 21:26:27 +00002263 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002264
2265 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002266 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002267 return true;
2268 }
2269
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002270 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2271 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002272 return Visit(E->getResultExpr());
2273 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002274 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002275 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002276 return true;
2277 return false;
2278 }
John McCallf85e1932011-06-15 23:02:42 +00002279 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002280 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002281 return true;
2282 return false;
2283 }
2284 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002285 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002286 return true;
2287 return false;
2288 }
2289
Mike Stumpc4c90452009-10-27 22:09:17 +00002290 // We don't want to evaluate BlockExprs multiple times, as they generate
2291 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002292 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2293 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2294 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002295 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002296 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2297 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2298 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2299 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2300 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2301 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002302 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002303 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002304 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002305 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002306 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002307 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2308 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2309 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2310 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002311 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002312 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2313 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2314 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2315 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2316 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002317 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002318 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002319 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002320 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002321 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002322
2323 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002324 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002325 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2326 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002327 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002328 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002329 return false;
2330 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002331
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002332 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002333};
2334
John McCall56ca35d2011-02-17 10:25:35 +00002335class OpaqueValueEvaluation {
2336 EvalInfo &info;
2337 OpaqueValueExpr *opaqueValue;
2338
2339public:
2340 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2341 Expr *value)
2342 : info(info), opaqueValue(opaqueValue) {
2343
2344 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002345 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002346 this->opaqueValue = 0;
2347 return;
2348 }
John McCall56ca35d2011-02-17 10:25:35 +00002349 }
2350
2351 bool hasError() const { return opaqueValue == 0; }
2352
2353 ~OpaqueValueEvaluation() {
Richard Smith74e1ad92012-02-16 02:46:34 +00002354 // FIXME: For a recursive constexpr call, an outer stack frame might have
2355 // been using this opaque value too, and will now have to re-evaluate the
2356 // source expression.
John McCall56ca35d2011-02-17 10:25:35 +00002357 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2358 }
2359};
2360
Mike Stumpc4c90452009-10-27 22:09:17 +00002361} // end anonymous namespace
2362
Eli Friedman4efaa272008-11-12 09:44:48 +00002363//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002364// Generic Evaluation
2365//===----------------------------------------------------------------------===//
2366namespace {
2367
Richard Smithf48fdb02011-12-09 22:58:01 +00002368// FIXME: RetTy is always bool. Remove it.
2369template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002370class ExprEvaluatorBase
2371 : public ConstStmtVisitor<Derived, RetTy> {
2372private:
Richard Smith47a1eed2011-10-29 20:57:55 +00002373 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002374 return static_cast<Derived*>(this)->Success(V, E);
2375 }
Richard Smith51201882011-12-30 21:15:51 +00002376 RetTy DerivedZeroInitialization(const Expr *E) {
2377 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002378 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002379
Richard Smith74e1ad92012-02-16 02:46:34 +00002380 // Check whether a conditional operator with a non-constant condition is a
2381 // potential constant expression. If neither arm is a potential constant
2382 // expression, then the conditional operator is not either.
2383 template<typename ConditionalOperator>
2384 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2385 assert(Info.CheckingPotentialConstantExpression);
2386
2387 // Speculatively evaluate both arms.
2388 {
2389 llvm::SmallVector<PartialDiagnosticAt, 8> Diag;
2390 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2391
2392 StmtVisitorTy::Visit(E->getFalseExpr());
2393 if (Diag.empty())
2394 return;
2395
2396 Diag.clear();
2397 StmtVisitorTy::Visit(E->getTrueExpr());
2398 if (Diag.empty())
2399 return;
2400 }
2401
2402 Error(E, diag::note_constexpr_conditional_never_const);
2403 }
2404
2405
2406 template<typename ConditionalOperator>
2407 bool HandleConditionalOperator(const ConditionalOperator *E) {
2408 bool BoolResult;
2409 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2410 if (Info.CheckingPotentialConstantExpression)
2411 CheckPotentialConstantConditional(E);
2412 return false;
2413 }
2414
2415 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2416 return StmtVisitorTy::Visit(EvalExpr);
2417 }
2418
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002419protected:
2420 EvalInfo &Info;
2421 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2422 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2423
Richard Smithdd1f29b2011-12-12 09:28:41 +00002424 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd5093422011-12-12 09:41:58 +00002425 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002426 }
2427
2428 /// Report an evaluation error. This should only be called when an error is
2429 /// first discovered. When propagating an error, just return false.
2430 bool Error(const Expr *E, diag::kind D) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00002431 Info.Diag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002432 return false;
2433 }
2434 bool Error(const Expr *E) {
2435 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2436 }
2437
Richard Smith51201882011-12-30 21:15:51 +00002438 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00002439
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002440public:
2441 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2442
2443 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002444 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002445 }
2446 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002447 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002448 }
2449
2450 RetTy VisitParenExpr(const ParenExpr *E)
2451 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2452 RetTy VisitUnaryExtension(const UnaryOperator *E)
2453 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2454 RetTy VisitUnaryPlus(const UnaryOperator *E)
2455 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2456 RetTy VisitChooseExpr(const ChooseExpr *E)
2457 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2458 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2459 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002460 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2461 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002462 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2463 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002464 // We cannot create any objects for which cleanups are required, so there is
2465 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2466 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2467 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002468
Richard Smithc216a012011-12-12 12:46:16 +00002469 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2470 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2471 return static_cast<Derived*>(this)->VisitCastExpr(E);
2472 }
2473 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2474 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2475 return static_cast<Derived*>(this)->VisitCastExpr(E);
2476 }
2477
Richard Smithe24f5fc2011-11-17 22:56:20 +00002478 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2479 switch (E->getOpcode()) {
2480 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002481 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002482
2483 case BO_Comma:
2484 VisitIgnoredValue(E->getLHS());
2485 return StmtVisitorTy::Visit(E->getRHS());
2486
2487 case BO_PtrMemD:
2488 case BO_PtrMemI: {
2489 LValue Obj;
2490 if (!HandleMemberPointerAccess(Info, E, Obj))
2491 return false;
2492 CCValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002493 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002494 return false;
2495 return DerivedSuccess(Result, E);
2496 }
2497 }
2498 }
2499
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002500 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith74e1ad92012-02-16 02:46:34 +00002501 // Cache the value of the common expression.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002502 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2503 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002504 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002505
Richard Smith74e1ad92012-02-16 02:46:34 +00002506 return HandleConditionalOperator(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002507 }
2508
2509 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002510 bool IsBcpCall = false;
2511 // If the condition (ignoring parens) is a __builtin_constant_p call,
2512 // the result is a constant expression if it can be folded without
2513 // side-effects. This is an important GNU extension. See GCC PR38377
2514 // for discussion.
2515 if (const CallExpr *CallCE =
2516 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2517 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2518 IsBcpCall = true;
2519
2520 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2521 // constant expression; we can't check whether it's potentially foldable.
2522 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2523 return false;
2524
2525 FoldConstant Fold(Info);
2526
Richard Smith74e1ad92012-02-16 02:46:34 +00002527 if (!HandleConditionalOperator(E))
Richard Smithf15fda02012-02-02 01:16:57 +00002528 return false;
2529
2530 if (IsBcpCall)
2531 Fold.Fold(Info);
2532
2533 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002534 }
2535
2536 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002537 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002538 if (!Value) {
2539 const Expr *Source = E->getSourceExpr();
2540 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002541 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002542 if (Source == E) { // sanity checking.
2543 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002544 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002545 }
2546 return StmtVisitorTy::Visit(Source);
2547 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002548 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002549 }
Richard Smithf10d9172011-10-11 21:43:33 +00002550
Richard Smithd0dccea2011-10-28 22:34:42 +00002551 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002552 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002553 QualType CalleeType = Callee->getType();
2554
Richard Smithd0dccea2011-10-28 22:34:42 +00002555 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002556 LValue *This = 0, ThisVal;
2557 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith86c3ae42012-02-13 03:54:03 +00002558 bool HasQualifier = false;
Richard Smith6c957872011-11-10 09:31:24 +00002559
Richard Smith59efe262011-11-11 04:05:33 +00002560 // Extract function decl and 'this' pointer from the callee.
2561 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002562 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002563 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2564 // Explicit bound member calls, such as x.f() or p->g();
2565 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002566 return false;
2567 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002568 This = &ThisVal;
Richard Smith86c3ae42012-02-13 03:54:03 +00002569 HasQualifier = ME->hasQualifier();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002570 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2571 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002572 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2573 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002574 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002575 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002576 return Error(Callee);
2577
2578 FD = dyn_cast<FunctionDecl>(Member);
2579 if (!FD)
2580 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002581 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002582 LValue Call;
2583 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002584 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002585
Richard Smithb4e85ed2012-01-06 16:39:00 +00002586 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002587 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002588 FD = dyn_cast_or_null<FunctionDecl>(
2589 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002590 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002591 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002592
2593 // Overloaded operator calls to member functions are represented as normal
2594 // calls with '*this' as the first argument.
2595 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2596 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002597 // FIXME: When selecting an implicit conversion for an overloaded
2598 // operator delete, we sometimes try to evaluate calls to conversion
2599 // operators without a 'this' parameter!
2600 if (Args.empty())
2601 return Error(E);
2602
Richard Smith59efe262011-11-11 04:05:33 +00002603 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2604 return false;
2605 This = &ThisVal;
2606 Args = Args.slice(1);
2607 }
2608
2609 // Don't call function pointers which have been cast to some other type.
2610 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002611 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002612 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002613 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002614
Richard Smithb04035a2012-02-01 02:39:43 +00002615 if (This && !This->checkSubobject(Info, E, CSK_This))
2616 return false;
2617
Richard Smith86c3ae42012-02-13 03:54:03 +00002618 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2619 // calls to such functions in constant expressions.
2620 if (This && !HasQualifier &&
2621 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2622 return Error(E, diag::note_constexpr_virtual_call);
2623
Richard Smithc1c5f272011-12-13 06:39:58 +00002624 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002625 Stmt *Body = FD->getBody(Definition);
Richard Smith83587db2012-02-15 02:18:13 +00002626 CCValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002627
Richard Smithc1c5f272011-12-13 06:39:58 +00002628 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002629 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2630 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002631 return false;
2632
Richard Smith83587db2012-02-15 02:18:13 +00002633 return DerivedSuccess(Result, E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002634 }
2635
Richard Smithc49bd112011-10-28 17:51:58 +00002636 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2637 return StmtVisitorTy::Visit(E->getInitializer());
2638 }
Richard Smithf10d9172011-10-11 21:43:33 +00002639 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002640 if (E->getNumInits() == 0)
2641 return DerivedZeroInitialization(E);
2642 if (E->getNumInits() == 1)
2643 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002644 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002645 }
2646 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002647 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002648 }
2649 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002650 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002651 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002652 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002653 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002654 }
Richard Smithf10d9172011-10-11 21:43:33 +00002655
Richard Smith180f4792011-11-10 06:34:14 +00002656 /// A member expression where the object is a prvalue is itself a prvalue.
2657 RetTy VisitMemberExpr(const MemberExpr *E) {
2658 assert(!E->isArrow() && "missing call to bound member function?");
2659
2660 CCValue Val;
2661 if (!Evaluate(Val, Info, E->getBase()))
2662 return false;
2663
2664 QualType BaseTy = E->getBase()->getType();
2665
2666 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002667 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002668 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2669 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2670 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2671
Richard Smithb4e85ed2012-01-06 16:39:00 +00002672 SubobjectDesignator Designator(BaseTy);
2673 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002674
Richard Smithf48fdb02011-12-09 22:58:01 +00002675 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002676 DerivedSuccess(Val, E);
2677 }
2678
Richard Smithc49bd112011-10-28 17:51:58 +00002679 RetTy VisitCastExpr(const CastExpr *E) {
2680 switch (E->getCastKind()) {
2681 default:
2682 break;
2683
David Chisnall7a7ee302012-01-16 17:27:18 +00002684 case CK_AtomicToNonAtomic:
2685 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002686 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002687 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002688 return StmtVisitorTy::Visit(E->getSubExpr());
2689
2690 case CK_LValueToRValue: {
2691 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002692 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2693 return false;
2694 CCValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00002695 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2696 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2697 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002698 return false;
2699 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002700 }
2701 }
2702
Richard Smithf48fdb02011-12-09 22:58:01 +00002703 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002704 }
2705
Richard Smith8327fad2011-10-24 18:44:57 +00002706 /// Visit a value which is evaluated, but whose value is ignored.
2707 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002708 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002709 if (!Evaluate(Scratch, Info, E))
2710 Info.EvalStatus.HasSideEffects = true;
2711 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002712};
2713
2714}
2715
2716//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002717// Common base class for lvalue and temporary evaluation.
2718//===----------------------------------------------------------------------===//
2719namespace {
2720template<class Derived>
2721class LValueExprEvaluatorBase
2722 : public ExprEvaluatorBase<Derived, bool> {
2723protected:
2724 LValue &Result;
2725 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2726 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2727
2728 bool Success(APValue::LValueBase B) {
2729 Result.set(B);
2730 return true;
2731 }
2732
2733public:
2734 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2735 ExprEvaluatorBaseTy(Info), Result(Result) {}
2736
2737 bool Success(const CCValue &V, const Expr *E) {
2738 Result.setFrom(V);
2739 return true;
2740 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002741
Richard Smithe24f5fc2011-11-17 22:56:20 +00002742 bool VisitMemberExpr(const MemberExpr *E) {
2743 // Handle non-static data members.
2744 QualType BaseTy;
2745 if (E->isArrow()) {
2746 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2747 return false;
2748 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002749 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002750 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002751 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2752 return false;
2753 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002754 } else {
2755 if (!this->Visit(E->getBase()))
2756 return false;
2757 BaseTy = E->getBase()->getType();
2758 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002759
Richard Smithd9b02e72012-01-25 22:15:11 +00002760 const ValueDecl *MD = E->getMemberDecl();
2761 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2762 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2763 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2764 (void)BaseTy;
2765 HandleLValueMember(this->Info, E, Result, FD);
2766 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2767 HandleLValueIndirectMember(this->Info, E, Result, IFD);
2768 } else
2769 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002770
Richard Smithd9b02e72012-01-25 22:15:11 +00002771 if (MD->getType()->isReferenceType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002772 CCValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002773 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002774 RefValue))
2775 return false;
2776 return Success(RefValue, E);
2777 }
2778 return true;
2779 }
2780
2781 bool VisitBinaryOperator(const BinaryOperator *E) {
2782 switch (E->getOpcode()) {
2783 default:
2784 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2785
2786 case BO_PtrMemD:
2787 case BO_PtrMemI:
2788 return HandleMemberPointerAccess(this->Info, E, Result);
2789 }
2790 }
2791
2792 bool VisitCastExpr(const CastExpr *E) {
2793 switch (E->getCastKind()) {
2794 default:
2795 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2796
2797 case CK_DerivedToBase:
2798 case CK_UncheckedDerivedToBase: {
2799 if (!this->Visit(E->getSubExpr()))
2800 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002801
2802 // Now figure out the necessary offset to add to the base LV to get from
2803 // the derived class to the base class.
2804 QualType Type = E->getSubExpr()->getType();
2805
2806 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2807 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002808 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002809 *PathI))
2810 return false;
2811 Type = (*PathI)->getType();
2812 }
2813
2814 return true;
2815 }
2816 }
2817 }
2818};
2819}
2820
2821//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002822// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002823//
2824// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2825// function designators (in C), decl references to void objects (in C), and
2826// temporaries (if building with -Wno-address-of-temporary).
2827//
2828// LValue evaluation produces values comprising a base expression of one of the
2829// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002830// - Declarations
2831// * VarDecl
2832// * FunctionDecl
2833// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002834// * CompoundLiteralExpr in C
2835// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002836// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002837// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002838// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002839// * ObjCEncodeExpr
2840// * AddrLabelExpr
2841// * BlockExpr
2842// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002843// - Locals and temporaries
Richard Smith83587db2012-02-15 02:18:13 +00002844// * Any Expr, with a CallIndex indicating the function in which the temporary
2845// was evaluated.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002846// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002847//===----------------------------------------------------------------------===//
2848namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002849class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002850 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002851public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002852 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2853 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002854
Richard Smithc49bd112011-10-28 17:51:58 +00002855 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2856
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002857 bool VisitDeclRefExpr(const DeclRefExpr *E);
2858 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002859 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002860 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2861 bool VisitMemberExpr(const MemberExpr *E);
2862 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2863 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002864 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002865 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2866 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002867
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002868 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002869 switch (E->getCastKind()) {
2870 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002871 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002872
Eli Friedmandb924222011-10-11 00:13:24 +00002873 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002874 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002875 if (!Visit(E->getSubExpr()))
2876 return false;
2877 Result.Designator.setInvalid();
2878 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002879
Richard Smithe24f5fc2011-11-17 22:56:20 +00002880 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002881 if (!Visit(E->getSubExpr()))
2882 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002883 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002884 }
2885 }
Sebastian Redlcea8d962011-09-24 17:48:14 +00002886
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002887 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002888
Eli Friedman4efaa272008-11-12 09:44:48 +00002889};
2890} // end anonymous namespace
2891
Richard Smithc49bd112011-10-28 17:51:58 +00002892/// Evaluate an expression as an lvalue. This can be legitimately called on
2893/// expressions which are not glvalues, in a few cases:
2894/// * function designators in C,
2895/// * "extern void" objects,
2896/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002897static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002898 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2899 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2900 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002901 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002902}
2903
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002904bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002905 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2906 return Success(FD);
2907 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002908 return VisitVarDecl(E, VD);
2909 return Error(E);
2910}
Richard Smith436c8892011-10-24 23:14:33 +00002911
Richard Smithc49bd112011-10-28 17:51:58 +00002912bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002913 if (!VD->getType()->isReferenceType()) {
2914 if (isa<ParmVarDecl>(VD)) {
Richard Smith83587db2012-02-15 02:18:13 +00002915 Result.set(VD, Info.CurrentCall->Index);
Richard Smith177dce72011-11-01 16:57:24 +00002916 return true;
2917 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002918 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002919 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002920
Richard Smith47a1eed2011-10-29 20:57:55 +00002921 CCValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002922 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2923 return false;
2924 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002925}
2926
Richard Smithbd552ef2011-10-31 05:52:43 +00002927bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2928 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002929 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002930 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002931 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2932
Richard Smith83587db2012-02-15 02:18:13 +00002933 Result.set(E, Info.CurrentCall->Index);
2934 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2935 Result, E->GetTemporaryExpr());
Richard Smithe24f5fc2011-11-17 22:56:20 +00002936 }
2937
2938 // Materialization of an lvalue temporary occurs when we need to force a copy
2939 // (for instance, if it's a bitfield).
2940 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2941 if (!Visit(E->GetTemporaryExpr()))
2942 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002943 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002944 Info.CurrentCall->Temporaries[E]))
2945 return false;
Richard Smith83587db2012-02-15 02:18:13 +00002946 Result.set(E, Info.CurrentCall->Index);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002947 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002948}
2949
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002950bool
2951LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002952 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2953 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2954 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002955 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002956}
2957
Richard Smith47d21452011-12-27 12:18:28 +00002958bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2959 if (E->isTypeOperand())
2960 return Success(E);
2961 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2962 if (RD && RD->isPolymorphic()) {
2963 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2964 << E->getExprOperand()->getType()
2965 << E->getExprOperand()->getSourceRange();
2966 return false;
2967 }
2968 return Success(E);
2969}
2970
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002971bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002972 // Handle static data members.
2973 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2974 VisitIgnoredValue(E->getBase());
2975 return VisitVarDecl(E, VD);
2976 }
2977
Richard Smithd0dccea2011-10-28 22:34:42 +00002978 // Handle static member functions.
2979 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2980 if (MD->isStatic()) {
2981 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002982 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002983 }
2984 }
2985
Richard Smith180f4792011-11-10 06:34:14 +00002986 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002987 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002988}
2989
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002990bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002991 // FIXME: Deal with vectors as array subscript bases.
2992 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002993 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002994
Anders Carlsson3068d112008-11-16 19:01:22 +00002995 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002996 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002997
Anders Carlsson3068d112008-11-16 19:01:22 +00002998 APSInt Index;
2999 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003000 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003001 int64_t IndexValue
3002 = Index.isSigned() ? Index.getSExtValue()
3003 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00003004
Richard Smithb4e85ed2012-01-06 16:39:00 +00003005 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00003006}
Eli Friedman4efaa272008-11-12 09:44:48 +00003007
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003008bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00003009 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00003010}
3011
Eli Friedman4efaa272008-11-12 09:44:48 +00003012//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003013// Pointer Evaluation
3014//===----------------------------------------------------------------------===//
3015
Anders Carlssonc754aa62008-07-08 05:13:58 +00003016namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003017class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003018 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00003019 LValue &Result;
3020
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003021 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003022 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00003023 return true;
3024 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003025public:
Mike Stump1eb44332009-09-09 15:08:12 +00003026
John McCallefdb83e2010-05-07 21:00:08 +00003027 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003028 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003029
Richard Smith47a1eed2011-10-29 20:57:55 +00003030 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003031 Result.setFrom(V);
3032 return true;
3033 }
Richard Smith51201882011-12-30 21:15:51 +00003034 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00003035 return Success((Expr*)0);
3036 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003037
John McCallefdb83e2010-05-07 21:00:08 +00003038 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003039 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00003040 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003041 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00003042 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003043 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00003044 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003045 bool VisitCallExpr(const CallExpr *E);
3046 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00003047 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00003048 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00003049 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00003050 }
Richard Smith180f4792011-11-10 06:34:14 +00003051 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3052 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00003053 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003054 Result = *Info.CurrentCall->This;
3055 return true;
3056 }
John McCall56ca35d2011-02-17 10:25:35 +00003057
Eli Friedmanba98d6b2009-03-23 04:56:01 +00003058 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00003059};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003060} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003061
John McCallefdb83e2010-05-07 21:00:08 +00003062static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003063 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003064 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003065}
3066
John McCallefdb83e2010-05-07 21:00:08 +00003067bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003068 if (E->getOpcode() != BO_Add &&
3069 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00003070 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003071
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003072 const Expr *PExp = E->getLHS();
3073 const Expr *IExp = E->getRHS();
3074 if (IExp->getType()->isPointerType())
3075 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003076
Richard Smith745f5142012-01-27 01:14:48 +00003077 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3078 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00003079 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003080
John McCallefdb83e2010-05-07 21:00:08 +00003081 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00003082 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00003083 return false;
3084 int64_t AdditionalOffset
3085 = Offset.isSigned() ? Offset.getSExtValue()
3086 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00003087 if (E->getOpcode() == BO_Sub)
3088 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003089
Richard Smith180f4792011-11-10 06:34:14 +00003090 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00003091 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3092 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003093}
Eli Friedman4efaa272008-11-12 09:44:48 +00003094
John McCallefdb83e2010-05-07 21:00:08 +00003095bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3096 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003097}
Mike Stump1eb44332009-09-09 15:08:12 +00003098
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003099bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3100 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003101
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003102 switch (E->getCastKind()) {
3103 default:
3104 break;
3105
John McCall2de56d12010-08-25 11:45:40 +00003106 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003107 case CK_CPointerToObjCPointerCast:
3108 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00003109 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00003110 if (!Visit(SubExpr))
3111 return false;
Richard Smithc216a012011-12-12 12:46:16 +00003112 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3113 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3114 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003115 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00003116 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003117 if (SubExpr->getType()->isVoidPointerType())
3118 CCEDiag(E, diag::note_constexpr_invalid_cast)
3119 << 3 << SubExpr->getType();
3120 else
3121 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3122 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003123 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003124
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003125 case CK_DerivedToBase:
3126 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00003127 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003128 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003129 if (!Result.Base && Result.Offset.isZero())
3130 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003131
Richard Smith180f4792011-11-10 06:34:14 +00003132 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003133 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00003134 QualType Type =
3135 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003136
Richard Smith180f4792011-11-10 06:34:14 +00003137 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003138 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003139 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3140 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003141 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003142 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003143 }
3144
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003145 return true;
3146 }
3147
Richard Smithe24f5fc2011-11-17 22:56:20 +00003148 case CK_BaseToDerived:
3149 if (!Visit(E->getSubExpr()))
3150 return false;
3151 if (!Result.Base && Result.Offset.isZero())
3152 return true;
3153 return HandleBaseToDerivedCast(Info, E, Result);
3154
Richard Smith47a1eed2011-10-29 20:57:55 +00003155 case CK_NullToPointer:
Richard Smith51201882011-12-30 21:15:51 +00003156 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00003157
John McCall2de56d12010-08-25 11:45:40 +00003158 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003159 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3160
Richard Smith47a1eed2011-10-29 20:57:55 +00003161 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003162 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003163 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003164
John McCallefdb83e2010-05-07 21:00:08 +00003165 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003166 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3167 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003168 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003169 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith83587db2012-02-15 02:18:13 +00003170 Result.CallIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003171 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003172 return true;
3173 } else {
3174 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00003175 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00003176 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003177 }
3178 }
John McCall2de56d12010-08-25 11:45:40 +00003179 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003180 if (SubExpr->isGLValue()) {
3181 if (!EvaluateLValue(SubExpr, Result, Info))
3182 return false;
3183 } else {
Richard Smith83587db2012-02-15 02:18:13 +00003184 Result.set(SubExpr, Info.CurrentCall->Index);
3185 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3186 Info, Result, SubExpr))
Richard Smithe24f5fc2011-11-17 22:56:20 +00003187 return false;
3188 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003189 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003190 if (const ConstantArrayType *CAT
3191 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3192 Result.addArray(Info, E, CAT);
3193 else
3194 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003195 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003196
John McCall2de56d12010-08-25 11:45:40 +00003197 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003198 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003199 }
3200
Richard Smithc49bd112011-10-28 17:51:58 +00003201 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003202}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003203
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003204bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003205 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003206 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003207
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003208 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003209}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003210
3211//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003212// Member Pointer Evaluation
3213//===----------------------------------------------------------------------===//
3214
3215namespace {
3216class MemberPointerExprEvaluator
3217 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3218 MemberPtr &Result;
3219
3220 bool Success(const ValueDecl *D) {
3221 Result = MemberPtr(D);
3222 return true;
3223 }
3224public:
3225
3226 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3227 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3228
3229 bool Success(const CCValue &V, const Expr *E) {
3230 Result.setFrom(V);
3231 return true;
3232 }
Richard Smith51201882011-12-30 21:15:51 +00003233 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003234 return Success((const ValueDecl*)0);
3235 }
3236
3237 bool VisitCastExpr(const CastExpr *E);
3238 bool VisitUnaryAddrOf(const UnaryOperator *E);
3239};
3240} // end anonymous namespace
3241
3242static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3243 EvalInfo &Info) {
3244 assert(E->isRValue() && E->getType()->isMemberPointerType());
3245 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3246}
3247
3248bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3249 switch (E->getCastKind()) {
3250 default:
3251 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3252
3253 case CK_NullToMemberPointer:
Richard Smith51201882011-12-30 21:15:51 +00003254 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003255
3256 case CK_BaseToDerivedMemberPointer: {
3257 if (!Visit(E->getSubExpr()))
3258 return false;
3259 if (E->path_empty())
3260 return true;
3261 // Base-to-derived member pointer casts store the path in derived-to-base
3262 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3263 // the wrong end of the derived->base arc, so stagger the path by one class.
3264 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3265 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3266 PathI != PathE; ++PathI) {
3267 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3268 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3269 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003270 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003271 }
3272 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3273 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003274 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003275 return true;
3276 }
3277
3278 case CK_DerivedToBaseMemberPointer:
3279 if (!Visit(E->getSubExpr()))
3280 return false;
3281 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3282 PathE = E->path_end(); PathI != PathE; ++PathI) {
3283 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3284 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3285 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003286 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003287 }
3288 return true;
3289 }
3290}
3291
3292bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3293 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3294 // member can be formed.
3295 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3296}
3297
3298//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003299// Record Evaluation
3300//===----------------------------------------------------------------------===//
3301
3302namespace {
3303 class RecordExprEvaluator
3304 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3305 const LValue &This;
3306 APValue &Result;
3307 public:
3308
3309 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3310 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3311
3312 bool Success(const CCValue &V, const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003313 Result = V;
3314 return true;
Richard Smith180f4792011-11-10 06:34:14 +00003315 }
Richard Smith51201882011-12-30 21:15:51 +00003316 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003317
Richard Smith59efe262011-11-11 04:05:33 +00003318 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003319 bool VisitInitListExpr(const InitListExpr *E);
3320 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3321 };
3322}
3323
Richard Smith51201882011-12-30 21:15:51 +00003324/// Perform zero-initialization on an object of non-union class type.
3325/// C++11 [dcl.init]p5:
3326/// To zero-initialize an object or reference of type T means:
3327/// [...]
3328/// -- if T is a (possibly cv-qualified) non-union class type,
3329/// each non-static data member and each base-class subobject is
3330/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003331static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3332 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003333 const LValue &This, APValue &Result) {
3334 assert(!RD->isUnion() && "Expected non-union class type");
3335 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3336 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3337 std::distance(RD->field_begin(), RD->field_end()));
3338
3339 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3340
3341 if (CD) {
3342 unsigned Index = 0;
3343 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003344 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003345 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3346 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003347 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3348 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003349 Result.getStructBase(Index)))
3350 return false;
3351 }
3352 }
3353
Richard Smithb4e85ed2012-01-06 16:39:00 +00003354 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3355 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003356 // -- if T is a reference type, no initialization is performed.
3357 if ((*I)->getType()->isReferenceType())
3358 continue;
3359
3360 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003361 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smith51201882011-12-30 21:15:51 +00003362
3363 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003364 if (!EvaluateInPlace(
Richard Smith51201882011-12-30 21:15:51 +00003365 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3366 return false;
3367 }
3368
3369 return true;
3370}
3371
3372bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3373 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3374 if (RD->isUnion()) {
3375 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3376 // object's first non-static named data member is zero-initialized
3377 RecordDecl::field_iterator I = RD->field_begin();
3378 if (I == RD->field_end()) {
3379 Result = APValue((const FieldDecl*)0);
3380 return true;
3381 }
3382
3383 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003384 HandleLValueMember(Info, E, Subobject, *I);
Richard Smith51201882011-12-30 21:15:51 +00003385 Result = APValue(*I);
3386 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003387 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003388 }
3389
Richard Smithb4e85ed2012-01-06 16:39:00 +00003390 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003391}
3392
Richard Smith59efe262011-11-11 04:05:33 +00003393bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3394 switch (E->getCastKind()) {
3395 default:
3396 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3397
3398 case CK_ConstructorConversion:
3399 return Visit(E->getSubExpr());
3400
3401 case CK_DerivedToBase:
3402 case CK_UncheckedDerivedToBase: {
3403 CCValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003404 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003405 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003406 if (!DerivedObject.isStruct())
3407 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003408
3409 // Derived-to-base rvalue conversion: just slice off the derived part.
3410 APValue *Value = &DerivedObject;
3411 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3412 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3413 PathE = E->path_end(); PathI != PathE; ++PathI) {
3414 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3415 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3416 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3417 RD = Base;
3418 }
3419 Result = *Value;
3420 return true;
3421 }
3422 }
3423}
3424
Richard Smith180f4792011-11-10 06:34:14 +00003425bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3426 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3427 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3428
3429 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003430 const FieldDecl *Field = E->getInitializedFieldInUnion();
3431 Result = APValue(Field);
3432 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003433 return true;
Richard Smithec789162012-01-12 18:54:33 +00003434
3435 // If the initializer list for a union does not contain any elements, the
3436 // first element of the union is value-initialized.
3437 ImplicitValueInitExpr VIE(Field->getType());
3438 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3439
Richard Smith180f4792011-11-10 06:34:14 +00003440 LValue Subobject = This;
Richard Smithec789162012-01-12 18:54:33 +00003441 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
Richard Smith83587db2012-02-15 02:18:13 +00003442 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003443 }
3444
3445 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3446 "initializer list for class with base classes");
3447 Result = APValue(APValue::UninitStruct(), 0,
3448 std::distance(RD->field_begin(), RD->field_end()));
3449 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003450 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003451 for (RecordDecl::field_iterator Field = RD->field_begin(),
3452 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3453 // Anonymous bit-fields are not considered members of the class for
3454 // purposes of aggregate initialization.
3455 if (Field->isUnnamedBitfield())
3456 continue;
3457
3458 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003459
Richard Smith745f5142012-01-27 01:14:48 +00003460 bool HaveInit = ElementNo < E->getNumInits();
3461
3462 // FIXME: Diagnostics here should point to the end of the initializer
3463 // list, not the start.
3464 HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3465 *Field, &Layout);
3466
3467 // Perform an implicit value-initialization for members beyond the end of
3468 // the initializer list.
3469 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3470
Richard Smith83587db2012-02-15 02:18:13 +00003471 if (!EvaluateInPlace(
Richard Smith745f5142012-01-27 01:14:48 +00003472 Result.getStructField((*Field)->getFieldIndex()),
3473 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3474 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003475 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003476 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003477 }
3478 }
3479
Richard Smith745f5142012-01-27 01:14:48 +00003480 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003481}
3482
3483bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3484 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith51201882011-12-30 21:15:51 +00003485 bool ZeroInit = E->requiresZeroInitialization();
3486 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003487 // If we've already performed zero-initialization, we're already done.
3488 if (!Result.isUninit())
3489 return true;
3490
Richard Smith51201882011-12-30 21:15:51 +00003491 if (ZeroInit)
3492 return ZeroInitialization(E);
3493
Richard Smith61802452011-12-22 02:22:31 +00003494 const CXXRecordDecl *RD = FD->getParent();
3495 if (RD->isUnion())
3496 Result = APValue((FieldDecl*)0);
3497 else
3498 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3499 std::distance(RD->field_begin(), RD->field_end()));
3500 return true;
3501 }
3502
Richard Smith180f4792011-11-10 06:34:14 +00003503 const FunctionDecl *Definition = 0;
3504 FD->getBody(Definition);
3505
Richard Smithc1c5f272011-12-13 06:39:58 +00003506 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3507 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003508
Richard Smith610a60c2012-01-10 04:32:03 +00003509 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003510 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003511 if (const MaterializeTemporaryExpr *ME
3512 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3513 return Visit(ME->GetTemporaryExpr());
3514
Richard Smith51201882011-12-30 21:15:51 +00003515 if (ZeroInit && !ZeroInitialization(E))
3516 return false;
3517
Richard Smith180f4792011-11-10 06:34:14 +00003518 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003519 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003520 cast<CXXConstructorDecl>(Definition), Info,
3521 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003522}
3523
3524static bool EvaluateRecord(const Expr *E, const LValue &This,
3525 APValue &Result, EvalInfo &Info) {
3526 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003527 "can't evaluate expression as a record rvalue");
3528 return RecordExprEvaluator(Info, This, Result).Visit(E);
3529}
3530
3531//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003532// Temporary Evaluation
3533//
3534// Temporaries are represented in the AST as rvalues, but generally behave like
3535// lvalues. The full-object of which the temporary is a subobject is implicitly
3536// materialized so that a reference can bind to it.
3537//===----------------------------------------------------------------------===//
3538namespace {
3539class TemporaryExprEvaluator
3540 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3541public:
3542 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3543 LValueExprEvaluatorBaseTy(Info, Result) {}
3544
3545 /// Visit an expression which constructs the value of this temporary.
3546 bool VisitConstructExpr(const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003547 Result.set(E, Info.CurrentCall->Index);
3548 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003549 }
3550
3551 bool VisitCastExpr(const CastExpr *E) {
3552 switch (E->getCastKind()) {
3553 default:
3554 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3555
3556 case CK_ConstructorConversion:
3557 return VisitConstructExpr(E->getSubExpr());
3558 }
3559 }
3560 bool VisitInitListExpr(const InitListExpr *E) {
3561 return VisitConstructExpr(E);
3562 }
3563 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3564 return VisitConstructExpr(E);
3565 }
3566 bool VisitCallExpr(const CallExpr *E) {
3567 return VisitConstructExpr(E);
3568 }
3569};
3570} // end anonymous namespace
3571
3572/// Evaluate an expression of record type as a temporary.
3573static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003574 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003575 return TemporaryExprEvaluator(Info, Result).Visit(E);
3576}
3577
3578//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003579// Vector Evaluation
3580//===----------------------------------------------------------------------===//
3581
3582namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003583 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003584 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3585 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003586 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003587
Richard Smith07fc6572011-10-22 21:10:00 +00003588 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3589 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003590
Richard Smith07fc6572011-10-22 21:10:00 +00003591 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3592 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3593 // FIXME: remove this APValue copy.
3594 Result = APValue(V.data(), V.size());
3595 return true;
3596 }
Richard Smith69c2c502011-11-04 05:33:44 +00003597 bool Success(const CCValue &V, const Expr *E) {
3598 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003599 Result = V;
3600 return true;
3601 }
Richard Smith51201882011-12-30 21:15:51 +00003602 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003603
Richard Smith07fc6572011-10-22 21:10:00 +00003604 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003605 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003606 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003607 bool VisitInitListExpr(const InitListExpr *E);
3608 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003609 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003610 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003611 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003612 };
3613} // end anonymous namespace
3614
3615static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003616 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003617 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003618}
3619
Richard Smith07fc6572011-10-22 21:10:00 +00003620bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3621 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003622 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003623
Richard Smithd62ca372011-12-06 22:44:34 +00003624 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003625 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003626
Eli Friedman46a52322011-03-25 00:43:55 +00003627 switch (E->getCastKind()) {
3628 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003629 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003630 if (SETy->isIntegerType()) {
3631 APSInt IntResult;
3632 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003633 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003634 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003635 } else if (SETy->isRealFloatingType()) {
3636 APFloat F(0.0);
3637 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003638 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003639 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003640 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003641 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003642 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003643
3644 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003645 SmallVector<APValue, 4> Elts(NElts, Val);
3646 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003647 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003648 case CK_BitCast: {
3649 // Evaluate the operand into an APInt we can extract from.
3650 llvm::APInt SValInt;
3651 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3652 return false;
3653 // Extract the elements
3654 QualType EltTy = VTy->getElementType();
3655 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3656 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3657 SmallVector<APValue, 4> Elts;
3658 if (EltTy->isRealFloatingType()) {
3659 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3660 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3661 unsigned FloatEltSize = EltSize;
3662 if (&Sem == &APFloat::x87DoubleExtended)
3663 FloatEltSize = 80;
3664 for (unsigned i = 0; i < NElts; i++) {
3665 llvm::APInt Elt;
3666 if (BigEndian)
3667 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3668 else
3669 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3670 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3671 }
3672 } else if (EltTy->isIntegerType()) {
3673 for (unsigned i = 0; i < NElts; i++) {
3674 llvm::APInt Elt;
3675 if (BigEndian)
3676 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3677 else
3678 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3679 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3680 }
3681 } else {
3682 return Error(E);
3683 }
3684 return Success(Elts, E);
3685 }
Eli Friedman46a52322011-03-25 00:43:55 +00003686 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003687 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003688 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003689}
3690
Richard Smith07fc6572011-10-22 21:10:00 +00003691bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003692VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003693 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003694 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003695 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003696
Nate Begeman59b5da62009-01-18 03:20:47 +00003697 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003698 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003699
Eli Friedman3edd5a92012-01-03 23:24:20 +00003700 // The number of initializers can be less than the number of
3701 // vector elements. For OpenCL, this can be due to nested vector
3702 // initialization. For GCC compatibility, missing trailing elements
3703 // should be initialized with zeroes.
3704 unsigned CountInits = 0, CountElts = 0;
3705 while (CountElts < NumElements) {
3706 // Handle nested vector initialization.
3707 if (CountInits < NumInits
3708 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3709 APValue v;
3710 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3711 return Error(E);
3712 unsigned vlen = v.getVectorLength();
3713 for (unsigned j = 0; j < vlen; j++)
3714 Elements.push_back(v.getVectorElt(j));
3715 CountElts += vlen;
3716 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003717 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003718 if (CountInits < NumInits) {
3719 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3720 return Error(E);
3721 } else // trailing integer zero.
3722 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3723 Elements.push_back(APValue(sInt));
3724 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003725 } else {
3726 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003727 if (CountInits < NumInits) {
3728 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3729 return Error(E);
3730 } else // trailing float zero.
3731 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3732 Elements.push_back(APValue(f));
3733 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003734 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003735 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003736 }
Richard Smith07fc6572011-10-22 21:10:00 +00003737 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003738}
3739
Richard Smith07fc6572011-10-22 21:10:00 +00003740bool
Richard Smith51201882011-12-30 21:15:51 +00003741VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003742 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003743 QualType EltTy = VT->getElementType();
3744 APValue ZeroElement;
3745 if (EltTy->isIntegerType())
3746 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3747 else
3748 ZeroElement =
3749 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3750
Chris Lattner5f9e2722011-07-23 10:55:15 +00003751 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003752 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003753}
3754
Richard Smith07fc6572011-10-22 21:10:00 +00003755bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003756 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003757 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003758}
3759
Nate Begeman59b5da62009-01-18 03:20:47 +00003760//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003761// Array Evaluation
3762//===----------------------------------------------------------------------===//
3763
3764namespace {
3765 class ArrayExprEvaluator
3766 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003767 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003768 APValue &Result;
3769 public:
3770
Richard Smith180f4792011-11-10 06:34:14 +00003771 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3772 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003773
3774 bool Success(const APValue &V, const Expr *E) {
3775 assert(V.isArray() && "Expected array type");
3776 Result = V;
3777 return true;
3778 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003779
Richard Smith51201882011-12-30 21:15:51 +00003780 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003781 const ConstantArrayType *CAT =
3782 Info.Ctx.getAsConstantArrayType(E->getType());
3783 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003784 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003785
3786 Result = APValue(APValue::UninitArray(), 0,
3787 CAT->getSize().getZExtValue());
3788 if (!Result.hasArrayFiller()) return true;
3789
Richard Smith51201882011-12-30 21:15:51 +00003790 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003791 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003792 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003793 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003794 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith180f4792011-11-10 06:34:14 +00003795 }
3796
Richard Smithcc5d4f62011-11-07 09:22:26 +00003797 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003798 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003799 };
3800} // end anonymous namespace
3801
Richard Smith180f4792011-11-10 06:34:14 +00003802static bool EvaluateArray(const Expr *E, const LValue &This,
3803 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003804 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003805 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003806}
3807
3808bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3809 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3810 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003811 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003812
Richard Smith974c5f92011-12-22 01:07:19 +00003813 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3814 // an appropriately-typed string literal enclosed in braces.
Richard Smithec789162012-01-12 18:54:33 +00003815 if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
Richard Smith974c5f92011-12-22 01:07:19 +00003816 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3817 LValue LV;
3818 if (!EvaluateLValue(E->getInit(0), LV, Info))
3819 return false;
3820 uint64_t NumElements = CAT->getSize().getZExtValue();
3821 Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3822
3823 // Copy the string literal into the array. FIXME: Do this better.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003824 LV.addArray(Info, E, CAT);
Richard Smith974c5f92011-12-22 01:07:19 +00003825 for (uint64_t I = 0; I < NumElements; ++I) {
3826 CCValue Char;
3827 if (!HandleLValueToRValueConversion(Info, E->getInit(0),
Richard Smith83587db2012-02-15 02:18:13 +00003828 CAT->getElementType(), LV, Char))
3829 return false;
3830 Result.getArrayInitializedElt(I) = Char.toAPValue();
3831 if (!HandleLValueArrayAdjustment(Info, E->getInit(0), LV,
Richard Smithb4e85ed2012-01-06 16:39:00 +00003832 CAT->getElementType(), 1))
Richard Smith974c5f92011-12-22 01:07:19 +00003833 return false;
3834 }
3835 return true;
3836 }
3837
Richard Smith745f5142012-01-27 01:14:48 +00003838 bool Success = true;
3839
Richard Smithcc5d4f62011-11-07 09:22:26 +00003840 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3841 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003842 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003843 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003844 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003845 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003846 I != End; ++I, ++Index) {
Richard Smith83587db2012-02-15 02:18:13 +00003847 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3848 Info, Subobject, cast<Expr>(*I)) ||
Richard Smith745f5142012-01-27 01:14:48 +00003849 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3850 CAT->getElementType(), 1)) {
3851 if (!Info.keepEvaluatingAfterFailure())
3852 return false;
3853 Success = false;
3854 }
Richard Smith180f4792011-11-10 06:34:14 +00003855 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003856
Richard Smith745f5142012-01-27 01:14:48 +00003857 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003858 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003859 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3860 // but sometimes does:
3861 // struct S { constexpr S() : p(&p) {} void *p; };
3862 // S s[10] = {};
Richard Smith83587db2012-02-15 02:18:13 +00003863 return EvaluateInPlace(Result.getArrayFiller(), Info,
3864 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003865}
3866
Richard Smithe24f5fc2011-11-17 22:56:20 +00003867bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3868 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3869 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003870 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003871
Richard Smithec789162012-01-12 18:54:33 +00003872 bool HadZeroInit = !Result.isUninit();
3873 if (!HadZeroInit)
3874 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003875 if (!Result.hasArrayFiller())
3876 return true;
3877
3878 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003879
Richard Smith51201882011-12-30 21:15:51 +00003880 bool ZeroInit = E->requiresZeroInitialization();
3881 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003882 if (HadZeroInit)
3883 return true;
3884
Richard Smith51201882011-12-30 21:15:51 +00003885 if (ZeroInit) {
3886 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003887 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003888 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003889 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003890 }
3891
Richard Smith61802452011-12-22 02:22:31 +00003892 const CXXRecordDecl *RD = FD->getParent();
3893 if (RD->isUnion())
3894 Result.getArrayFiller() = APValue((FieldDecl*)0);
3895 else
3896 Result.getArrayFiller() =
3897 APValue(APValue::UninitStruct(), RD->getNumBases(),
3898 std::distance(RD->field_begin(), RD->field_end()));
3899 return true;
3900 }
3901
Richard Smithe24f5fc2011-11-17 22:56:20 +00003902 const FunctionDecl *Definition = 0;
3903 FD->getBody(Definition);
3904
Richard Smithc1c5f272011-12-13 06:39:58 +00003905 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3906 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003907
3908 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3909 // but sometimes does:
3910 // struct S { constexpr S() : p(&p) {} void *p; };
3911 // S s[10];
3912 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003913 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003914
Richard Smithec789162012-01-12 18:54:33 +00003915 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003916 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003917 if (!EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003918 return false;
3919 }
3920
Richard Smithe24f5fc2011-11-17 22:56:20 +00003921 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003922 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003923 cast<CXXConstructorDecl>(Definition),
3924 Info, Result.getArrayFiller());
3925}
3926
Richard Smithcc5d4f62011-11-07 09:22:26 +00003927//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003928// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003929//
3930// As a GNU extension, we support casting pointers to sufficiently-wide integer
3931// types and back in constant folding. Integer values are thus represented
3932// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003933//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003934
3935namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003936class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003937 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00003938 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003939public:
Richard Smith47a1eed2011-10-29 20:57:55 +00003940 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003941 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003942
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003943 bool Success(const llvm::APSInt &SI, const Expr *E) {
3944 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003945 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003946 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003947 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003948 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003949 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003950 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003951 return true;
3952 }
3953
Daniel Dunbar131eb432009-02-19 09:06:44 +00003954 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003955 assert(E->getType()->isIntegralOrEnumerationType() &&
3956 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003957 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003958 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003959 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003960 Result.getInt().setIsUnsigned(
3961 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003962 return true;
3963 }
3964
3965 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003966 assert(E->getType()->isIntegralOrEnumerationType() &&
3967 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003968 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003969 return true;
3970 }
3971
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003972 bool Success(CharUnits Size, const Expr *E) {
3973 return Success(Size.getQuantity(), E);
3974 }
3975
Richard Smith47a1eed2011-10-29 20:57:55 +00003976 bool Success(const CCValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00003977 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00003978 Result = V;
3979 return true;
3980 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003981 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003982 }
Mike Stump1eb44332009-09-09 15:08:12 +00003983
Richard Smith51201882011-12-30 21:15:51 +00003984 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00003985
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003986 //===--------------------------------------------------------------------===//
3987 // Visitor Methods
3988 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003989
Chris Lattner4c4867e2008-07-12 00:38:25 +00003990 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003991 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003992 }
3993 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003994 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003995 }
Eli Friedman04309752009-11-24 05:28:59 +00003996
3997 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3998 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003999 if (CheckReferencedDecl(E, E->getDecl()))
4000 return true;
4001
4002 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004003 }
4004 bool VisitMemberExpr(const MemberExpr *E) {
4005 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00004006 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00004007 return true;
4008 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004009
4010 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004011 }
4012
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004013 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004014 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004015 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004016 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00004017
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004018 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004019 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00004020
Anders Carlsson3068d112008-11-16 19:01:22 +00004021 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004022 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00004023 }
Mike Stump1eb44332009-09-09 15:08:12 +00004024
Richard Smithf10d9172011-10-11 21:43:33 +00004025 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00004026 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00004027 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00004028 }
4029
Sebastian Redl64b45f72009-01-05 20:52:13 +00004030 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00004031 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00004032 }
4033
Francois Pichet6ad6f282010-12-07 00:08:36 +00004034 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4035 return Success(E->getValue(), E);
4036 }
4037
John Wiegley21ff2e52011-04-28 00:16:57 +00004038 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4039 return Success(E->getValue(), E);
4040 }
4041
John Wiegley55262202011-04-25 06:54:41 +00004042 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4043 return Success(E->getValue(), E);
4044 }
4045
Eli Friedman722c7172009-02-28 03:59:05 +00004046 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004047 bool VisitUnaryImag(const UnaryOperator *E);
4048
Sebastian Redl295995c2010-09-10 20:55:47 +00004049 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00004050 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004051
Chris Lattnerfcee0012008-07-11 21:24:13 +00004052private:
Ken Dyck8b752f12010-01-27 17:10:57 +00004053 CharUnits GetAlignOfExpr(const Expr *E);
4054 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004055 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004056 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004057 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004058};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004059} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00004060
Richard Smithc49bd112011-10-28 17:51:58 +00004061/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4062/// produce either the integer value or a pointer.
4063///
4064/// GCC has a heinous extension which folds casts between pointer types and
4065/// pointer-sized integral types. We support this by allowing the evaluation of
4066/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4067/// Some simple arithmetic on such values is supported (they are treated much
4068/// like char*).
Richard Smithf48fdb02011-12-09 22:58:01 +00004069static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00004070 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004071 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004072 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004073}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004074
Richard Smithf48fdb02011-12-09 22:58:01 +00004075static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004076 CCValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00004077 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004078 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004079 if (!Val.isInt()) {
4080 // FIXME: It would be better to produce the diagnostic for casting
4081 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00004082 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00004083 return false;
4084 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004085 Result = Val.getInt();
4086 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00004087}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004088
Richard Smithf48fdb02011-12-09 22:58:01 +00004089/// Check whether the given declaration can be directly converted to an integral
4090/// rvalue. If not, no diagnostic is produced; there are other things we can
4091/// try.
Eli Friedman04309752009-11-24 05:28:59 +00004092bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00004093 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004094 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004095 // Check for signedness/width mismatches between E type and ECD value.
4096 bool SameSign = (ECD->getInitVal().isSigned()
4097 == E->getType()->isSignedIntegerOrEnumerationType());
4098 bool SameWidth = (ECD->getInitVal().getBitWidth()
4099 == Info.Ctx.getIntWidth(E->getType()));
4100 if (SameSign && SameWidth)
4101 return Success(ECD->getInitVal(), E);
4102 else {
4103 // Get rid of mismatch (otherwise Success assertions will fail)
4104 // by computing a new value matching the type of E.
4105 llvm::APSInt Val = ECD->getInitVal();
4106 if (!SameSign)
4107 Val.setIsSigned(!ECD->getInitVal().isSigned());
4108 if (!SameWidth)
4109 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4110 return Success(Val, E);
4111 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004112 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004113 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00004114}
4115
Chris Lattnera4d55d82008-10-06 06:40:35 +00004116/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4117/// as GCC.
4118static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4119 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004120 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00004121 enum gcc_type_class {
4122 no_type_class = -1,
4123 void_type_class, integer_type_class, char_type_class,
4124 enumeral_type_class, boolean_type_class,
4125 pointer_type_class, reference_type_class, offset_type_class,
4126 real_type_class, complex_type_class,
4127 function_type_class, method_type_class,
4128 record_type_class, union_type_class,
4129 array_type_class, string_type_class,
4130 lang_type_class
4131 };
Mike Stump1eb44332009-09-09 15:08:12 +00004132
4133 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00004134 // ideal, however it is what gcc does.
4135 if (E->getNumArgs() == 0)
4136 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00004137
Chris Lattnera4d55d82008-10-06 06:40:35 +00004138 QualType ArgTy = E->getArg(0)->getType();
4139 if (ArgTy->isVoidType())
4140 return void_type_class;
4141 else if (ArgTy->isEnumeralType())
4142 return enumeral_type_class;
4143 else if (ArgTy->isBooleanType())
4144 return boolean_type_class;
4145 else if (ArgTy->isCharType())
4146 return string_type_class; // gcc doesn't appear to use char_type_class
4147 else if (ArgTy->isIntegerType())
4148 return integer_type_class;
4149 else if (ArgTy->isPointerType())
4150 return pointer_type_class;
4151 else if (ArgTy->isReferenceType())
4152 return reference_type_class;
4153 else if (ArgTy->isRealType())
4154 return real_type_class;
4155 else if (ArgTy->isComplexType())
4156 return complex_type_class;
4157 else if (ArgTy->isFunctionType())
4158 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004159 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004160 return record_type_class;
4161 else if (ArgTy->isUnionType())
4162 return union_type_class;
4163 else if (ArgTy->isArrayType())
4164 return array_type_class;
4165 else if (ArgTy->isUnionType())
4166 return union_type_class;
4167 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004168 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004169}
4170
Richard Smith80d4b552011-12-28 19:48:30 +00004171/// EvaluateBuiltinConstantPForLValue - Determine the result of
4172/// __builtin_constant_p when applied to the given lvalue.
4173///
4174/// An lvalue is only "constant" if it is a pointer or reference to the first
4175/// character of a string literal.
4176template<typename LValue>
4177static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
4178 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
4179 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4180}
4181
4182/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4183/// GCC as we can manage.
4184static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4185 QualType ArgType = Arg->getType();
4186
4187 // __builtin_constant_p always has one operand. The rules which gcc follows
4188 // are not precisely documented, but are as follows:
4189 //
4190 // - If the operand is of integral, floating, complex or enumeration type,
4191 // and can be folded to a known value of that type, it returns 1.
4192 // - If the operand and can be folded to a pointer to the first character
4193 // of a string literal (or such a pointer cast to an integral type), it
4194 // returns 1.
4195 //
4196 // Otherwise, it returns 0.
4197 //
4198 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4199 // its support for this does not currently work.
4200 if (ArgType->isIntegralOrEnumerationType()) {
4201 Expr::EvalResult Result;
4202 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4203 return false;
4204
4205 APValue &V = Result.Val;
4206 if (V.getKind() == APValue::Int)
4207 return true;
4208
4209 return EvaluateBuiltinConstantPForLValue(V);
4210 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4211 return Arg->isEvaluatable(Ctx);
4212 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4213 LValue LV;
4214 Expr::EvalStatus Status;
4215 EvalInfo Info(Ctx, Status);
4216 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4217 : EvaluatePointer(Arg, LV, Info)) &&
4218 !Status.HasSideEffects)
4219 return EvaluateBuiltinConstantPForLValue(LV);
4220 }
4221
4222 // Anything else isn't considered to be sufficiently constant.
4223 return false;
4224}
4225
John McCall42c8f872010-05-10 23:27:23 +00004226/// Retrieves the "underlying object type" of the given expression,
4227/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004228QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4229 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4230 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004231 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004232 } else if (const Expr *E = B.get<const Expr*>()) {
4233 if (isa<CompoundLiteralExpr>(E))
4234 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004235 }
4236
4237 return QualType();
4238}
4239
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004240bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004241 // TODO: Perhaps we should let LLVM lower this?
4242 LValue Base;
4243 if (!EvaluatePointer(E->getArg(0), Base, Info))
4244 return false;
4245
4246 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004247 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004248
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004249 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004250 if (T.isNull() ||
4251 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004252 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004253 T->isVariablyModifiedType() ||
4254 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004255 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004256
4257 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4258 CharUnits Offset = Base.getLValueOffset();
4259
4260 if (!Offset.isNegative() && Offset <= Size)
4261 Size -= Offset;
4262 else
4263 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004264 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004265}
4266
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004267bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004268 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004269 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004270 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004271
4272 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004273 if (TryEvaluateBuiltinObjectSize(E))
4274 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004275
Eric Christopherb2aaf512010-01-19 22:58:35 +00004276 // If evaluating the argument has side-effects we can't determine
4277 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004278 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004279 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004280 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004281 return Success(0, E);
4282 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004283
Richard Smithf48fdb02011-12-09 22:58:01 +00004284 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004285 }
4286
Chris Lattner019f4e82008-10-06 05:28:25 +00004287 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004288 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004289
Richard Smith80d4b552011-12-28 19:48:30 +00004290 case Builtin::BI__builtin_constant_p:
4291 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004292
Chris Lattner21fb98e2009-09-23 06:06:36 +00004293 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004294 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004295 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004296 return Success(Operand, E);
4297 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004298
4299 case Builtin::BI__builtin_expect:
4300 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004301
Douglas Gregor5726d402010-09-10 06:27:15 +00004302 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004303 // A call to strlen is not a constant expression.
4304 if (Info.getLangOpts().CPlusPlus0x)
4305 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_function)
4306 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4307 else
4308 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
4309 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004310 case Builtin::BI__builtin_strlen:
4311 // As an extension, we support strlen() and __builtin_strlen() as constant
4312 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004313 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004314 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4315 // The string literal may have embedded null characters. Find the first
4316 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004317 StringRef Str = S->getString();
4318 StringRef::size_type Pos = Str.find(0);
4319 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004320 Str = Str.substr(0, Pos);
4321
4322 return Success(Str.size(), E);
4323 }
4324
Richard Smithf48fdb02011-12-09 22:58:01 +00004325 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004326
4327 case Builtin::BI__atomic_is_lock_free: {
4328 APSInt SizeVal;
4329 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4330 return false;
4331
4332 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4333 // of two less than the maximum inline atomic width, we know it is
4334 // lock-free. If the size isn't a power of two, or greater than the
4335 // maximum alignment where we promote atomics, we know it is not lock-free
4336 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4337 // the answer can only be determined at runtime; for example, 16-byte
4338 // atomics have lock-free implementations on some, but not all,
4339 // x86-64 processors.
4340
4341 // Check power-of-two.
4342 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4343 if (!Size.isPowerOfTwo())
4344#if 0
4345 // FIXME: Suppress this folding until the ABI for the promotion width
4346 // settles.
4347 return Success(0, E);
4348#else
Richard Smithf48fdb02011-12-09 22:58:01 +00004349 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004350#endif
4351
4352#if 0
4353 // Check against promotion width.
4354 // FIXME: Suppress this folding until the ABI for the promotion width
4355 // settles.
4356 unsigned PromoteWidthBits =
4357 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
4358 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
4359 return Success(0, E);
4360#endif
4361
4362 // Check against inlining width.
4363 unsigned InlineWidthBits =
4364 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4365 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
4366 return Success(1, E);
4367
Richard Smithf48fdb02011-12-09 22:58:01 +00004368 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004369 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004370 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004371}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004372
Richard Smith625b8072011-10-31 01:37:14 +00004373static bool HasSameBase(const LValue &A, const LValue &B) {
4374 if (!A.getLValueBase())
4375 return !B.getLValueBase();
4376 if (!B.getLValueBase())
4377 return false;
4378
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004379 if (A.getLValueBase().getOpaqueValue() !=
4380 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004381 const Decl *ADecl = GetLValueBaseDecl(A);
4382 if (!ADecl)
4383 return false;
4384 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004385 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004386 return false;
4387 }
4388
4389 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith83587db2012-02-15 02:18:13 +00004390 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith625b8072011-10-31 01:37:14 +00004391}
4392
Richard Smith7b48a292012-02-01 05:53:12 +00004393/// Perform the given integer operation, which is known to need at most BitWidth
4394/// bits, and check for overflow in the original type (if that type was not an
4395/// unsigned type).
4396template<typename Operation>
4397static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4398 const APSInt &LHS, const APSInt &RHS,
4399 unsigned BitWidth, Operation Op) {
4400 if (LHS.isUnsigned())
4401 return Op(LHS, RHS);
4402
4403 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4404 APSInt Result = Value.trunc(LHS.getBitWidth());
4405 if (Result.extend(BitWidth) != Value)
4406 HandleOverflow(Info, E, Value, E->getType());
4407 return Result;
4408}
4409
Chris Lattnerb542afe2008-07-11 19:10:17 +00004410bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004411 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004412 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004413
John McCall2de56d12010-08-25 11:45:40 +00004414 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00004415 VisitIgnoredValue(E->getLHS());
4416 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00004417 }
4418
4419 if (E->isLogicalOp()) {
4420 // These need to be handled specially because the operands aren't
Richard Smith74e1ad92012-02-16 02:46:34 +00004421 // necessarily integral nor evaluated.
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004422 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00004423
Richard Smithc49bd112011-10-28 17:51:58 +00004424 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00004425 // We were able to evaluate the LHS, see if we can get away with not
4426 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00004427 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004428 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004429
Richard Smithc49bd112011-10-28 17:51:58 +00004430 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00004431 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004432 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004433 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00004434 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004435 }
4436 } else {
Richard Smith74e1ad92012-02-16 02:46:34 +00004437 // Since we weren't able to evaluate the left hand side, it
4438 // must have had side effects.
4439 Info.EvalStatus.HasSideEffects = true;
4440
4441 // Suppress diagnostics from this arm.
4442 SpeculativeEvaluationRAII Speculative(Info);
Richard Smithc49bd112011-10-28 17:51:58 +00004443 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004444 // We can't evaluate the LHS; however, sometimes the result
4445 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smith74e1ad92012-02-16 02:46:34 +00004446 if (rhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar131eb432009-02-19 09:06:44 +00004447 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004448 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00004449 }
Eli Friedmana6afa762008-11-13 06:09:17 +00004450
Eli Friedmana6afa762008-11-13 06:09:17 +00004451 return false;
4452 }
4453
Anders Carlsson286f85e2008-11-16 07:17:21 +00004454 QualType LHSTy = E->getLHS()->getType();
4455 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004456
4457 if (LHSTy->isAnyComplexType()) {
4458 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004459 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004460
Richard Smith745f5142012-01-27 01:14:48 +00004461 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4462 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004463 return false;
4464
Richard Smith745f5142012-01-27 01:14:48 +00004465 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004466 return false;
4467
4468 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004469 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004470 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004471 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004472 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4473
John McCall2de56d12010-08-25 11:45:40 +00004474 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004475 return Success((CR_r == APFloat::cmpEqual &&
4476 CR_i == APFloat::cmpEqual), E);
4477 else {
John McCall2de56d12010-08-25 11:45:40 +00004478 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004479 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004480 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004481 CR_r == APFloat::cmpLessThan ||
4482 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004483 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004484 CR_i == APFloat::cmpLessThan ||
4485 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004486 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004487 } else {
John McCall2de56d12010-08-25 11:45:40 +00004488 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004489 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4490 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4491 else {
John McCall2de56d12010-08-25 11:45:40 +00004492 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004493 "Invalid compex comparison.");
4494 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4495 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4496 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004497 }
4498 }
Mike Stump1eb44332009-09-09 15:08:12 +00004499
Anders Carlsson286f85e2008-11-16 07:17:21 +00004500 if (LHSTy->isRealFloatingType() &&
4501 RHSTy->isRealFloatingType()) {
4502 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004503
Richard Smith745f5142012-01-27 01:14:48 +00004504 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4505 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004506 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004507
Richard Smith745f5142012-01-27 01:14:48 +00004508 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004509 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004510
Anders Carlsson286f85e2008-11-16 07:17:21 +00004511 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004512
Anders Carlsson286f85e2008-11-16 07:17:21 +00004513 switch (E->getOpcode()) {
4514 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004515 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004516 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004517 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004518 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004519 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004520 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004521 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004522 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004523 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004524 E);
John McCall2de56d12010-08-25 11:45:40 +00004525 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004526 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004527 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004528 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004529 || CR == APFloat::cmpLessThan
4530 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004531 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004532 }
Mike Stump1eb44332009-09-09 15:08:12 +00004533
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004534 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004535 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004536 LValue LHSValue, RHSValue;
4537
4538 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4539 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004540 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004541
Richard Smith745f5142012-01-27 01:14:48 +00004542 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004543 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004544
Richard Smith625b8072011-10-31 01:37:14 +00004545 // Reject differing bases from the normal codepath; we special-case
4546 // comparisons to null.
4547 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004548 if (E->getOpcode() == BO_Sub) {
4549 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004550 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4551 return false;
4552 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4553 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4554 if (!LHSExpr || !RHSExpr)
4555 return false;
4556 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4557 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4558 if (!LHSAddrExpr || !RHSAddrExpr)
4559 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004560 // Make sure both labels come from the same function.
4561 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4562 RHSAddrExpr->getLabel()->getDeclContext())
4563 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004564 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4565 return true;
4566 }
Richard Smith9e36b532011-10-31 05:11:32 +00004567 // Inequalities and subtractions between unrelated pointers have
4568 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004569 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004570 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004571 // A constant address may compare equal to the address of a symbol.
4572 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004573 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004574 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4575 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004576 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004577 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004578 // distinct addresses. In clang, the result of such a comparison is
4579 // unspecified, so it is not a constant expression. However, we do know
4580 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004581 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4582 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004583 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004584 // We can't tell whether weak symbols will end up pointing to the same
4585 // object.
4586 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004587 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004588 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004589 // (Note that clang defaults to -fmerge-all-constants, which can
4590 // lead to inconsistent results for comparisons involving the address
4591 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004592 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004593 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004594
Richard Smith15efc4d2012-02-01 08:10:20 +00004595 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4596 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4597
Richard Smithf15fda02012-02-02 01:16:57 +00004598 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4599 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4600
John McCall2de56d12010-08-25 11:45:40 +00004601 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00004602 // C++11 [expr.add]p6:
4603 // Unless both pointers point to elements of the same array object, or
4604 // one past the last element of the array object, the behavior is
4605 // undefined.
4606 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4607 !AreElementsOfSameArray(getType(LHSValue.Base),
4608 LHSDesignator, RHSDesignator))
4609 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4610
Chris Lattner4992bdd2010-04-20 17:13:14 +00004611 QualType Type = E->getLHS()->getType();
4612 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004613
Richard Smith180f4792011-11-10 06:34:14 +00004614 CharUnits ElementSize;
Richard Smith74e1ad92012-02-16 02:46:34 +00004615 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smith180f4792011-11-10 06:34:14 +00004616 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004617
Richard Smith15efc4d2012-02-01 08:10:20 +00004618 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
4619 // and produce incorrect results when it overflows. Such behavior
4620 // appears to be non-conforming, but is common, so perhaps we should
4621 // assume the standard intended for such cases to be undefined behavior
4622 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00004623
Richard Smith15efc4d2012-02-01 08:10:20 +00004624 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
4625 // overflow in the final conversion to ptrdiff_t.
4626 APSInt LHS(
4627 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
4628 APSInt RHS(
4629 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
4630 APSInt ElemSize(
4631 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
4632 APSInt TrueResult = (LHS - RHS) / ElemSize;
4633 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
4634
4635 if (Result.extend(65) != TrueResult)
4636 HandleOverflow(Info, E, TrueResult, E->getType());
4637 return Success(Result, E);
4638 }
Richard Smith82f28582012-01-31 06:41:30 +00004639
4640 // C++11 [expr.rel]p3:
4641 // Pointers to void (after pointer conversions) can be compared, with a
4642 // result defined as follows: If both pointers represent the same
4643 // address or are both the null pointer value, the result is true if the
4644 // operator is <= or >= and false otherwise; otherwise the result is
4645 // unspecified.
4646 // We interpret this as applying to pointers to *cv* void.
4647 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00004648 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00004649 CCEDiag(E, diag::note_constexpr_void_comparison);
4650
Richard Smithf15fda02012-02-02 01:16:57 +00004651 // C++11 [expr.rel]p2:
4652 // - If two pointers point to non-static data members of the same object,
4653 // or to subobjects or array elements fo such members, recursively, the
4654 // pointer to the later declared member compares greater provided the
4655 // two members have the same access control and provided their class is
4656 // not a union.
4657 // [...]
4658 // - Otherwise pointer comparisons are unspecified.
4659 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4660 E->isRelationalOp()) {
4661 bool WasArrayIndex;
4662 unsigned Mismatch =
4663 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
4664 RHSDesignator, WasArrayIndex);
4665 // At the point where the designators diverge, the comparison has a
4666 // specified value if:
4667 // - we are comparing array indices
4668 // - we are comparing fields of a union, or fields with the same access
4669 // Otherwise, the result is unspecified and thus the comparison is not a
4670 // constant expression.
4671 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
4672 Mismatch < RHSDesignator.Entries.size()) {
4673 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
4674 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
4675 if (!LF && !RF)
4676 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
4677 else if (!LF)
4678 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4679 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
4680 << RF->getParent() << RF;
4681 else if (!RF)
4682 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4683 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
4684 << LF->getParent() << LF;
4685 else if (!LF->getParent()->isUnion() &&
4686 LF->getAccess() != RF->getAccess())
4687 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
4688 << LF << LF->getAccess() << RF << RF->getAccess()
4689 << LF->getParent();
4690 }
4691 }
4692
Richard Smith625b8072011-10-31 01:37:14 +00004693 switch (E->getOpcode()) {
4694 default: llvm_unreachable("missing comparison operator");
4695 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4696 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4697 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4698 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4699 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4700 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004701 }
Anders Carlsson3068d112008-11-16 19:01:22 +00004702 }
4703 }
Richard Smithb02e4622012-02-01 01:42:44 +00004704
4705 if (LHSTy->isMemberPointerType()) {
4706 assert(E->isEqualityOp() && "unexpected member pointer operation");
4707 assert(RHSTy->isMemberPointerType() && "invalid comparison");
4708
4709 MemberPtr LHSValue, RHSValue;
4710
4711 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
4712 if (!LHSOK && Info.keepEvaluatingAfterFailure())
4713 return false;
4714
4715 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
4716 return false;
4717
4718 // C++11 [expr.eq]p2:
4719 // If both operands are null, they compare equal. Otherwise if only one is
4720 // null, they compare unequal.
4721 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
4722 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
4723 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4724 }
4725
4726 // Otherwise if either is a pointer to a virtual member function, the
4727 // result is unspecified.
4728 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
4729 if (MD->isVirtual())
4730 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4731 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
4732 if (MD->isVirtual())
4733 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4734
4735 // Otherwise they compare equal if and only if they would refer to the
4736 // same member of the same most derived object or the same subobject if
4737 // they were dereferenced with a hypothetical object of the associated
4738 // class type.
4739 bool Equal = LHSValue == RHSValue;
4740 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4741 }
4742
Richard Smith26f2cac2012-02-14 22:35:28 +00004743 if (LHSTy->isNullPtrType()) {
4744 assert(E->isComparisonOp() && "unexpected nullptr operation");
4745 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
4746 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
4747 // are compared, the result is true of the operator is <=, >= or ==, and
4748 // false otherwise.
4749 BinaryOperator::Opcode Opcode = E->getOpcode();
4750 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
4751 }
4752
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004753 if (!LHSTy->isIntegralOrEnumerationType() ||
4754 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004755 // We can't continue from here for non-integral types.
4756 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004757 }
4758
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004759 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00004760 CCValue LHSVal;
Richard Smith745f5142012-01-27 01:14:48 +00004761
4762 bool LHSOK = EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info);
4763 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Richard Smithf48fdb02011-12-09 22:58:01 +00004764 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00004765
Richard Smith745f5142012-01-27 01:14:48 +00004766 if (!Visit(E->getRHS()) || !LHSOK)
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004767 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004768
Richard Smith47a1eed2011-10-29 20:57:55 +00004769 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004770
4771 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00004772 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00004773 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4774 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00004775 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00004776 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004777 else
Richard Smith47a1eed2011-10-29 20:57:55 +00004778 LHSVal.getLValueOffset() -= AdditionalOffset;
4779 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004780 return true;
4781 }
4782
4783 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00004784 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00004785 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004786 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4787 LHSVal.getInt().getZExtValue());
4788 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00004789 return true;
4790 }
4791
Eli Friedman65639282012-01-04 23:13:47 +00004792 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4793 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedman65639282012-01-04 23:13:47 +00004794 if (!LHSVal.getLValueOffset().isZero() ||
4795 !RHSVal.getLValueOffset().isZero())
4796 return false;
4797 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4798 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4799 if (!LHSExpr || !RHSExpr)
4800 return false;
4801 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4802 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4803 if (!LHSAddrExpr || !RHSAddrExpr)
4804 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004805 // Make sure both labels come from the same function.
4806 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4807 RHSAddrExpr->getLabel()->getDeclContext())
4808 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004809 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4810 return true;
4811 }
4812
Eli Friedman42edd0d2009-03-24 01:14:50 +00004813 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00004814 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00004815 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004816
Richard Smithc49bd112011-10-28 17:51:58 +00004817 APSInt &LHS = LHSVal.getInt();
4818 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00004819
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004820 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00004821 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004822 return Error(E);
Richard Smith7b48a292012-02-01 05:53:12 +00004823 case BO_Mul:
4824 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4825 LHS.getBitWidth() * 2,
4826 std::multiplies<APSInt>()), E);
4827 case BO_Add:
4828 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4829 LHS.getBitWidth() + 1,
4830 std::plus<APSInt>()), E);
4831 case BO_Sub:
4832 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4833 LHS.getBitWidth() + 1,
4834 std::minus<APSInt>()), E);
Richard Smithc49bd112011-10-28 17:51:58 +00004835 case BO_And: return Success(LHS & RHS, E);
4836 case BO_Xor: return Success(LHS ^ RHS, E);
4837 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004838 case BO_Div:
John McCall2de56d12010-08-25 11:45:40 +00004839 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00004840 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004841 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith3df61302012-01-31 23:24:19 +00004842 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is not
4843 // actually undefined behavior in C++11 due to a language defect.
4844 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4845 LHS.isSigned() && LHS.isMinSignedValue())
4846 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4847 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004848 case BO_Shl: {
Richard Smith789f9b62012-01-31 04:08:20 +00004849 // During constant-folding, a negative shift is an opposite shift. Such a
4850 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004851 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004852 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004853 RHS = -RHS;
4854 goto shift_right;
4855 }
4856
4857 shift_left:
Richard Smith789f9b62012-01-31 04:08:20 +00004858 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4859 // shifted type.
4860 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4861 if (SA != RHS) {
4862 CCEDiag(E, diag::note_constexpr_large_shift)
4863 << RHS << E->getType() << LHS.getBitWidth();
4864 } else if (LHS.isSigned()) {
4865 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
Richard Smith925d8e72012-02-08 06:14:53 +00004866 // operand, and must not overflow the corresponding unsigned type.
Richard Smith789f9b62012-01-31 04:08:20 +00004867 if (LHS.isNegative())
4868 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
Richard Smith925d8e72012-02-08 06:14:53 +00004869 else if (LHS.countLeadingZeros() < SA)
4870 CCEDiag(E, diag::note_constexpr_lshift_discards);
Richard Smith789f9b62012-01-31 04:08:20 +00004871 }
4872
Richard Smithc49bd112011-10-28 17:51:58 +00004873 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004874 }
John McCall2de56d12010-08-25 11:45:40 +00004875 case BO_Shr: {
Richard Smith789f9b62012-01-31 04:08:20 +00004876 // During constant-folding, a negative shift is an opposite shift. Such a
4877 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004878 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004879 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004880 RHS = -RHS;
4881 goto shift_left;
4882 }
4883
4884 shift_right:
Richard Smith789f9b62012-01-31 04:08:20 +00004885 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4886 // shifted type.
4887 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4888 if (SA != RHS)
4889 CCEDiag(E, diag::note_constexpr_large_shift)
4890 << RHS << E->getType() << LHS.getBitWidth();
4891
Richard Smithc49bd112011-10-28 17:51:58 +00004892 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004893 }
Mike Stump1eb44332009-09-09 15:08:12 +00004894
Richard Smithc49bd112011-10-28 17:51:58 +00004895 case BO_LT: return Success(LHS < RHS, E);
4896 case BO_GT: return Success(LHS > RHS, E);
4897 case BO_LE: return Success(LHS <= RHS, E);
4898 case BO_GE: return Success(LHS >= RHS, E);
4899 case BO_EQ: return Success(LHS == RHS, E);
4900 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00004901 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004902}
4903
Ken Dyck8b752f12010-01-27 17:10:57 +00004904CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00004905 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4906 // result shall be the alignment of the referenced type."
4907 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4908 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00004909
4910 // __alignof is defined to return the preferred alignment.
4911 return Info.Ctx.toCharUnitsFromBits(
4912 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00004913}
4914
Ken Dyck8b752f12010-01-27 17:10:57 +00004915CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00004916 E = E->IgnoreParens();
4917
4918 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00004919 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00004920 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004921 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4922 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00004923
Chris Lattneraf707ab2009-01-24 21:53:27 +00004924 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004925 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4926 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00004927
Chris Lattnere9feb472009-01-24 21:09:06 +00004928 return GetAlignOfType(E->getType());
4929}
4930
4931
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004932/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4933/// a result as the expression's type.
4934bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4935 const UnaryExprOrTypeTraitExpr *E) {
4936 switch(E->getKind()) {
4937 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00004938 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004939 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004940 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004941 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004942 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004943
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004944 case UETT_VecStep: {
4945 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00004946
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004947 if (Ty->isVectorType()) {
4948 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00004949
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004950 // The vec_step built-in functions that take a 3-component
4951 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4952 if (n == 3)
4953 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00004954
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004955 return Success(n, E);
4956 } else
4957 return Success(1, E);
4958 }
4959
4960 case UETT_SizeOf: {
4961 QualType SrcTy = E->getTypeOfArgument();
4962 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4963 // the result is the size of the referenced type."
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004964 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4965 SrcTy = Ref->getPointeeType();
4966
Richard Smith180f4792011-11-10 06:34:14 +00004967 CharUnits Sizeof;
Richard Smith74e1ad92012-02-16 02:46:34 +00004968 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004969 return false;
Richard Smith180f4792011-11-10 06:34:14 +00004970 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004971 }
4972 }
4973
4974 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00004975}
4976
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004977bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004978 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004979 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004980 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004981 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004982 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004983 for (unsigned i = 0; i != n; ++i) {
4984 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4985 switch (ON.getKind()) {
4986 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004987 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004988 APSInt IdxResult;
4989 if (!EvaluateInteger(Idx, IdxResult, Info))
4990 return false;
4991 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4992 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004993 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004994 CurrentType = AT->getElementType();
4995 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4996 Result += IdxResult.getSExtValue() * ElementSize;
4997 break;
4998 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004999
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005000 case OffsetOfExpr::OffsetOfNode::Field: {
5001 FieldDecl *MemberDecl = ON.getField();
5002 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005003 if (!RT)
5004 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005005 RecordDecl *RD = RT->getDecl();
5006 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00005007 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005008 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00005009 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005010 CurrentType = MemberDecl->getType().getNonReferenceType();
5011 break;
5012 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005013
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005014 case OffsetOfExpr::OffsetOfNode::Identifier:
5015 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00005016
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005017 case OffsetOfExpr::OffsetOfNode::Base: {
5018 CXXBaseSpecifier *BaseSpec = ON.getBase();
5019 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00005020 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005021
5022 // Find the layout of the class whose base we are looking into.
5023 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005024 if (!RT)
5025 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005026 RecordDecl *RD = RT->getDecl();
5027 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5028
5029 // Find the base class itself.
5030 CurrentType = BaseSpec->getType();
5031 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5032 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005033 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005034
5035 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00005036 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005037 break;
5038 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005039 }
5040 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005041 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005042}
5043
Chris Lattnerb542afe2008-07-11 19:10:17 +00005044bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005045 switch (E->getOpcode()) {
5046 default:
5047 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5048 // See C99 6.6p3.
5049 return Error(E);
5050 case UO_Extension:
5051 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5052 // If so, we could clear the diagnostic ID.
5053 return Visit(E->getSubExpr());
5054 case UO_Plus:
5055 // The result is just the value.
5056 return Visit(E->getSubExpr());
5057 case UO_Minus: {
5058 if (!Visit(E->getSubExpr()))
5059 return false;
5060 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00005061 const APSInt &Value = Result.getInt();
5062 if (Value.isSigned() && Value.isMinSignedValue())
5063 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5064 E->getType());
5065 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00005066 }
5067 case UO_Not: {
5068 if (!Visit(E->getSubExpr()))
5069 return false;
5070 if (!Result.isInt()) return Error(E);
5071 return Success(~Result.getInt(), E);
5072 }
5073 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00005074 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00005075 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00005076 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005077 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00005078 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005079 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005080}
Mike Stump1eb44332009-09-09 15:08:12 +00005081
Chris Lattner732b2232008-07-12 01:15:53 +00005082/// HandleCast - This is used to evaluate implicit or explicit casts where the
5083/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005084bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5085 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00005086 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00005087 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00005088
Eli Friedman46a52322011-03-25 00:43:55 +00005089 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00005090 case CK_BaseToDerived:
5091 case CK_DerivedToBase:
5092 case CK_UncheckedDerivedToBase:
5093 case CK_Dynamic:
5094 case CK_ToUnion:
5095 case CK_ArrayToPointerDecay:
5096 case CK_FunctionToPointerDecay:
5097 case CK_NullToPointer:
5098 case CK_NullToMemberPointer:
5099 case CK_BaseToDerivedMemberPointer:
5100 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00005101 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00005102 case CK_ConstructorConversion:
5103 case CK_IntegralToPointer:
5104 case CK_ToVoid:
5105 case CK_VectorSplat:
5106 case CK_IntegralToFloating:
5107 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005108 case CK_CPointerToObjCPointerCast:
5109 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005110 case CK_AnyPointerToBlockPointerCast:
5111 case CK_ObjCObjectLValueCast:
5112 case CK_FloatingRealToComplex:
5113 case CK_FloatingComplexToReal:
5114 case CK_FloatingComplexCast:
5115 case CK_FloatingComplexToIntegralComplex:
5116 case CK_IntegralRealToComplex:
5117 case CK_IntegralComplexCast:
5118 case CK_IntegralComplexToFloatingComplex:
5119 llvm_unreachable("invalid cast kind for integral value");
5120
Eli Friedmane50c2972011-03-25 19:07:11 +00005121 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005122 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005123 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00005124 case CK_ARCProduceObject:
5125 case CK_ARCConsumeObject:
5126 case CK_ARCReclaimReturnedObject:
5127 case CK_ARCExtendBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00005128 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005129
Richard Smith7d580a42012-01-17 21:17:26 +00005130 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00005131 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005132 case CK_AtomicToNonAtomic:
5133 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00005134 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005135 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005136
5137 case CK_MemberPointerToBoolean:
5138 case CK_PointerToBoolean:
5139 case CK_IntegralToBoolean:
5140 case CK_FloatingToBoolean:
5141 case CK_FloatingComplexToBoolean:
5142 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005143 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00005144 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00005145 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005146 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005147 }
5148
Eli Friedman46a52322011-03-25 00:43:55 +00005149 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00005150 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005151 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00005152
Eli Friedmanbe265702009-02-20 01:15:07 +00005153 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00005154 // Allow casts of address-of-label differences if they are no-ops
5155 // or narrowing. (The narrowing case isn't actually guaranteed to
5156 // be constant-evaluatable except in some narrow cases which are hard
5157 // to detect here. We let it through on the assumption the user knows
5158 // what they are doing.)
5159 if (Result.isAddrLabelDiff())
5160 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005161 // Only allow casts of lvalues if they are lossless.
5162 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5163 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005164
Richard Smithf72fccf2012-01-30 22:27:01 +00005165 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5166 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005167 }
Mike Stump1eb44332009-09-09 15:08:12 +00005168
Eli Friedman46a52322011-03-25 00:43:55 +00005169 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005170 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5171
John McCallefdb83e2010-05-07 21:00:08 +00005172 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005173 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005174 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005175
Daniel Dunbardd211642009-02-19 22:24:01 +00005176 if (LV.getLValueBase()) {
5177 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005178 // FIXME: Allow a larger integer size than the pointer size, and allow
5179 // narrowing back down to pointer width in subsequent integral casts.
5180 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005181 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005182 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005183
Richard Smithb755a9d2011-11-16 07:18:12 +00005184 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005185 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005186 return true;
5187 }
5188
Ken Dycka7305832010-01-15 12:37:54 +00005189 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5190 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005191 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005192 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005193
Eli Friedman46a52322011-03-25 00:43:55 +00005194 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005195 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005196 if (!EvaluateComplex(SubExpr, C, Info))
5197 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005198 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005199 }
Eli Friedman2217c872009-02-22 11:46:18 +00005200
Eli Friedman46a52322011-03-25 00:43:55 +00005201 case CK_FloatingToIntegral: {
5202 APFloat F(0.0);
5203 if (!EvaluateFloat(SubExpr, F, Info))
5204 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005205
Richard Smithc1c5f272011-12-13 06:39:58 +00005206 APSInt Value;
5207 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5208 return false;
5209 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005210 }
5211 }
Mike Stump1eb44332009-09-09 15:08:12 +00005212
Eli Friedman46a52322011-03-25 00:43:55 +00005213 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005214}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005215
Eli Friedman722c7172009-02-28 03:59:05 +00005216bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5217 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005218 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005219 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5220 return false;
5221 if (!LV.isComplexInt())
5222 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005223 return Success(LV.getComplexIntReal(), E);
5224 }
5225
5226 return Visit(E->getSubExpr());
5227}
5228
Eli Friedman664a1042009-02-27 04:45:43 +00005229bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005230 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005231 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005232 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5233 return false;
5234 if (!LV.isComplexInt())
5235 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005236 return Success(LV.getComplexIntImag(), E);
5237 }
5238
Richard Smith8327fad2011-10-24 18:44:57 +00005239 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005240 return Success(0, E);
5241}
5242
Douglas Gregoree8aff02011-01-04 17:33:58 +00005243bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5244 return Success(E->getPackLength(), E);
5245}
5246
Sebastian Redl295995c2010-09-10 20:55:47 +00005247bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5248 return Success(E->getValue(), E);
5249}
5250
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005251//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005252// Float Evaluation
5253//===----------------------------------------------------------------------===//
5254
5255namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005256class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005257 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005258 APFloat &Result;
5259public:
5260 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005261 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005262
Richard Smith47a1eed2011-10-29 20:57:55 +00005263 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005264 Result = V.getFloat();
5265 return true;
5266 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005267
Richard Smith51201882011-12-30 21:15:51 +00005268 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005269 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5270 return true;
5271 }
5272
Chris Lattner019f4e82008-10-06 05:28:25 +00005273 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005274
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005275 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005276 bool VisitBinaryOperator(const BinaryOperator *E);
5277 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005278 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005279
John McCallabd3a852010-05-07 22:08:54 +00005280 bool VisitUnaryReal(const UnaryOperator *E);
5281 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005282
Richard Smith51201882011-12-30 21:15:51 +00005283 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005284};
5285} // end anonymous namespace
5286
5287static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005288 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005289 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005290}
5291
Jay Foad4ba2a172011-01-12 09:06:06 +00005292static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005293 QualType ResultTy,
5294 const Expr *Arg,
5295 bool SNaN,
5296 llvm::APFloat &Result) {
5297 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5298 if (!S) return false;
5299
5300 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5301
5302 llvm::APInt fill;
5303
5304 // Treat empty strings as if they were zero.
5305 if (S->getString().empty())
5306 fill = llvm::APInt(32, 0);
5307 else if (S->getString().getAsInteger(0, fill))
5308 return false;
5309
5310 if (SNaN)
5311 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5312 else
5313 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5314 return true;
5315}
5316
Chris Lattner019f4e82008-10-06 05:28:25 +00005317bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005318 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005319 default:
5320 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5321
Chris Lattner019f4e82008-10-06 05:28:25 +00005322 case Builtin::BI__builtin_huge_val:
5323 case Builtin::BI__builtin_huge_valf:
5324 case Builtin::BI__builtin_huge_vall:
5325 case Builtin::BI__builtin_inf:
5326 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005327 case Builtin::BI__builtin_infl: {
5328 const llvm::fltSemantics &Sem =
5329 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005330 Result = llvm::APFloat::getInf(Sem);
5331 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005332 }
Mike Stump1eb44332009-09-09 15:08:12 +00005333
John McCalldb7b72a2010-02-28 13:00:19 +00005334 case Builtin::BI__builtin_nans:
5335 case Builtin::BI__builtin_nansf:
5336 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005337 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5338 true, Result))
5339 return Error(E);
5340 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005341
Chris Lattner9e621712008-10-06 06:31:58 +00005342 case Builtin::BI__builtin_nan:
5343 case Builtin::BI__builtin_nanf:
5344 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005345 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005346 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005347 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5348 false, Result))
5349 return Error(E);
5350 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005351
5352 case Builtin::BI__builtin_fabs:
5353 case Builtin::BI__builtin_fabsf:
5354 case Builtin::BI__builtin_fabsl:
5355 if (!EvaluateFloat(E->getArg(0), Result, Info))
5356 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005357
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005358 if (Result.isNegative())
5359 Result.changeSign();
5360 return true;
5361
Mike Stump1eb44332009-09-09 15:08:12 +00005362 case Builtin::BI__builtin_copysign:
5363 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005364 case Builtin::BI__builtin_copysignl: {
5365 APFloat RHS(0.);
5366 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5367 !EvaluateFloat(E->getArg(1), RHS, Info))
5368 return false;
5369 Result.copySign(RHS);
5370 return true;
5371 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005372 }
5373}
5374
John McCallabd3a852010-05-07 22:08:54 +00005375bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005376 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5377 ComplexValue CV;
5378 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5379 return false;
5380 Result = CV.FloatReal;
5381 return true;
5382 }
5383
5384 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005385}
5386
5387bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005388 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5389 ComplexValue CV;
5390 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5391 return false;
5392 Result = CV.FloatImag;
5393 return true;
5394 }
5395
Richard Smith8327fad2011-10-24 18:44:57 +00005396 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005397 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5398 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005399 return true;
5400}
5401
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005402bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005403 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005404 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005405 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005406 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005407 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005408 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5409 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005410 Result.changeSign();
5411 return true;
5412 }
5413}
Chris Lattner019f4e82008-10-06 05:28:25 +00005414
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005415bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005416 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5417 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005418
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005419 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005420 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5421 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005422 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005423 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005424 return false;
5425
5426 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005427 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005428 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005429 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005430 break;
John McCall2de56d12010-08-25 11:45:40 +00005431 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005432 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005433 break;
John McCall2de56d12010-08-25 11:45:40 +00005434 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005435 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005436 break;
John McCall2de56d12010-08-25 11:45:40 +00005437 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005438 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005439 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005440 }
Richard Smith7b48a292012-02-01 05:53:12 +00005441
5442 if (Result.isInfinity() || Result.isNaN())
5443 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5444 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005445}
5446
5447bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5448 Result = E->getValue();
5449 return true;
5450}
5451
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005452bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5453 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005454
Eli Friedman2a523ee2011-03-25 00:54:52 +00005455 switch (E->getCastKind()) {
5456 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005457 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005458
5459 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005460 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005461 return EvaluateInteger(SubExpr, IntResult, Info) &&
5462 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5463 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005464 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005465
5466 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005467 if (!Visit(SubExpr))
5468 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005469 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5470 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005471 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005472
Eli Friedman2a523ee2011-03-25 00:54:52 +00005473 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005474 ComplexValue V;
5475 if (!EvaluateComplex(SubExpr, V, Info))
5476 return false;
5477 Result = V.getComplexFloatReal();
5478 return true;
5479 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005480 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005481}
5482
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005483//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005484// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005485//===----------------------------------------------------------------------===//
5486
5487namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005488class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005489 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005490 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005491
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005492public:
John McCallf4cf1a12010-05-07 17:22:02 +00005493 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005494 : ExprEvaluatorBaseTy(info), Result(Result) {}
5495
Richard Smith47a1eed2011-10-29 20:57:55 +00005496 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005497 Result.setFrom(V);
5498 return true;
5499 }
Mike Stump1eb44332009-09-09 15:08:12 +00005500
Eli Friedman7ead5c72012-01-10 04:58:17 +00005501 bool ZeroInitialization(const Expr *E);
5502
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005503 //===--------------------------------------------------------------------===//
5504 // Visitor Methods
5505 //===--------------------------------------------------------------------===//
5506
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005507 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005508 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005509 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005510 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005511 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005512};
5513} // end anonymous namespace
5514
John McCallf4cf1a12010-05-07 17:22:02 +00005515static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5516 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005517 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005518 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005519}
5520
Eli Friedman7ead5c72012-01-10 04:58:17 +00005521bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005522 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005523 if (ElemTy->isRealFloatingType()) {
5524 Result.makeComplexFloat();
5525 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5526 Result.FloatReal = Zero;
5527 Result.FloatImag = Zero;
5528 } else {
5529 Result.makeComplexInt();
5530 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5531 Result.IntReal = Zero;
5532 Result.IntImag = Zero;
5533 }
5534 return true;
5535}
5536
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005537bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5538 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005539
5540 if (SubExpr->getType()->isRealFloatingType()) {
5541 Result.makeComplexFloat();
5542 APFloat &Imag = Result.FloatImag;
5543 if (!EvaluateFloat(SubExpr, Imag, Info))
5544 return false;
5545
5546 Result.FloatReal = APFloat(Imag.getSemantics());
5547 return true;
5548 } else {
5549 assert(SubExpr->getType()->isIntegerType() &&
5550 "Unexpected imaginary literal.");
5551
5552 Result.makeComplexInt();
5553 APSInt &Imag = Result.IntImag;
5554 if (!EvaluateInteger(SubExpr, Imag, Info))
5555 return false;
5556
5557 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5558 return true;
5559 }
5560}
5561
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005562bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005563
John McCall8786da72010-12-14 17:51:41 +00005564 switch (E->getCastKind()) {
5565 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005566 case CK_BaseToDerived:
5567 case CK_DerivedToBase:
5568 case CK_UncheckedDerivedToBase:
5569 case CK_Dynamic:
5570 case CK_ToUnion:
5571 case CK_ArrayToPointerDecay:
5572 case CK_FunctionToPointerDecay:
5573 case CK_NullToPointer:
5574 case CK_NullToMemberPointer:
5575 case CK_BaseToDerivedMemberPointer:
5576 case CK_DerivedToBaseMemberPointer:
5577 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00005578 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00005579 case CK_ConstructorConversion:
5580 case CK_IntegralToPointer:
5581 case CK_PointerToIntegral:
5582 case CK_PointerToBoolean:
5583 case CK_ToVoid:
5584 case CK_VectorSplat:
5585 case CK_IntegralCast:
5586 case CK_IntegralToBoolean:
5587 case CK_IntegralToFloating:
5588 case CK_FloatingToIntegral:
5589 case CK_FloatingToBoolean:
5590 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005591 case CK_CPointerToObjCPointerCast:
5592 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005593 case CK_AnyPointerToBlockPointerCast:
5594 case CK_ObjCObjectLValueCast:
5595 case CK_FloatingComplexToReal:
5596 case CK_FloatingComplexToBoolean:
5597 case CK_IntegralComplexToReal:
5598 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005599 case CK_ARCProduceObject:
5600 case CK_ARCConsumeObject:
5601 case CK_ARCReclaimReturnedObject:
5602 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005603 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005604
John McCall8786da72010-12-14 17:51:41 +00005605 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005606 case CK_AtomicToNonAtomic:
5607 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005608 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005609 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005610
5611 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005612 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005613 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005614 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005615
5616 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005617 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005618 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005619 return false;
5620
John McCall8786da72010-12-14 17:51:41 +00005621 Result.makeComplexFloat();
5622 Result.FloatImag = APFloat(Real.getSemantics());
5623 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005624 }
5625
John McCall8786da72010-12-14 17:51:41 +00005626 case CK_FloatingComplexCast: {
5627 if (!Visit(E->getSubExpr()))
5628 return false;
5629
5630 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5631 QualType From
5632 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5633
Richard Smithc1c5f272011-12-13 06:39:58 +00005634 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5635 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005636 }
5637
5638 case CK_FloatingComplexToIntegralComplex: {
5639 if (!Visit(E->getSubExpr()))
5640 return false;
5641
5642 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5643 QualType From
5644 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5645 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005646 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5647 To, Result.IntReal) &&
5648 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5649 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005650 }
5651
5652 case CK_IntegralRealToComplex: {
5653 APSInt &Real = Result.IntReal;
5654 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5655 return false;
5656
5657 Result.makeComplexInt();
5658 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5659 return true;
5660 }
5661
5662 case CK_IntegralComplexCast: {
5663 if (!Visit(E->getSubExpr()))
5664 return false;
5665
5666 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5667 QualType From
5668 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5669
Richard Smithf72fccf2012-01-30 22:27:01 +00005670 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5671 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005672 return true;
5673 }
5674
5675 case CK_IntegralComplexToFloatingComplex: {
5676 if (!Visit(E->getSubExpr()))
5677 return false;
5678
5679 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5680 QualType From
5681 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5682 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005683 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5684 To, Result.FloatReal) &&
5685 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5686 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005687 }
5688 }
5689
5690 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005691}
5692
John McCallf4cf1a12010-05-07 17:22:02 +00005693bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005694 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005695 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5696
Richard Smith745f5142012-01-27 01:14:48 +00005697 bool LHSOK = Visit(E->getLHS());
5698 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005699 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005700
John McCallf4cf1a12010-05-07 17:22:02 +00005701 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005702 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005703 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005704
Daniel Dunbar3f279872009-01-29 01:32:56 +00005705 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5706 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005707 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005708 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005709 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005710 if (Result.isComplexFloat()) {
5711 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5712 APFloat::rmNearestTiesToEven);
5713 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5714 APFloat::rmNearestTiesToEven);
5715 } else {
5716 Result.getComplexIntReal() += RHS.getComplexIntReal();
5717 Result.getComplexIntImag() += RHS.getComplexIntImag();
5718 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005719 break;
John McCall2de56d12010-08-25 11:45:40 +00005720 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005721 if (Result.isComplexFloat()) {
5722 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5723 APFloat::rmNearestTiesToEven);
5724 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5725 APFloat::rmNearestTiesToEven);
5726 } else {
5727 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5728 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5729 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005730 break;
John McCall2de56d12010-08-25 11:45:40 +00005731 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005732 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005733 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005734 APFloat &LHS_r = LHS.getComplexFloatReal();
5735 APFloat &LHS_i = LHS.getComplexFloatImag();
5736 APFloat &RHS_r = RHS.getComplexFloatReal();
5737 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005738
Daniel Dunbar3f279872009-01-29 01:32:56 +00005739 APFloat Tmp = LHS_r;
5740 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5741 Result.getComplexFloatReal() = Tmp;
5742 Tmp = LHS_i;
5743 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5744 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5745
5746 Tmp = LHS_r;
5747 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5748 Result.getComplexFloatImag() = Tmp;
5749 Tmp = LHS_i;
5750 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5751 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5752 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005753 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005754 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005755 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5756 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00005757 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005758 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5759 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5760 }
5761 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005762 case BO_Div:
5763 if (Result.isComplexFloat()) {
5764 ComplexValue LHS = Result;
5765 APFloat &LHS_r = LHS.getComplexFloatReal();
5766 APFloat &LHS_i = LHS.getComplexFloatImag();
5767 APFloat &RHS_r = RHS.getComplexFloatReal();
5768 APFloat &RHS_i = RHS.getComplexFloatImag();
5769 APFloat &Res_r = Result.getComplexFloatReal();
5770 APFloat &Res_i = Result.getComplexFloatImag();
5771
5772 APFloat Den = RHS_r;
5773 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5774 APFloat Tmp = RHS_i;
5775 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5776 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5777
5778 Res_r = LHS_r;
5779 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5780 Tmp = LHS_i;
5781 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5782 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5783 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5784
5785 Res_i = LHS_i;
5786 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5787 Tmp = LHS_r;
5788 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5789 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5790 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5791 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00005792 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5793 return Error(E, diag::note_expr_divide_by_zero);
5794
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005795 ComplexValue LHS = Result;
5796 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5797 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5798 Result.getComplexIntReal() =
5799 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5800 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5801 Result.getComplexIntImag() =
5802 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5803 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5804 }
5805 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005806 }
5807
John McCallf4cf1a12010-05-07 17:22:02 +00005808 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005809}
5810
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005811bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5812 // Get the operand value into 'Result'.
5813 if (!Visit(E->getSubExpr()))
5814 return false;
5815
5816 switch (E->getOpcode()) {
5817 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00005818 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005819 case UO_Extension:
5820 return true;
5821 case UO_Plus:
5822 // The result is always just the subexpr.
5823 return true;
5824 case UO_Minus:
5825 if (Result.isComplexFloat()) {
5826 Result.getComplexFloatReal().changeSign();
5827 Result.getComplexFloatImag().changeSign();
5828 }
5829 else {
5830 Result.getComplexIntReal() = -Result.getComplexIntReal();
5831 Result.getComplexIntImag() = -Result.getComplexIntImag();
5832 }
5833 return true;
5834 case UO_Not:
5835 if (Result.isComplexFloat())
5836 Result.getComplexFloatImag().changeSign();
5837 else
5838 Result.getComplexIntImag() = -Result.getComplexIntImag();
5839 return true;
5840 }
5841}
5842
Eli Friedman7ead5c72012-01-10 04:58:17 +00005843bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5844 if (E->getNumInits() == 2) {
5845 if (E->getType()->isComplexType()) {
5846 Result.makeComplexFloat();
5847 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5848 return false;
5849 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5850 return false;
5851 } else {
5852 Result.makeComplexInt();
5853 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5854 return false;
5855 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5856 return false;
5857 }
5858 return true;
5859 }
5860 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5861}
5862
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005863//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00005864// Void expression evaluation, primarily for a cast to void on the LHS of a
5865// comma operator
5866//===----------------------------------------------------------------------===//
5867
5868namespace {
5869class VoidExprEvaluator
5870 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5871public:
5872 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5873
5874 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00005875
5876 bool VisitCastExpr(const CastExpr *E) {
5877 switch (E->getCastKind()) {
5878 default:
5879 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5880 case CK_ToVoid:
5881 VisitIgnoredValue(E->getSubExpr());
5882 return true;
5883 }
5884 }
5885};
5886} // end anonymous namespace
5887
5888static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5889 assert(E->isRValue() && E->getType()->isVoidType());
5890 return VoidExprEvaluator(Info).Visit(E);
5891}
5892
5893//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00005894// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005895//===----------------------------------------------------------------------===//
5896
Richard Smith47a1eed2011-10-29 20:57:55 +00005897static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00005898 // In C, function designators are not lvalues, but we evaluate them as if they
5899 // are.
5900 if (E->isGLValue() || E->getType()->isFunctionType()) {
5901 LValue LV;
5902 if (!EvaluateLValue(E, LV, Info))
5903 return false;
5904 LV.moveInto(Result);
5905 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005906 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00005907 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00005908 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005909 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005910 return false;
John McCallefdb83e2010-05-07 21:00:08 +00005911 } else if (E->getType()->hasPointerRepresentation()) {
5912 LValue LV;
5913 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005914 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005915 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00005916 } else if (E->getType()->isRealFloatingType()) {
5917 llvm::APFloat F(0.0);
5918 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005919 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00005920 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00005921 } else if (E->getType()->isAnyComplexType()) {
5922 ComplexValue C;
5923 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005924 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005925 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00005926 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005927 MemberPtr P;
5928 if (!EvaluateMemberPointer(E, P, Info))
5929 return false;
5930 P.moveInto(Result);
5931 return true;
Richard Smith51201882011-12-30 21:15:51 +00005932 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005933 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00005934 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00005935 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00005936 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005937 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00005938 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005939 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00005940 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00005941 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5942 return false;
5943 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00005944 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00005945 if (Info.getLangOpts().CPlusPlus0x)
5946 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5947 << E->getType();
5948 else
5949 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00005950 if (!EvaluateVoid(E, Info))
5951 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005952 } else if (Info.getLangOpts().CPlusPlus0x) {
5953 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5954 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005955 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00005956 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00005957 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005958 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005959
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00005960 return true;
5961}
5962
Richard Smith83587db2012-02-15 02:18:13 +00005963/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
5964/// cases, the in-place evaluation is essential, since later initializers for
5965/// an object can indirectly refer to subobjects which were initialized earlier.
5966static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
5967 const Expr *E, CheckConstantExpressionKind CCEK,
5968 bool AllowNonLiteralTypes) {
Richard Smith7ca48502012-02-13 22:16:19 +00005969 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smith51201882011-12-30 21:15:51 +00005970 return false;
5971
5972 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00005973 // Evaluate arrays and record types in-place, so that later initializers can
5974 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00005975 if (E->getType()->isArrayType())
5976 return EvaluateArray(E, This, Result, Info);
5977 else if (E->getType()->isRecordType())
5978 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00005979 }
5980
5981 // For any other type, in-place evaluation is unimportant.
5982 CCValue CoreConstResult;
Richard Smith83587db2012-02-15 02:18:13 +00005983 if (!Evaluate(CoreConstResult, Info, E))
5984 return false;
5985 Result = CoreConstResult.toAPValue();
5986 return true;
Richard Smith69c2c502011-11-04 05:33:44 +00005987}
5988
Richard Smithf48fdb02011-12-09 22:58:01 +00005989/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5990/// lvalue-to-rvalue cast if it is an lvalue.
5991static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00005992 if (!CheckLiteralType(Info, E))
5993 return false;
5994
Richard Smithf48fdb02011-12-09 22:58:01 +00005995 CCValue Value;
5996 if (!::Evaluate(Value, Info, E))
5997 return false;
5998
5999 if (E->isGLValue()) {
6000 LValue LV;
6001 LV.setFrom(Value);
6002 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
6003 return false;
6004 }
6005
6006 // Check this core constant expression is a constant expression, and if so,
6007 // convert it to one.
Richard Smith83587db2012-02-15 02:18:13 +00006008 Result = Value.toAPValue();
6009 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf48fdb02011-12-09 22:58:01 +00006010}
Richard Smithc49bd112011-10-28 17:51:58 +00006011
Richard Smith51f47082011-10-29 00:50:52 +00006012/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00006013/// any crazy technique (that has nothing to do with language standards) that
6014/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00006015/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6016/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00006017bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00006018 // Fast-path evaluations of integer literals, since we sometimes see files
6019 // containing vast quantities of these.
6020 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
6021 Result.Val = APValue(APSInt(L->getValue(),
6022 L->getType()->isUnsignedIntegerType()));
6023 return true;
6024 }
6025
Richard Smith2d6a5672012-01-14 04:30:29 +00006026 // FIXME: Evaluating values of large array and record types can cause
6027 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00006028 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
6029 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00006030 return false;
6031
Richard Smithf48fdb02011-12-09 22:58:01 +00006032 EvalInfo Info(Ctx, Result);
6033 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00006034}
6035
Jay Foad4ba2a172011-01-12 09:06:06 +00006036bool Expr::EvaluateAsBooleanCondition(bool &Result,
6037 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00006038 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00006039 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithb4e85ed2012-01-06 16:39:00 +00006040 HandleConversionToBool(CCValue(const_cast<ASTContext&>(Ctx),
6041 Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00006042 Result);
John McCallcd7a4452010-01-05 23:42:56 +00006043}
6044
Richard Smith80d4b552011-12-28 19:48:30 +00006045bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6046 SideEffectsKind AllowSideEffects) const {
6047 if (!getType()->isIntegralOrEnumerationType())
6048 return false;
6049
Richard Smithc49bd112011-10-28 17:51:58 +00006050 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00006051 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6052 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00006053 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006054
Richard Smithc49bd112011-10-28 17:51:58 +00006055 Result = ExprResult.Val.getInt();
6056 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006057}
6058
Jay Foad4ba2a172011-01-12 09:06:06 +00006059bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00006060 EvalInfo Info(Ctx, Result);
6061
John McCallefdb83e2010-05-07 21:00:08 +00006062 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006063 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6064 !CheckLValueConstantExpression(Info, getExprLoc(),
6065 Ctx.getLValueReferenceType(getType()), LV))
6066 return false;
6067
6068 CCValue Tmp;
6069 LV.moveInto(Tmp);
6070 Result.Val = Tmp.toAPValue();
6071 return true;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00006072}
6073
Richard Smith099e7f62011-12-19 06:19:21 +00006074bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6075 const VarDecl *VD,
6076 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00006077 // FIXME: Evaluating initializers for large array and record types can cause
6078 // performance problems. Only do so in C++11 for now.
6079 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
6080 !Ctx.getLangOptions().CPlusPlus0x)
6081 return false;
6082
Richard Smith099e7f62011-12-19 06:19:21 +00006083 Expr::EvalStatus EStatus;
6084 EStatus.Diag = &Notes;
6085
6086 EvalInfo InitInfo(Ctx, EStatus);
6087 InitInfo.setEvaluatingDecl(VD, Value);
6088
6089 LValue LVal;
6090 LVal.set(VD);
6091
Richard Smith51201882011-12-30 21:15:51 +00006092 // C++11 [basic.start.init]p2:
6093 // Variables with static storage duration or thread storage duration shall be
6094 // zero-initialized before any other initialization takes place.
6095 // This behavior is not present in C.
6096 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
6097 !VD->getType()->isReferenceType()) {
6098 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith83587db2012-02-15 02:18:13 +00006099 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6100 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00006101 return false;
6102 }
6103
Richard Smith83587db2012-02-15 02:18:13 +00006104 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6105 /*AllowNonLiteralTypes=*/true) ||
6106 EStatus.HasSideEffects)
6107 return false;
6108
6109 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6110 Value);
Richard Smith099e7f62011-12-19 06:19:21 +00006111}
6112
Richard Smith51f47082011-10-29 00:50:52 +00006113/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6114/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00006115bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00006116 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00006117 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00006118}
Anders Carlsson51fe9962008-11-22 21:04:56 +00006119
Jay Foad4ba2a172011-01-12 09:06:06 +00006120bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00006121 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00006122}
6123
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006124APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006125 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00006126 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00006127 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00006128 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006129 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00006130
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006131 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00006132}
John McCalld905f5a2010-05-07 05:32:02 +00006133
Abramo Bagnarae17a6432010-05-14 17:07:14 +00006134 bool Expr::EvalResult::isGlobalLValue() const {
6135 assert(Val.isLValue());
6136 return IsGlobalLValue(Val.getLValueBase());
6137 }
6138
6139
John McCalld905f5a2010-05-07 05:32:02 +00006140/// isIntegerConstantExpr - this recursive routine will test if an expression is
6141/// an integer constant expression.
6142
6143/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6144/// comma, etc
6145///
6146/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
6147/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
6148/// cast+dereference.
6149
6150// CheckICE - This function does the fundamental ICE checking: the returned
6151// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
6152// Note that to reduce code duplication, this helper does no evaluation
6153// itself; the caller checks whether the expression is evaluatable, and
6154// in the rare cases where CheckICE actually cares about the evaluated
6155// value, it calls into Evalute.
6156//
6157// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00006158// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00006159// 1: This expression is not an ICE, but if it isn't evaluated, it's
6160// a legal subexpression for an ICE. This return value is used to handle
6161// the comma operator in C99 mode.
6162// 2: This expression is not an ICE, and is not a legal subexpression for one.
6163
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006164namespace {
6165
John McCalld905f5a2010-05-07 05:32:02 +00006166struct ICEDiag {
6167 unsigned Val;
6168 SourceLocation Loc;
6169
6170 public:
6171 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6172 ICEDiag() : Val(0) {}
6173};
6174
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006175}
6176
6177static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00006178
6179static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6180 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006181 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00006182 !EVResult.Val.isInt()) {
6183 return ICEDiag(2, E->getLocStart());
6184 }
6185 return NoDiag();
6186}
6187
6188static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6189 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00006190 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00006191 return ICEDiag(2, E->getLocStart());
6192 }
6193
6194 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006195#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006196#define STMT(Node, Base) case Expr::Node##Class:
6197#define EXPR(Node, Base)
6198#include "clang/AST/StmtNodes.inc"
6199 case Expr::PredefinedExprClass:
6200 case Expr::FloatingLiteralClass:
6201 case Expr::ImaginaryLiteralClass:
6202 case Expr::StringLiteralClass:
6203 case Expr::ArraySubscriptExprClass:
6204 case Expr::MemberExprClass:
6205 case Expr::CompoundAssignOperatorClass:
6206 case Expr::CompoundLiteralExprClass:
6207 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006208 case Expr::DesignatedInitExprClass:
6209 case Expr::ImplicitValueInitExprClass:
6210 case Expr::ParenListExprClass:
6211 case Expr::VAArgExprClass:
6212 case Expr::AddrLabelExprClass:
6213 case Expr::StmtExprClass:
6214 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006215 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006216 case Expr::CXXDynamicCastExprClass:
6217 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006218 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006219 case Expr::CXXNullPtrLiteralExprClass:
6220 case Expr::CXXThisExprClass:
6221 case Expr::CXXThrowExprClass:
6222 case Expr::CXXNewExprClass:
6223 case Expr::CXXDeleteExprClass:
6224 case Expr::CXXPseudoDestructorExprClass:
6225 case Expr::UnresolvedLookupExprClass:
6226 case Expr::DependentScopeDeclRefExprClass:
6227 case Expr::CXXConstructExprClass:
6228 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006229 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006230 case Expr::CXXTemporaryObjectExprClass:
6231 case Expr::CXXUnresolvedConstructExprClass:
6232 case Expr::CXXDependentScopeMemberExprClass:
6233 case Expr::UnresolvedMemberExprClass:
6234 case Expr::ObjCStringLiteralClass:
6235 case Expr::ObjCEncodeExprClass:
6236 case Expr::ObjCMessageExprClass:
6237 case Expr::ObjCSelectorExprClass:
6238 case Expr::ObjCProtocolExprClass:
6239 case Expr::ObjCIvarRefExprClass:
6240 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006241 case Expr::ObjCIsaExprClass:
6242 case Expr::ShuffleVectorExprClass:
6243 case Expr::BlockExprClass:
6244 case Expr::BlockDeclRefExprClass:
6245 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006246 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006247 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006248 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006249 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006250 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006251 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006252 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006253 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006254 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00006255 case Expr::LambdaExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006256 return ICEDiag(2, E->getLocStart());
6257
Douglas Gregoree8aff02011-01-04 17:33:58 +00006258 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006259 case Expr::GNUNullExprClass:
6260 // GCC considers the GNU __null value to be an integral constant expression.
6261 return NoDiag();
6262
John McCall91a57552011-07-15 05:09:51 +00006263 case Expr::SubstNonTypeTemplateParmExprClass:
6264 return
6265 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6266
John McCalld905f5a2010-05-07 05:32:02 +00006267 case Expr::ParenExprClass:
6268 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006269 case Expr::GenericSelectionExprClass:
6270 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006271 case Expr::IntegerLiteralClass:
6272 case Expr::CharacterLiteralClass:
6273 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006274 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006275 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006276 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006277 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006278 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006279 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006280 return NoDiag();
6281 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006282 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006283 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6284 // constant expressions, but they can never be ICEs because an ICE cannot
6285 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006286 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006287 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006288 return CheckEvalInICE(E, Ctx);
6289 return ICEDiag(2, E->getLocStart());
6290 }
6291 case Expr::DeclRefExprClass:
6292 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6293 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00006294 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006295 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
6296
6297 // Parameter variables are never constants. Without this check,
6298 // getAnyInitializer() can find a default argument, which leads
6299 // to chaos.
6300 if (isa<ParmVarDecl>(D))
6301 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6302
6303 // C++ 7.1.5.1p2
6304 // A variable of non-volatile const-qualified integral or enumeration
6305 // type initialized by an ICE can be used in ICEs.
6306 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006307 if (!Dcl->getType()->isIntegralOrEnumerationType())
6308 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6309
Richard Smith099e7f62011-12-19 06:19:21 +00006310 const VarDecl *VD;
6311 // Look for a declaration of this variable that has an initializer, and
6312 // check whether it is an ICE.
6313 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6314 return NoDiag();
6315 else
6316 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006317 }
6318 }
6319 return ICEDiag(2, E->getLocStart());
6320 case Expr::UnaryOperatorClass: {
6321 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6322 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006323 case UO_PostInc:
6324 case UO_PostDec:
6325 case UO_PreInc:
6326 case UO_PreDec:
6327 case UO_AddrOf:
6328 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006329 // C99 6.6/3 allows increment and decrement within unevaluated
6330 // subexpressions of constant expressions, but they can never be ICEs
6331 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006332 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006333 case UO_Extension:
6334 case UO_LNot:
6335 case UO_Plus:
6336 case UO_Minus:
6337 case UO_Not:
6338 case UO_Real:
6339 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006340 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006341 }
6342
6343 // OffsetOf falls through here.
6344 }
6345 case Expr::OffsetOfExprClass: {
6346 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00006347 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00006348 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00006349 // compliance: we should warn earlier for offsetof expressions with
6350 // array subscripts that aren't ICEs, and if the array subscripts
6351 // are ICEs, the value of the offsetof must be an integer constant.
6352 return CheckEvalInICE(E, Ctx);
6353 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006354 case Expr::UnaryExprOrTypeTraitExprClass: {
6355 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6356 if ((Exp->getKind() == UETT_SizeOf) &&
6357 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00006358 return ICEDiag(2, E->getLocStart());
6359 return NoDiag();
6360 }
6361 case Expr::BinaryOperatorClass: {
6362 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6363 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006364 case BO_PtrMemD:
6365 case BO_PtrMemI:
6366 case BO_Assign:
6367 case BO_MulAssign:
6368 case BO_DivAssign:
6369 case BO_RemAssign:
6370 case BO_AddAssign:
6371 case BO_SubAssign:
6372 case BO_ShlAssign:
6373 case BO_ShrAssign:
6374 case BO_AndAssign:
6375 case BO_XorAssign:
6376 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006377 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6378 // constant expressions, but they can never be ICEs because an ICE cannot
6379 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006380 return ICEDiag(2, E->getLocStart());
6381
John McCall2de56d12010-08-25 11:45:40 +00006382 case BO_Mul:
6383 case BO_Div:
6384 case BO_Rem:
6385 case BO_Add:
6386 case BO_Sub:
6387 case BO_Shl:
6388 case BO_Shr:
6389 case BO_LT:
6390 case BO_GT:
6391 case BO_LE:
6392 case BO_GE:
6393 case BO_EQ:
6394 case BO_NE:
6395 case BO_And:
6396 case BO_Xor:
6397 case BO_Or:
6398 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006399 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6400 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006401 if (Exp->getOpcode() == BO_Div ||
6402 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006403 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006404 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006405 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006406 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006407 if (REval == 0)
6408 return ICEDiag(1, E->getLocStart());
6409 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006410 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006411 if (LEval.isMinSignedValue())
6412 return ICEDiag(1, E->getLocStart());
6413 }
6414 }
6415 }
John McCall2de56d12010-08-25 11:45:40 +00006416 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00006417 if (Ctx.getLangOptions().C99) {
6418 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6419 // if it isn't evaluated.
6420 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6421 return ICEDiag(1, E->getLocStart());
6422 } else {
6423 // In both C89 and C++, commas in ICEs are illegal.
6424 return ICEDiag(2, E->getLocStart());
6425 }
6426 }
6427 if (LHSResult.Val >= RHSResult.Val)
6428 return LHSResult;
6429 return RHSResult;
6430 }
John McCall2de56d12010-08-25 11:45:40 +00006431 case BO_LAnd:
6432 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006433 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6434 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6435 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6436 // Rare case where the RHS has a comma "side-effect"; we need
6437 // to actually check the condition to see whether the side
6438 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006439 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006440 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006441 return RHSResult;
6442 return NoDiag();
6443 }
6444
6445 if (LHSResult.Val >= RHSResult.Val)
6446 return LHSResult;
6447 return RHSResult;
6448 }
6449 }
6450 }
6451 case Expr::ImplicitCastExprClass:
6452 case Expr::CStyleCastExprClass:
6453 case Expr::CXXFunctionalCastExprClass:
6454 case Expr::CXXStaticCastExprClass:
6455 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006456 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006457 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006458 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006459 if (isa<ExplicitCastExpr>(E)) {
6460 if (const FloatingLiteral *FL
6461 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6462 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6463 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6464 APSInt IgnoredVal(DestWidth, !DestSigned);
6465 bool Ignored;
6466 // If the value does not fit in the destination type, the behavior is
6467 // undefined, so we are not required to treat it as a constant
6468 // expression.
6469 if (FL->getValue().convertToInteger(IgnoredVal,
6470 llvm::APFloat::rmTowardZero,
6471 &Ignored) & APFloat::opInvalidOp)
6472 return ICEDiag(2, E->getLocStart());
6473 return NoDiag();
6474 }
6475 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006476 switch (cast<CastExpr>(E)->getCastKind()) {
6477 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006478 case CK_AtomicToNonAtomic:
6479 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006480 case CK_NoOp:
6481 case CK_IntegralToBoolean:
6482 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006483 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006484 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006485 return ICEDiag(2, E->getLocStart());
6486 }
John McCalld905f5a2010-05-07 05:32:02 +00006487 }
John McCall56ca35d2011-02-17 10:25:35 +00006488 case Expr::BinaryConditionalOperatorClass: {
6489 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6490 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6491 if (CommonResult.Val == 2) return CommonResult;
6492 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6493 if (FalseResult.Val == 2) return FalseResult;
6494 if (CommonResult.Val == 1) return CommonResult;
6495 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006496 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006497 return FalseResult;
6498 }
John McCalld905f5a2010-05-07 05:32:02 +00006499 case Expr::ConditionalOperatorClass: {
6500 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6501 // If the condition (ignoring parens) is a __builtin_constant_p call,
6502 // then only the true side is actually considered in an integer constant
6503 // expression, and it is fully evaluated. This is an important GNU
6504 // extension. See GCC PR38377 for discussion.
6505 if (const CallExpr *CallCE
6506 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006507 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6508 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006509 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006510 if (CondResult.Val == 2)
6511 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006512
Richard Smithf48fdb02011-12-09 22:58:01 +00006513 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6514 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006515
John McCalld905f5a2010-05-07 05:32:02 +00006516 if (TrueResult.Val == 2)
6517 return TrueResult;
6518 if (FalseResult.Val == 2)
6519 return FalseResult;
6520 if (CondResult.Val == 1)
6521 return CondResult;
6522 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6523 return NoDiag();
6524 // Rare case where the diagnostics depend on which side is evaluated
6525 // Note that if we get here, CondResult is 0, and at least one of
6526 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006527 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006528 return FalseResult;
6529 }
6530 return TrueResult;
6531 }
6532 case Expr::CXXDefaultArgExprClass:
6533 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6534 case Expr::ChooseExprClass: {
6535 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6536 }
6537 }
6538
David Blaikie30263482012-01-20 21:50:17 +00006539 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006540}
6541
Richard Smithf48fdb02011-12-09 22:58:01 +00006542/// Evaluate an expression as a C++11 integral constant expression.
6543static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6544 const Expr *E,
6545 llvm::APSInt *Value,
6546 SourceLocation *Loc) {
6547 if (!E->getType()->isIntegralOrEnumerationType()) {
6548 if (Loc) *Loc = E->getExprLoc();
6549 return false;
6550 }
6551
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006552 APValue Result;
6553 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006554 return false;
6555
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006556 assert(Result.isInt() && "pointer cast to int is not an ICE");
6557 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006558 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006559}
6560
Richard Smithdd1f29b2011-12-12 09:28:41 +00006561bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00006562 if (Ctx.getLangOptions().CPlusPlus0x)
6563 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6564
John McCalld905f5a2010-05-07 05:32:02 +00006565 ICEDiag d = CheckICE(this, Ctx);
6566 if (d.Val != 0) {
6567 if (Loc) *Loc = d.Loc;
6568 return false;
6569 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006570 return true;
6571}
6572
6573bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6574 SourceLocation *Loc, bool isEvaluated) const {
6575 if (Ctx.getLangOptions().CPlusPlus0x)
6576 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6577
6578 if (!isIntegerConstantExpr(Ctx, Loc))
6579 return false;
6580 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006581 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006582 return true;
6583}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006584
Richard Smith70488e22012-02-14 21:38:30 +00006585bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
6586 return CheckICE(this, Ctx).Val == 0;
6587}
6588
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006589bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6590 SourceLocation *Loc) const {
6591 // We support this checking in C++98 mode in order to diagnose compatibility
6592 // issues.
6593 assert(Ctx.getLangOptions().CPlusPlus);
6594
Richard Smith70488e22012-02-14 21:38:30 +00006595 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006596 Expr::EvalStatus Status;
6597 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6598 Status.Diag = &Diags;
6599 EvalInfo Info(Ctx, Status);
6600
6601 APValue Scratch;
6602 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6603
6604 if (!Diags.empty()) {
6605 IsConstExpr = false;
6606 if (Loc) *Loc = Diags[0].first;
6607 } else if (!IsConstExpr) {
6608 // FIXME: This shouldn't happen.
6609 if (Loc) *Loc = getExprLoc();
6610 }
6611
6612 return IsConstExpr;
6613}
Richard Smith745f5142012-01-27 01:14:48 +00006614
6615bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6616 llvm::SmallVectorImpl<
6617 PartialDiagnosticAt> &Diags) {
6618 // FIXME: It would be useful to check constexpr function templates, but at the
6619 // moment the constant expression evaluator cannot cope with the non-rigorous
6620 // ASTs which we build for dependent expressions.
6621 if (FD->isDependentContext())
6622 return true;
6623
6624 Expr::EvalStatus Status;
6625 Status.Diag = &Diags;
6626
6627 EvalInfo Info(FD->getASTContext(), Status);
6628 Info.CheckingPotentialConstantExpression = true;
6629
6630 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6631 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6632
6633 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6634 // is a temporary being used as the 'this' pointer.
6635 LValue This;
6636 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smith83587db2012-02-15 02:18:13 +00006637 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith745f5142012-01-27 01:14:48 +00006638
Richard Smith745f5142012-01-27 01:14:48 +00006639 ArrayRef<const Expr*> Args;
6640
6641 SourceLocation Loc = FD->getLocation();
6642
6643 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Richard Smith83587db2012-02-15 02:18:13 +00006644 APValue Scratch;
Richard Smith745f5142012-01-27 01:14:48 +00006645 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith83587db2012-02-15 02:18:13 +00006646 } else {
6647 CCValue Scratch;
Richard Smith745f5142012-01-27 01:14:48 +00006648 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6649 Args, FD->getBody(), Info, Scratch);
Richard Smith83587db2012-02-15 02:18:13 +00006650 }
Richard Smith745f5142012-01-27 01:14:48 +00006651
6652 return Diags.empty();
6653}