blob: 9454895c7529b7015017afaa9a80134b0ef6e153 [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() {
547 return CheckingPotentialConstantExpression && EvalStatus.Diag->empty();
548 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000549 };
Richard Smithf15fda02012-02-02 01:16:57 +0000550
551 /// Object used to treat all foldable expressions as constant expressions.
552 struct FoldConstant {
553 bool Enabled;
554
555 explicit FoldConstant(EvalInfo &Info)
556 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
557 !Info.EvalStatus.HasSideEffects) {
558 }
559 // Treat the value we've computed since this object was created as constant.
560 void Fold(EvalInfo &Info) {
561 if (Enabled && !Info.EvalStatus.Diag->empty() &&
562 !Info.EvalStatus.HasSideEffects)
563 Info.EvalStatus.Diag->clear();
564 }
565 };
Richard Smith08d6e032011-12-16 19:06:07 +0000566}
Richard Smithbd552ef2011-10-31 05:52:43 +0000567
Richard Smithb4e85ed2012-01-06 16:39:00 +0000568bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
569 CheckSubobjectKind CSK) {
570 if (Invalid)
571 return false;
572 if (isOnePastTheEnd()) {
573 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_past_end_subobject)
574 << CSK;
575 setInvalid();
576 return false;
577 }
578 return true;
579}
580
581void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
582 const Expr *E, uint64_t N) {
583 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
584 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
585 << static_cast<int>(N) << /*array*/ 0
586 << static_cast<unsigned>(MostDerivedArraySize);
587 else
588 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
589 << static_cast<int>(N) << /*non-array*/ 1;
590 setInvalid();
591}
592
Richard Smith08d6e032011-12-16 19:06:07 +0000593CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
594 const FunctionDecl *Callee, const LValue *This,
595 const CCValue *Arguments)
596 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smith83587db2012-02-15 02:18:13 +0000597 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smith08d6e032011-12-16 19:06:07 +0000598 Info.CurrentCall = this;
599 ++Info.CallStackDepth;
600}
601
602CallStackFrame::~CallStackFrame() {
603 assert(Info.CurrentCall == this && "calls retired out of order");
604 --Info.CallStackDepth;
605 Info.CurrentCall = Caller;
606}
607
608/// Produce a string describing the given constexpr call.
609static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
610 unsigned ArgIndex = 0;
611 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith5ba73e12012-02-04 00:33:54 +0000612 !isa<CXXConstructorDecl>(Frame->Callee) &&
613 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smith08d6e032011-12-16 19:06:07 +0000614
615 if (!IsMemberCall)
616 Out << *Frame->Callee << '(';
617
618 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
619 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumi5fe31222012-01-26 09:37:36 +0000620 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smith08d6e032011-12-16 19:06:07 +0000621 Out << ", ";
622
623 const ParmVarDecl *Param = *I;
624 const CCValue &Arg = Frame->Arguments[ArgIndex];
625 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
626 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
627 else {
Richard Smith83587db2012-02-15 02:18:13 +0000628 // Convert the CCValue to an APValue without checking for constantness.
Richard Smith08d6e032011-12-16 19:06:07 +0000629 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
630 Arg.getLValueDesignator().Entries,
Richard Smith83587db2012-02-15 02:18:13 +0000631 Arg.getLValueDesignator().IsOnePastTheEnd,
632 Arg.getLValueCallIndex());
Richard Smith08d6e032011-12-16 19:06:07 +0000633 Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
634 }
635
636 if (ArgIndex == 0 && IsMemberCall)
637 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000638 }
639
Richard Smith08d6e032011-12-16 19:06:07 +0000640 Out << ')';
641}
642
643void EvalInfo::addCallStack(unsigned Limit) {
644 // Determine which calls to skip, if any.
645 unsigned ActiveCalls = CallStackDepth - 1;
646 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
647 if (Limit && Limit < ActiveCalls) {
648 SkipStart = Limit / 2 + Limit % 2;
649 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000650 }
651
Richard Smith08d6e032011-12-16 19:06:07 +0000652 // Walk the call stack and add the diagnostics.
653 unsigned CallIdx = 0;
654 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
655 Frame = Frame->Caller, ++CallIdx) {
656 // Skip this call?
657 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
658 if (CallIdx == SkipStart) {
659 // Note that we're skipping calls.
660 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
661 << unsigned(ActiveCalls - Limit);
662 }
663 continue;
664 }
665
666 llvm::SmallVector<char, 128> Buffer;
667 llvm::raw_svector_ostream Out(Buffer);
668 describeCall(Frame, Out);
669 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
670 }
671}
672
673namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000674 struct ComplexValue {
675 private:
676 bool IsInt;
677
678 public:
679 APSInt IntReal, IntImag;
680 APFloat FloatReal, FloatImag;
681
682 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
683
684 void makeComplexFloat() { IsInt = false; }
685 bool isComplexFloat() const { return !IsInt; }
686 APFloat &getComplexFloatReal() { return FloatReal; }
687 APFloat &getComplexFloatImag() { return FloatImag; }
688
689 void makeComplexInt() { IsInt = true; }
690 bool isComplexInt() const { return IsInt; }
691 APSInt &getComplexIntReal() { return IntReal; }
692 APSInt &getComplexIntImag() { return IntImag; }
693
Richard Smith47a1eed2011-10-29 20:57:55 +0000694 void moveInto(CCValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000695 if (isComplexFloat())
Richard Smith47a1eed2011-10-29 20:57:55 +0000696 v = CCValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000697 else
Richard Smith47a1eed2011-10-29 20:57:55 +0000698 v = CCValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000699 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000700 void setFrom(const CCValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000701 assert(v.isComplexFloat() || v.isComplexInt());
702 if (v.isComplexFloat()) {
703 makeComplexFloat();
704 FloatReal = v.getComplexFloatReal();
705 FloatImag = v.getComplexFloatImag();
706 } else {
707 makeComplexInt();
708 IntReal = v.getComplexIntReal();
709 IntImag = v.getComplexIntImag();
710 }
711 }
John McCallf4cf1a12010-05-07 17:22:02 +0000712 };
John McCallefdb83e2010-05-07 21:00:08 +0000713
714 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000715 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000716 CharUnits Offset;
Richard Smith83587db2012-02-15 02:18:13 +0000717 unsigned CallIndex;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000718 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000719
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000720 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000721 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000722 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith83587db2012-02-15 02:18:13 +0000723 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000724 SubobjectDesignator &getLValueDesignator() { return Designator; }
725 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000726
Richard Smith47a1eed2011-10-29 20:57:55 +0000727 void moveInto(CCValue &V) const {
Richard Smith83587db2012-02-15 02:18:13 +0000728 V = CCValue(Base, Offset, CallIndex, Designator);
John McCallefdb83e2010-05-07 21:00:08 +0000729 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000730 void setFrom(const CCValue &V) {
731 assert(V.isLValue());
732 Base = V.getLValueBase();
733 Offset = V.getLValueOffset();
Richard Smith83587db2012-02-15 02:18:13 +0000734 CallIndex = V.getLValueCallIndex();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000735 Designator = V.getLValueDesignator();
736 }
737
Richard Smith83587db2012-02-15 02:18:13 +0000738 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000739 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000740 Offset = CharUnits::Zero();
Richard Smith83587db2012-02-15 02:18:13 +0000741 CallIndex = I;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000742 Designator = SubobjectDesignator(getType(B));
743 }
744
745 // Check that this LValue is not based on a null pointer. If it is, produce
746 // a diagnostic and mark the designator as invalid.
747 bool checkNullPointer(EvalInfo &Info, const Expr *E,
748 CheckSubobjectKind CSK) {
749 if (Designator.Invalid)
750 return false;
751 if (!Base) {
752 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_null_subobject)
753 << CSK;
754 Designator.setInvalid();
755 return false;
756 }
757 return true;
758 }
759
760 // Check this LValue refers to an object. If not, set the designator to be
761 // invalid and emit a diagnostic.
762 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
763 return checkNullPointer(Info, E, CSK) &&
764 Designator.checkSubobject(Info, E, CSK);
765 }
766
767 void addDecl(EvalInfo &Info, const Expr *E,
768 const Decl *D, bool Virtual = false) {
769 checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base);
770 Designator.addDeclUnchecked(D, Virtual);
771 }
772 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
773 checkSubobject(Info, E, CSK_ArrayToPointer);
774 Designator.addArrayUnchecked(CAT);
775 }
776 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
777 if (!checkNullPointer(Info, E, CSK_ArrayIndex))
778 return;
779 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000780 }
John McCallefdb83e2010-05-07 21:00:08 +0000781 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000782
783 struct MemberPtr {
784 MemberPtr() {}
785 explicit MemberPtr(const ValueDecl *Decl) :
786 DeclAndIsDerivedMember(Decl, false), Path() {}
787
788 /// The member or (direct or indirect) field referred to by this member
789 /// pointer, or 0 if this is a null member pointer.
790 const ValueDecl *getDecl() const {
791 return DeclAndIsDerivedMember.getPointer();
792 }
793 /// Is this actually a member of some type derived from the relevant class?
794 bool isDerivedMember() const {
795 return DeclAndIsDerivedMember.getInt();
796 }
797 /// Get the class which the declaration actually lives in.
798 const CXXRecordDecl *getContainingRecord() const {
799 return cast<CXXRecordDecl>(
800 DeclAndIsDerivedMember.getPointer()->getDeclContext());
801 }
802
803 void moveInto(CCValue &V) const {
804 V = CCValue(getDecl(), isDerivedMember(), Path);
805 }
806 void setFrom(const CCValue &V) {
807 assert(V.isMemberPointer());
808 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
809 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
810 Path.clear();
811 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
812 Path.insert(Path.end(), P.begin(), P.end());
813 }
814
815 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
816 /// whether the member is a member of some class derived from the class type
817 /// of the member pointer.
818 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
819 /// Path - The path of base/derived classes from the member declaration's
820 /// class (exclusive) to the class type of the member pointer (inclusive).
821 SmallVector<const CXXRecordDecl*, 4> Path;
822
823 /// Perform a cast towards the class of the Decl (either up or down the
824 /// hierarchy).
825 bool castBack(const CXXRecordDecl *Class) {
826 assert(!Path.empty());
827 const CXXRecordDecl *Expected;
828 if (Path.size() >= 2)
829 Expected = Path[Path.size() - 2];
830 else
831 Expected = getContainingRecord();
832 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
833 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
834 // if B does not contain the original member and is not a base or
835 // derived class of the class containing the original member, the result
836 // of the cast is undefined.
837 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
838 // (D::*). We consider that to be a language defect.
839 return false;
840 }
841 Path.pop_back();
842 return true;
843 }
844 /// Perform a base-to-derived member pointer cast.
845 bool castToDerived(const CXXRecordDecl *Derived) {
846 if (!getDecl())
847 return true;
848 if (!isDerivedMember()) {
849 Path.push_back(Derived);
850 return true;
851 }
852 if (!castBack(Derived))
853 return false;
854 if (Path.empty())
855 DeclAndIsDerivedMember.setInt(false);
856 return true;
857 }
858 /// Perform a derived-to-base member pointer cast.
859 bool castToBase(const CXXRecordDecl *Base) {
860 if (!getDecl())
861 return true;
862 if (Path.empty())
863 DeclAndIsDerivedMember.setInt(true);
864 if (isDerivedMember()) {
865 Path.push_back(Base);
866 return true;
867 }
868 return castBack(Base);
869 }
870 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000871
Richard Smithb02e4622012-02-01 01:42:44 +0000872 /// Compare two member pointers, which are assumed to be of the same type.
873 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
874 if (!LHS.getDecl() || !RHS.getDecl())
875 return !LHS.getDecl() && !RHS.getDecl();
876 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
877 return false;
878 return LHS.Path == RHS.Path;
879 }
880
Richard Smithc1c5f272011-12-13 06:39:58 +0000881 /// Kinds of constant expression checking, for diagnostics.
882 enum CheckConstantExpressionKind {
883 CCEK_Constant, ///< A normal constant.
884 CCEK_ReturnValue, ///< A constexpr function return value.
885 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
886 };
John McCallf4cf1a12010-05-07 17:22:02 +0000887}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000888
Richard Smith47a1eed2011-10-29 20:57:55 +0000889static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith83587db2012-02-15 02:18:13 +0000890static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
891 const LValue &This, const Expr *E,
892 CheckConstantExpressionKind CCEK = CCEK_Constant,
893 bool AllowNonLiteralTypes = false);
John McCallefdb83e2010-05-07 21:00:08 +0000894static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
895static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000896static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
897 EvalInfo &Info);
898static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000899static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith47a1eed2011-10-29 20:57:55 +0000900static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000901 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000902static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000903static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000904
905//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000906// Misc utilities
907//===----------------------------------------------------------------------===//
908
Richard Smith180f4792011-11-10 06:34:14 +0000909/// Should this call expression be treated as a string literal?
910static bool IsStringLiteralCall(const CallExpr *E) {
911 unsigned Builtin = E->isBuiltinCall();
912 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
913 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
914}
915
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000916static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000917 // C++11 [expr.const]p3 An address constant expression is a prvalue core
918 // constant expression of pointer type that evaluates to...
919
920 // ... a null pointer value, or a prvalue core constant expression of type
921 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000922 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000923
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000924 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
925 // ... the address of an object with static storage duration,
926 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
927 return VD->hasGlobalStorage();
928 // ... the address of a function,
929 return isa<FunctionDecl>(D);
930 }
931
932 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000933 switch (E->getStmtClass()) {
934 default:
935 return false;
Richard Smith180f4792011-11-10 06:34:14 +0000936 case Expr::CompoundLiteralExprClass:
937 return cast<CompoundLiteralExpr>(E)->isFileScope();
938 // A string literal has static storage duration.
939 case Expr::StringLiteralClass:
940 case Expr::PredefinedExprClass:
941 case Expr::ObjCStringLiteralClass:
942 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000943 case Expr::CXXTypeidExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000944 return true;
945 case Expr::CallExprClass:
946 return IsStringLiteralCall(cast<CallExpr>(E));
947 // For GCC compatibility, &&label has static storage duration.
948 case Expr::AddrLabelExprClass:
949 return true;
950 // A Block literal expression may be used as the initialization value for
951 // Block variables at global or local static scope.
952 case Expr::BlockExprClass:
953 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000954 case Expr::ImplicitValueInitExprClass:
955 // FIXME:
956 // We can never form an lvalue with an implicit value initialization as its
957 // base through expression evaluation, so these only appear in one case: the
958 // implicit variable declaration we invent when checking whether a constexpr
959 // constructor can produce a constant expression. We must assume that such
960 // an expression might be a global lvalue.
961 return true;
Richard Smith180f4792011-11-10 06:34:14 +0000962 }
John McCall42c8f872010-05-10 23:27:23 +0000963}
964
Richard Smith83587db2012-02-15 02:18:13 +0000965static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
966 assert(Base && "no location for a null lvalue");
967 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
968 if (VD)
969 Info.Note(VD->getLocation(), diag::note_declared_at);
970 else
971 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
972 diag::note_constexpr_temporary_here);
973}
974
Richard Smith9a17a682011-11-07 05:07:52 +0000975/// Check that this reference or pointer core constant expression is a valid
Richard Smithb4e85ed2012-01-06 16:39:00 +0000976/// value for an address or reference constant expression. Type T should be
Richard Smith61e61622012-01-12 06:08:57 +0000977/// either LValue or CCValue. Return true if we can fold this expression,
978/// whether or not it's a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +0000979static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
980 QualType Type, const LValue &LVal) {
981 bool IsReferenceType = Type->isReferenceType();
982
Richard Smithc1c5f272011-12-13 06:39:58 +0000983 APValue::LValueBase Base = LVal.getLValueBase();
984 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
985
986 if (!IsGlobalLValue(Base)) {
987 if (Info.getLangOpts().CPlusPlus0x) {
988 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +0000989 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
990 << IsReferenceType << !Designator.Entries.empty()
991 << !!VD << VD;
992 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +0000993 } else {
Richard Smith83587db2012-02-15 02:18:13 +0000994 Info.Diag(Loc);
Richard Smithc1c5f272011-12-13 06:39:58 +0000995 }
Richard Smith61e61622012-01-12 06:08:57 +0000996 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +0000997 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000998 }
Richard Smith83587db2012-02-15 02:18:13 +0000999 assert((Info.CheckingPotentialConstantExpression ||
1000 LVal.getLValueCallIndex() == 0) &&
1001 "have call index for global lvalue");
Richard Smithb4e85ed2012-01-06 16:39:00 +00001002
1003 // Allow address constant expressions to be past-the-end pointers. This is
1004 // an extension: the standard requires them to point to an object.
1005 if (!IsReferenceType)
1006 return true;
1007
1008 // A reference constant expression must refer to an object.
1009 if (!Base) {
1010 // FIXME: diagnostic
Richard Smith83587db2012-02-15 02:18:13 +00001011 Info.CCEDiag(Loc);
Richard Smith61e61622012-01-12 06:08:57 +00001012 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001013 }
1014
Richard Smithc1c5f272011-12-13 06:39:58 +00001015 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +00001016 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001017 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001018 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smithc1c5f272011-12-13 06:39:58 +00001019 << !Designator.Entries.empty() << !!VD << VD;
Richard Smith83587db2012-02-15 02:18:13 +00001020 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001021 }
1022
Richard Smith9a17a682011-11-07 05:07:52 +00001023 return true;
1024}
1025
Richard Smith51201882011-12-30 21:15:51 +00001026/// Check that this core constant expression is of literal type, and if not,
1027/// produce an appropriate diagnostic.
1028static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1029 if (!E->isRValue() || E->getType()->isLiteralType())
1030 return true;
1031
1032 // Prvalue constant expressions must be of literal types.
1033 if (Info.getLangOpts().CPlusPlus0x)
1034 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
1035 << E->getType();
1036 else
1037 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1038 return false;
1039}
1040
Richard Smith47a1eed2011-10-29 20:57:55 +00001041/// Check that this core constant expression value is a valid value for a
Richard Smith83587db2012-02-15 02:18:13 +00001042/// constant expression. If not, report an appropriate diagnostic. Does not
1043/// check that the expression is of literal type.
1044static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1045 QualType Type, const APValue &Value) {
1046 // Core issue 1454: For a literal constant expression of array or class type,
1047 // each subobject of its value shall have been initialized by a constant
1048 // expression.
1049 if (Value.isArray()) {
1050 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1051 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1052 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1053 Value.getArrayInitializedElt(I)))
1054 return false;
1055 }
1056 if (!Value.hasArrayFiller())
1057 return true;
1058 return CheckConstantExpression(Info, DiagLoc, EltTy,
1059 Value.getArrayFiller());
Richard Smith9a17a682011-11-07 05:07:52 +00001060 }
Richard Smith83587db2012-02-15 02:18:13 +00001061 if (Value.isUnion() && Value.getUnionField()) {
1062 return CheckConstantExpression(Info, DiagLoc,
1063 Value.getUnionField()->getType(),
1064 Value.getUnionValue());
1065 }
1066 if (Value.isStruct()) {
1067 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1068 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1069 unsigned BaseIndex = 0;
1070 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1071 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1072 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1073 Value.getStructBase(BaseIndex)))
1074 return false;
1075 }
1076 }
1077 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1078 I != E; ++I) {
1079 if (!CheckConstantExpression(Info, DiagLoc, (*I)->getType(),
1080 Value.getStructField((*I)->getFieldIndex())))
1081 return false;
1082 }
1083 }
1084
1085 if (Value.isLValue()) {
1086 CCValue Val(Info.Ctx, Value, CCValue::GlobalValue());
1087 LValue LVal;
1088 LVal.setFrom(Val);
1089 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1090 }
1091
1092 // Everything else is fine.
1093 return true;
Richard Smith47a1eed2011-10-29 20:57:55 +00001094}
1095
Richard Smith9e36b532011-10-31 05:11:32 +00001096const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001097 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001098}
1099
1100static bool IsLiteralLValue(const LValue &Value) {
Richard Smith83587db2012-02-15 02:18:13 +00001101 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith9e36b532011-10-31 05:11:32 +00001102}
1103
Richard Smith65ac5982011-11-01 21:06:14 +00001104static bool IsWeakLValue(const LValue &Value) {
1105 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001106 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001107}
1108
Richard Smithe24f5fc2011-11-17 22:56:20 +00001109static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001110 // A null base expression indicates a null pointer. These are always
1111 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001112 if (!Value.getLValueBase()) {
1113 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001114 return true;
1115 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001116
Richard Smithe24f5fc2011-11-17 22:56:20 +00001117 // We have a non-null base. These are generally known to be true, but if it's
1118 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001119 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001120 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001121 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001122}
1123
Richard Smith47a1eed2011-10-29 20:57:55 +00001124static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001125 switch (Val.getKind()) {
1126 case APValue::Uninitialized:
1127 return false;
1128 case APValue::Int:
1129 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001130 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001131 case APValue::Float:
1132 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001133 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001134 case APValue::ComplexInt:
1135 Result = Val.getComplexIntReal().getBoolValue() ||
1136 Val.getComplexIntImag().getBoolValue();
1137 return true;
1138 case APValue::ComplexFloat:
1139 Result = !Val.getComplexFloatReal().isZero() ||
1140 !Val.getComplexFloatImag().isZero();
1141 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001142 case APValue::LValue:
1143 return EvalPointerValueAsBool(Val, Result);
1144 case APValue::MemberPointer:
1145 Result = Val.getMemberPointerDecl();
1146 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001147 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001148 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001149 case APValue::Struct:
1150 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001151 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001152 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001153 }
1154
Richard Smithc49bd112011-10-28 17:51:58 +00001155 llvm_unreachable("unknown APValue kind");
1156}
1157
1158static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1159 EvalInfo &Info) {
1160 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith47a1eed2011-10-29 20:57:55 +00001161 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +00001162 if (!Evaluate(Val, Info, E))
1163 return false;
1164 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001165}
1166
Richard Smithc1c5f272011-12-13 06:39:58 +00001167template<typename T>
1168static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1169 const T &SrcValue, QualType DestType) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001170 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001171 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001172 return false;
1173}
1174
1175static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1176 QualType SrcType, const APFloat &Value,
1177 QualType DestType, APSInt &Result) {
1178 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001179 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001180 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Richard Smithc1c5f272011-12-13 06:39:58 +00001182 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001183 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001184 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1185 & APFloat::opInvalidOp)
1186 return HandleOverflow(Info, E, Value, DestType);
1187 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001188}
1189
Richard Smithc1c5f272011-12-13 06:39:58 +00001190static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1191 QualType SrcType, QualType DestType,
1192 APFloat &Result) {
1193 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001194 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001195 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1196 APFloat::rmNearestTiesToEven, &ignored)
1197 & APFloat::opOverflow)
1198 return HandleOverflow(Info, E, Value, DestType);
1199 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001200}
1201
Richard Smithf72fccf2012-01-30 22:27:01 +00001202static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1203 QualType DestType, QualType SrcType,
1204 APSInt &Value) {
1205 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001206 APSInt Result = Value;
1207 // Figure out if this is a truncate, extend or noop cast.
1208 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001209 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001210 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001211 return Result;
1212}
1213
Richard Smithc1c5f272011-12-13 06:39:58 +00001214static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1215 QualType SrcType, const APSInt &Value,
1216 QualType DestType, APFloat &Result) {
1217 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1218 if (Result.convertFromAPInt(Value, Value.isSigned(),
1219 APFloat::rmNearestTiesToEven)
1220 & APFloat::opOverflow)
1221 return HandleOverflow(Info, E, Value, DestType);
1222 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001223}
1224
Eli Friedmane6a24e82011-12-22 03:51:45 +00001225static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1226 llvm::APInt &Res) {
1227 CCValue SVal;
1228 if (!Evaluate(SVal, Info, E))
1229 return false;
1230 if (SVal.isInt()) {
1231 Res = SVal.getInt();
1232 return true;
1233 }
1234 if (SVal.isFloat()) {
1235 Res = SVal.getFloat().bitcastToAPInt();
1236 return true;
1237 }
1238 if (SVal.isVector()) {
1239 QualType VecTy = E->getType();
1240 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1241 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1242 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1243 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1244 Res = llvm::APInt::getNullValue(VecSize);
1245 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1246 APValue &Elt = SVal.getVectorElt(i);
1247 llvm::APInt EltAsInt;
1248 if (Elt.isInt()) {
1249 EltAsInt = Elt.getInt();
1250 } else if (Elt.isFloat()) {
1251 EltAsInt = Elt.getFloat().bitcastToAPInt();
1252 } else {
1253 // Don't try to handle vectors of anything other than int or float
1254 // (not sure if it's possible to hit this case).
1255 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1256 return false;
1257 }
1258 unsigned BaseEltSize = EltAsInt.getBitWidth();
1259 if (BigEndian)
1260 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1261 else
1262 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1263 }
1264 return true;
1265 }
1266 // Give up if the input isn't an int, float, or vector. For example, we
1267 // reject "(v4i16)(intptr_t)&a".
1268 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1269 return false;
1270}
1271
Richard Smithb4e85ed2012-01-06 16:39:00 +00001272/// Cast an lvalue referring to a base subobject to a derived class, by
1273/// truncating the lvalue's path to the given length.
1274static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1275 const RecordDecl *TruncatedType,
1276 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001277 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001278
1279 // Check we actually point to a derived class object.
1280 if (TruncatedElements == D.Entries.size())
1281 return true;
1282 assert(TruncatedElements >= D.MostDerivedPathLength &&
1283 "not casting to a derived class");
1284 if (!Result.checkSubobject(Info, E, CSK_Derived))
1285 return false;
1286
1287 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001288 const RecordDecl *RD = TruncatedType;
1289 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +00001290 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1291 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001292 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001293 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001294 else
Richard Smith180f4792011-11-10 06:34:14 +00001295 Result.Offset -= Layout.getBaseClassOffset(Base);
1296 RD = Base;
1297 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001298 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001299 return true;
1300}
1301
Richard Smithb4e85ed2012-01-06 16:39:00 +00001302static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001303 const CXXRecordDecl *Derived,
1304 const CXXRecordDecl *Base,
1305 const ASTRecordLayout *RL = 0) {
1306 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1307 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001308 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
Richard Smith180f4792011-11-10 06:34:14 +00001309}
1310
Richard Smithb4e85ed2012-01-06 16:39:00 +00001311static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001312 const CXXRecordDecl *DerivedDecl,
1313 const CXXBaseSpecifier *Base) {
1314 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1315
1316 if (!Base->isVirtual()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001317 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001318 return true;
1319 }
1320
Richard Smithb4e85ed2012-01-06 16:39:00 +00001321 SubobjectDesignator &D = Obj.Designator;
1322 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001323 return false;
1324
Richard Smithb4e85ed2012-01-06 16:39:00 +00001325 // Extract most-derived object and corresponding type.
1326 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1327 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1328 return false;
1329
1330 // Find the virtual base class.
Richard Smith180f4792011-11-10 06:34:14 +00001331 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1332 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001333 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001334 return true;
1335}
1336
1337/// Update LVal to refer to the given field, which must be a member of the type
1338/// currently described by LVal.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001339static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001340 const FieldDecl *FD,
1341 const ASTRecordLayout *RL = 0) {
1342 if (!RL)
1343 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1344
1345 unsigned I = FD->getFieldIndex();
1346 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001347 LVal.addDecl(Info, E, FD);
Richard Smith180f4792011-11-10 06:34:14 +00001348}
1349
Richard Smithd9b02e72012-01-25 22:15:11 +00001350/// Update LVal to refer to the given indirect field.
1351static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1352 LValue &LVal,
1353 const IndirectFieldDecl *IFD) {
1354 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1355 CE = IFD->chain_end(); C != CE; ++C)
1356 HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
1357}
1358
Richard Smith180f4792011-11-10 06:34:14 +00001359/// Get the size of the given type in char units.
1360static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1361 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1362 // extension.
1363 if (Type->isVoidType() || Type->isFunctionType()) {
1364 Size = CharUnits::One();
1365 return true;
1366 }
1367
1368 if (!Type->isConstantSizeType()) {
1369 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001370 // FIXME: Diagnostic.
Richard Smith180f4792011-11-10 06:34:14 +00001371 return false;
1372 }
1373
1374 Size = Info.Ctx.getTypeSizeInChars(Type);
1375 return true;
1376}
1377
1378/// Update a pointer value to model pointer arithmetic.
1379/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001380/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001381/// \param LVal - The pointer value to be updated.
1382/// \param EltTy - The pointee type represented by LVal.
1383/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001384static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1385 LValue &LVal, QualType EltTy,
1386 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001387 CharUnits SizeOfPointee;
1388 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1389 return false;
1390
1391 // Compute the new offset in the appropriate width.
1392 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001393 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001394 return true;
1395}
1396
Richard Smith03f96112011-10-24 17:54:18 +00001397/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001398static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1399 const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +00001400 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001401 // If this is a parameter to an active constexpr function call, perform
1402 // argument substitution.
1403 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001404 // Assume arguments of a potential constant expression are unknown
1405 // constant expressions.
1406 if (Info.CheckingPotentialConstantExpression)
1407 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001408 if (!Frame || !Frame->Arguments) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001409 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001410 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001411 }
Richard Smith177dce72011-11-01 16:57:24 +00001412 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1413 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001414 }
Richard Smith03f96112011-10-24 17:54:18 +00001415
Richard Smith099e7f62011-12-19 06:19:21 +00001416 // Dig out the initializer, and use the declaration which it's attached to.
1417 const Expr *Init = VD->getAnyInitializer(VD);
1418 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001419 // If we're checking a potential constant expression, the variable could be
1420 // initialized later.
1421 if (!Info.CheckingPotentialConstantExpression)
1422 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001423 return false;
1424 }
1425
Richard Smith180f4792011-11-10 06:34:14 +00001426 // If we're currently evaluating the initializer of this declaration, use that
1427 // in-flight value.
1428 if (Info.EvaluatingDecl == VD) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001429 Result = CCValue(Info.Ctx, *Info.EvaluatingDeclValue,
1430 CCValue::GlobalValue());
Richard Smith180f4792011-11-10 06:34:14 +00001431 return !Result.isUninit();
1432 }
1433
Richard Smith65ac5982011-11-01 21:06:14 +00001434 // Never evaluate the initializer of a weak variable. We can't be sure that
1435 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001436 if (VD->isWeak()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001437 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001438 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001439 }
Richard Smith65ac5982011-11-01 21:06:14 +00001440
Richard Smith099e7f62011-12-19 06:19:21 +00001441 // Check that we can fold the initializer. In C++, we will have already done
1442 // this in the cases where it matters for conformance.
1443 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1444 if (!VD->evaluateValue(Notes)) {
1445 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1446 Notes.size() + 1) << VD;
1447 Info.Note(VD->getLocation(), diag::note_declared_at);
1448 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001449 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001450 } else if (!VD->checkInitIsICE()) {
1451 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1452 Notes.size() + 1) << VD;
1453 Info.Note(VD->getLocation(), diag::note_declared_at);
1454 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001455 }
Richard Smith03f96112011-10-24 17:54:18 +00001456
Richard Smithb4e85ed2012-01-06 16:39:00 +00001457 Result = CCValue(Info.Ctx, *VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +00001458 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001459}
1460
Richard Smithc49bd112011-10-28 17:51:58 +00001461static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001462 Qualifiers Quals = T.getQualifiers();
1463 return Quals.hasConst() && !Quals.hasVolatile();
1464}
1465
Richard Smith59efe262011-11-11 04:05:33 +00001466/// Get the base index of the given base class within an APValue representing
1467/// the given derived class.
1468static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1469 const CXXRecordDecl *Base) {
1470 Base = Base->getCanonicalDecl();
1471 unsigned Index = 0;
1472 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1473 E = Derived->bases_end(); I != E; ++I, ++Index) {
1474 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1475 return Index;
1476 }
1477
1478 llvm_unreachable("base class missing from derived class's bases list");
1479}
1480
Richard Smithcc5d4f62011-11-07 09:22:26 +00001481/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001482static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1483 CCValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001484 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001485 if (Sub.Invalid)
1486 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001487 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001488 if (Sub.isOnePastTheEnd()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001489 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001490 (unsigned)diag::note_constexpr_read_past_end :
1491 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001492 return false;
1493 }
Richard Smithf64699e2011-11-11 08:28:03 +00001494 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001495 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001496 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1497 // This object might be initialized later.
1498 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001499
1500 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1501 const APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001502 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001503 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001504 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001505 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001506 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001507 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001508 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001509 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001510 // Note, it should not be possible to form a pointer with a valid
1511 // designator which points more than one past the end of the array.
1512 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001513 (unsigned)diag::note_constexpr_read_past_end :
1514 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001515 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001516 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001517 if (O->getArrayInitializedElts() > Index)
1518 O = &O->getArrayInitializedElt(Index);
1519 else
1520 O = &O->getArrayFiller();
1521 ObjType = CAT->getElementType();
Richard Smith180f4792011-11-10 06:34:14 +00001522 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithb4e5e282012-02-09 03:29:58 +00001523 if (Field->isMutable()) {
1524 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_mutable, 1)
1525 << Field;
1526 Info.Note(Field->getLocation(), diag::note_declared_at);
1527 return false;
1528 }
1529
Richard Smith180f4792011-11-10 06:34:14 +00001530 // Next subobject is a class, struct or union field.
1531 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1532 if (RD->isUnion()) {
1533 const FieldDecl *UnionField = O->getUnionField();
1534 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001535 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001536 Info.Diag(E->getExprLoc(),
1537 diag::note_constexpr_read_inactive_union_member)
1538 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001539 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001540 }
Richard Smith180f4792011-11-10 06:34:14 +00001541 O = &O->getUnionValue();
1542 } else
1543 O = &O->getStructField(Field->getFieldIndex());
1544 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001545
1546 if (ObjType.isVolatileQualified()) {
1547 if (Info.getLangOpts().CPlusPlus) {
1548 // FIXME: Include a description of the path to the volatile subobject.
1549 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1550 << 2 << Field;
1551 Info.Note(Field->getLocation(), diag::note_declared_at);
1552 } else {
1553 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1554 }
1555 return false;
1556 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001557 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001558 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001559 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1560 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1561 O = &O->getStructBase(getBaseIndex(Derived, Base));
1562 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001563 }
Richard Smith180f4792011-11-10 06:34:14 +00001564
Richard Smithf48fdb02011-12-09 22:58:01 +00001565 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001566 if (!Info.CheckingPotentialConstantExpression)
1567 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001568 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001569 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001570 }
1571
Richard Smithb4e85ed2012-01-06 16:39:00 +00001572 Obj = CCValue(Info.Ctx, *O, CCValue::GlobalValue());
Richard Smithcc5d4f62011-11-07 09:22:26 +00001573 return true;
1574}
1575
Richard Smithf15fda02012-02-02 01:16:57 +00001576/// Find the position where two subobject designators diverge, or equivalently
1577/// the length of the common initial subsequence.
1578static unsigned FindDesignatorMismatch(QualType ObjType,
1579 const SubobjectDesignator &A,
1580 const SubobjectDesignator &B,
1581 bool &WasArrayIndex) {
1582 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1583 for (/**/; I != N; ++I) {
1584 if (!ObjType.isNull() && ObjType->isArrayType()) {
1585 // Next subobject is an array element.
1586 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1587 WasArrayIndex = true;
1588 return I;
1589 }
1590 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
1591 } else {
1592 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1593 WasArrayIndex = false;
1594 return I;
1595 }
1596 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1597 // Next subobject is a field.
1598 ObjType = FD->getType();
1599 else
1600 // Next subobject is a base class.
1601 ObjType = QualType();
1602 }
1603 }
1604 WasArrayIndex = false;
1605 return I;
1606}
1607
1608/// Determine whether the given subobject designators refer to elements of the
1609/// same array object.
1610static bool AreElementsOfSameArray(QualType ObjType,
1611 const SubobjectDesignator &A,
1612 const SubobjectDesignator &B) {
1613 if (A.Entries.size() != B.Entries.size())
1614 return false;
1615
1616 bool IsArray = A.MostDerivedArraySize != 0;
1617 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1618 // A is a subobject of the array element.
1619 return false;
1620
1621 // If A (and B) designates an array element, the last entry will be the array
1622 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1623 // of length 1' case, and the entire path must match.
1624 bool WasArrayIndex;
1625 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1626 return CommonLength >= A.Entries.size() - IsArray;
1627}
1628
Richard Smith180f4792011-11-10 06:34:14 +00001629/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1630/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1631/// for looking up the glvalue referred to by an entity of reference type.
1632///
1633/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001634/// \param Conv - The expression for which we are performing the conversion.
1635/// Used for diagnostics.
Richard Smith9ec71972012-02-05 01:23:16 +00001636/// \param Type - The type we expect this conversion to produce, before
1637/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smith180f4792011-11-10 06:34:14 +00001638/// \param LVal - The glvalue on which we are attempting to perform this action.
1639/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001640static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1641 QualType Type,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001642 const LValue &LVal, CCValue &RVal) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001643 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1644 if (!Info.getLangOpts().CPlusPlus)
1645 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1646
Richard Smithb4e85ed2012-01-06 16:39:00 +00001647 if (LVal.Designator.Invalid)
1648 // A diagnostic will have already been produced.
1649 return false;
1650
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001651 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith7098cbd2011-12-21 05:04:46 +00001652 SourceLocation Loc = Conv->getExprLoc();
Richard Smithc49bd112011-10-28 17:51:58 +00001653
Richard Smithf48fdb02011-12-09 22:58:01 +00001654 if (!LVal.Base) {
1655 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith7098cbd2011-12-21 05:04:46 +00001656 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1657 return false;
1658 }
1659
Richard Smith83587db2012-02-15 02:18:13 +00001660 CallStackFrame *Frame = 0;
1661 if (LVal.CallIndex) {
1662 Frame = Info.getCallFrame(LVal.CallIndex);
1663 if (!Frame) {
1664 Info.Diag(Loc, diag::note_constexpr_lifetime_ended, 1) << !Base;
1665 NoteLValueLocation(Info, LVal.Base);
1666 return false;
1667 }
1668 }
1669
Richard Smith7098cbd2011-12-21 05:04:46 +00001670 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1671 // is not a constant expression (even if the object is non-volatile). We also
1672 // apply this rule to C++98, in order to conform to the expected 'volatile'
1673 // semantics.
1674 if (Type.isVolatileQualified()) {
1675 if (Info.getLangOpts().CPlusPlus)
1676 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1677 else
1678 Info.Diag(Loc);
Richard Smithc49bd112011-10-28 17:51:58 +00001679 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001680 }
Richard Smithc49bd112011-10-28 17:51:58 +00001681
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001682 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001683 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1684 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001685 // expressions are constant expressions too. Inside constexpr functions,
1686 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001687 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001688 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf15fda02012-02-02 01:16:57 +00001689 if (const VarDecl *VDef = VD->getDefinition())
1690 VD = VDef;
Richard Smithf48fdb02011-12-09 22:58:01 +00001691 if (!VD || VD->isInvalidDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001692 Info.Diag(Loc);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001693 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001694 }
1695
Richard Smith7098cbd2011-12-21 05:04:46 +00001696 // DR1313: If the object is volatile-qualified but the glvalue was not,
1697 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001698 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001699 if (VT.isVolatileQualified()) {
1700 if (Info.getLangOpts().CPlusPlus) {
1701 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1702 Info.Note(VD->getLocation(), diag::note_declared_at);
1703 } else {
1704 Info.Diag(Loc);
Richard Smithf48fdb02011-12-09 22:58:01 +00001705 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001706 return false;
1707 }
1708
1709 if (!isa<ParmVarDecl>(VD)) {
1710 if (VD->isConstexpr()) {
1711 // OK, we can read this variable.
1712 } else if (VT->isIntegralOrEnumerationType()) {
1713 if (!VT.isConstQualified()) {
1714 if (Info.getLangOpts().CPlusPlus) {
1715 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1716 Info.Note(VD->getLocation(), diag::note_declared_at);
1717 } else {
1718 Info.Diag(Loc);
1719 }
1720 return false;
1721 }
1722 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1723 // We support folding of const floating-point types, in order to make
1724 // static const data members of such types (supported as an extension)
1725 // more useful.
1726 if (Info.getLangOpts().CPlusPlus0x) {
1727 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1728 Info.Note(VD->getLocation(), diag::note_declared_at);
1729 } else {
1730 Info.CCEDiag(Loc);
1731 }
1732 } else {
1733 // FIXME: Allow folding of values of any literal type in all languages.
1734 if (Info.getLangOpts().CPlusPlus0x) {
1735 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1736 Info.Note(VD->getLocation(), diag::note_declared_at);
1737 } else {
1738 Info.Diag(Loc);
1739 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001740 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001741 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001742 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001743
Richard Smithf48fdb02011-12-09 22:58:01 +00001744 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001745 return false;
1746
Richard Smith47a1eed2011-10-29 20:57:55 +00001747 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001748 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001749
1750 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1751 // conversion. This happens when the declaration and the lvalue should be
1752 // considered synonymous, for instance when initializing an array of char
1753 // from a string literal. Continue as if the initializer lvalue was the
1754 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001755 assert(RVal.getLValueOffset().isZero() &&
1756 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001757 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith83587db2012-02-15 02:18:13 +00001758
1759 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1760 Frame = Info.getCallFrame(CallIndex);
1761 if (!Frame) {
1762 Info.Diag(Loc, diag::note_constexpr_lifetime_ended, 1) << !Base;
1763 NoteLValueLocation(Info, RVal.getLValueBase());
1764 return false;
1765 }
1766 } else {
1767 Frame = 0;
1768 }
Richard Smithc49bd112011-10-28 17:51:58 +00001769 }
1770
Richard Smith7098cbd2011-12-21 05:04:46 +00001771 // Volatile temporary objects cannot be read in constant expressions.
1772 if (Base->getType().isVolatileQualified()) {
1773 if (Info.getLangOpts().CPlusPlus) {
1774 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1775 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1776 } else {
1777 Info.Diag(Loc);
1778 }
1779 return false;
1780 }
1781
Richard Smith0a3bdb62011-11-04 02:25:55 +00001782 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1783 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1784 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf48fdb02011-12-09 22:58:01 +00001785 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001786 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001787 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001788 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001789
1790 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith9a17a682011-11-07 05:07:52 +00001791 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smith7098cbd2011-12-21 05:04:46 +00001792 const ConstantArrayType *CAT =
1793 Info.Ctx.getAsConstantArrayType(S->getType());
1794 if (Index >= CAT->getSize().getZExtValue()) {
1795 // Note, it should not be possible to form a pointer which points more
1796 // than one past the end of the array without producing a prior const expr
1797 // diagnostic.
1798 Info.Diag(Loc, diag::note_constexpr_read_past_end);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001799 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001800 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001801 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1802 Type->isUnsignedIntegerType());
1803 if (Index < S->getLength())
1804 Value = S->getCodeUnit(Index);
1805 RVal = CCValue(Value);
1806 return true;
1807 }
1808
Richard Smithcc5d4f62011-11-07 09:22:26 +00001809 if (Frame) {
1810 // If this is a temporary expression with a nontrivial initializer, grab the
1811 // value from the relevant stack frame.
1812 RVal = Frame->Temporaries[Base];
1813 } else if (const CompoundLiteralExpr *CLE
1814 = dyn_cast<CompoundLiteralExpr>(Base)) {
1815 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1816 // initializer until now for such expressions. Such an expression can't be
1817 // an ICE in C, so this only matters for fold.
1818 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1819 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1820 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001821 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001822 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001823 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001824 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001825
Richard Smithf48fdb02011-12-09 22:58:01 +00001826 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1827 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001828}
1829
Richard Smith59efe262011-11-11 04:05:33 +00001830/// Build an lvalue for the object argument of a member function call.
1831static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1832 LValue &This) {
1833 if (Object->getType()->isPointerType())
1834 return EvaluatePointer(Object, This, Info);
1835
1836 if (Object->isGLValue())
1837 return EvaluateLValue(Object, This, Info);
1838
Richard Smithe24f5fc2011-11-17 22:56:20 +00001839 if (Object->getType()->isLiteralType())
1840 return EvaluateTemporary(Object, This, Info);
1841
1842 return false;
1843}
1844
1845/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1846/// lvalue referring to the result.
1847///
1848/// \param Info - Information about the ongoing evaluation.
1849/// \param BO - The member pointer access operation.
1850/// \param LV - Filled in with a reference to the resulting object.
1851/// \param IncludeMember - Specifies whether the member itself is included in
1852/// the resulting LValue subobject designator. This is not possible when
1853/// creating a bound member function.
1854/// \return The field or method declaration to which the member pointer refers,
1855/// or 0 if evaluation fails.
1856static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1857 const BinaryOperator *BO,
1858 LValue &LV,
1859 bool IncludeMember = true) {
1860 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1861
Richard Smith745f5142012-01-27 01:14:48 +00001862 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1863 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001864 return 0;
1865
1866 MemberPtr MemPtr;
1867 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1868 return 0;
1869
1870 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1871 // member value, the behavior is undefined.
1872 if (!MemPtr.getDecl())
1873 return 0;
1874
Richard Smith745f5142012-01-27 01:14:48 +00001875 if (!EvalObjOK)
1876 return 0;
1877
Richard Smithe24f5fc2011-11-17 22:56:20 +00001878 if (MemPtr.isDerivedMember()) {
1879 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001880 // The end of the derived-to-base path for the base object must match the
1881 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001882 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001883 LV.Designator.Entries.size())
1884 return 0;
1885 unsigned PathLengthToMember =
1886 LV.Designator.Entries.size() - MemPtr.Path.size();
1887 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1888 const CXXRecordDecl *LVDecl = getAsBaseClass(
1889 LV.Designator.Entries[PathLengthToMember + I]);
1890 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1891 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1892 return 0;
1893 }
1894
1895 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001896 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1897 PathLengthToMember))
1898 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001899 } else if (!MemPtr.Path.empty()) {
1900 // Extend the LValue path with the member pointer's path.
1901 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1902 MemPtr.Path.size() + IncludeMember);
1903
1904 // Walk down to the appropriate base class.
1905 QualType LVType = BO->getLHS()->getType();
1906 if (const PointerType *PT = LVType->getAs<PointerType>())
1907 LVType = PT->getPointeeType();
1908 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1909 assert(RD && "member pointer access on non-class-type expression");
1910 // The first class in the path is that of the lvalue.
1911 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1912 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smithb4e85ed2012-01-06 16:39:00 +00001913 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001914 RD = Base;
1915 }
1916 // Finally cast to the class containing the member.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001917 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smithe24f5fc2011-11-17 22:56:20 +00001918 }
1919
1920 // Add the member. Note that we cannot build bound member functions here.
1921 if (IncludeMember) {
Richard Smithd9b02e72012-01-25 22:15:11 +00001922 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
1923 HandleLValueMember(Info, BO, LV, FD);
1924 else if (const IndirectFieldDecl *IFD =
1925 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
1926 HandleLValueIndirectMember(Info, BO, LV, IFD);
1927 else
1928 llvm_unreachable("can't construct reference to bound member function");
Richard Smithe24f5fc2011-11-17 22:56:20 +00001929 }
1930
1931 return MemPtr.getDecl();
1932}
1933
1934/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1935/// the provided lvalue, which currently refers to the base object.
1936static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1937 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001938 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001939 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001940 return false;
1941
Richard Smithb4e85ed2012-01-06 16:39:00 +00001942 QualType TargetQT = E->getType();
1943 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1944 TargetQT = PT->getPointeeType();
1945
1946 // Check this cast lands within the final derived-to-base subobject path.
1947 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
1948 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1949 << D.MostDerivedType << TargetQT;
1950 return false;
1951 }
1952
Richard Smithe24f5fc2011-11-17 22:56:20 +00001953 // Check the type of the final cast. We don't need to check the path,
1954 // since a cast can only be formed if the path is unique.
1955 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001956 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1957 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001958 if (NewEntriesSize == D.MostDerivedPathLength)
1959 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
1960 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00001961 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001962 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
1963 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1964 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001965 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001966 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001967
1968 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001969 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00001970}
1971
Mike Stumpc4c90452009-10-27 22:09:17 +00001972namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00001973enum EvalStmtResult {
1974 /// Evaluation failed.
1975 ESR_Failed,
1976 /// Hit a 'return' statement.
1977 ESR_Returned,
1978 /// Evaluation succeeded.
1979 ESR_Succeeded
1980};
1981}
1982
1983// Evaluate a statement.
Richard Smith83587db2012-02-15 02:18:13 +00001984static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00001985 const Stmt *S) {
1986 switch (S->getStmtClass()) {
1987 default:
1988 return ESR_Failed;
1989
1990 case Stmt::NullStmtClass:
1991 case Stmt::DeclStmtClass:
1992 return ESR_Succeeded;
1993
Richard Smithc1c5f272011-12-13 06:39:58 +00001994 case Stmt::ReturnStmtClass: {
Richard Smithc1c5f272011-12-13 06:39:58 +00001995 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith83587db2012-02-15 02:18:13 +00001996 if (!Evaluate(Result, Info, RetExpr))
Richard Smithc1c5f272011-12-13 06:39:58 +00001997 return ESR_Failed;
1998 return ESR_Returned;
1999 }
Richard Smithd0dccea2011-10-28 22:34:42 +00002000
2001 case Stmt::CompoundStmtClass: {
2002 const CompoundStmt *CS = cast<CompoundStmt>(S);
2003 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2004 BE = CS->body_end(); BI != BE; ++BI) {
2005 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2006 if (ESR != ESR_Succeeded)
2007 return ESR;
2008 }
2009 return ESR_Succeeded;
2010 }
2011 }
2012}
2013
Richard Smith61802452011-12-22 02:22:31 +00002014/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2015/// default constructor. If so, we'll fold it whether or not it's marked as
2016/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2017/// so we need special handling.
2018static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00002019 const CXXConstructorDecl *CD,
2020 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002021 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2022 return false;
2023
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002024 // Value-initialization does not call a trivial default constructor, so such a
2025 // call is a core constant expression whether or not the constructor is
2026 // constexpr.
2027 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002028 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002029 // FIXME: If DiagDecl is an implicitly-declared special member function,
2030 // we should be much more explicit about why it's not constexpr.
2031 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2032 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2033 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00002034 } else {
2035 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2036 }
2037 }
2038 return true;
2039}
2040
Richard Smithc1c5f272011-12-13 06:39:58 +00002041/// CheckConstexprFunction - Check that a function can be called in a constant
2042/// expression.
2043static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2044 const FunctionDecl *Declaration,
2045 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00002046 // Potential constant expressions can contain calls to declared, but not yet
2047 // defined, constexpr functions.
2048 if (Info.CheckingPotentialConstantExpression && !Definition &&
2049 Declaration->isConstexpr())
2050 return false;
2051
Richard Smithc1c5f272011-12-13 06:39:58 +00002052 // Can we evaluate this function call?
2053 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2054 return true;
2055
2056 if (Info.getLangOpts().CPlusPlus0x) {
2057 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00002058 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2059 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00002060 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2061 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2062 << DiagDecl;
2063 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2064 } else {
2065 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2066 }
2067 return false;
2068}
2069
Richard Smith180f4792011-11-10 06:34:14 +00002070namespace {
Richard Smithcd99b072011-11-11 05:48:57 +00002071typedef SmallVector<CCValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00002072}
2073
2074/// EvaluateArgs - Evaluate the arguments to a function call.
2075static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2076 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00002077 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002078 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00002079 I != E; ++I) {
2080 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2081 // If we're checking for a potential constant expression, evaluate all
2082 // initializers even if some of them fail.
2083 if (!Info.keepEvaluatingAfterFailure())
2084 return false;
2085 Success = false;
2086 }
2087 }
2088 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002089}
2090
Richard Smithd0dccea2011-10-28 22:34:42 +00002091/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002092static bool HandleFunctionCall(SourceLocation CallLoc,
2093 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002094 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith83587db2012-02-15 02:18:13 +00002095 EvalInfo &Info, CCValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002096 ArgVector ArgValues(Args.size());
2097 if (!EvaluateArgs(Args, ArgValues, Info))
2098 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00002099
Richard Smith745f5142012-01-27 01:14:48 +00002100 if (!Info.CheckCallLimit(CallLoc))
2101 return false;
2102
2103 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002104 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2105}
2106
Richard Smith180f4792011-11-10 06:34:14 +00002107/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002108static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002109 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002110 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002111 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002112 ArgVector ArgValues(Args.size());
2113 if (!EvaluateArgs(Args, ArgValues, Info))
2114 return false;
2115
Richard Smith745f5142012-01-27 01:14:48 +00002116 if (!Info.CheckCallLimit(CallLoc))
2117 return false;
2118
Richard Smith86c3ae42012-02-13 03:54:03 +00002119 const CXXRecordDecl *RD = Definition->getParent();
2120 if (RD->getNumVBases()) {
2121 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2122 return false;
2123 }
2124
Richard Smith745f5142012-01-27 01:14:48 +00002125 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002126
2127 // If it's a delegating constructor, just delegate.
2128 if (Definition->isDelegatingConstructor()) {
2129 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith83587db2012-02-15 02:18:13 +00002130 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
Richard Smith180f4792011-11-10 06:34:14 +00002131 }
2132
Richard Smith610a60c2012-01-10 04:32:03 +00002133 // For a trivial copy or move constructor, perform an APValue copy. This is
2134 // essential for unions, where the operations performed by the constructor
2135 // cannot be represented by ctor-initializers.
Richard Smith610a60c2012-01-10 04:32:03 +00002136 if (Definition->isDefaulted() &&
2137 ((Definition->isCopyConstructor() && RD->hasTrivialCopyConstructor()) ||
2138 (Definition->isMoveConstructor() && RD->hasTrivialMoveConstructor()))) {
2139 LValue RHS;
2140 RHS.setFrom(ArgValues[0]);
2141 CCValue Value;
Richard Smith745f5142012-01-27 01:14:48 +00002142 if (!HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2143 RHS, Value))
2144 return false;
2145 assert((Value.isStruct() || Value.isUnion()) &&
2146 "trivial copy/move from non-class type?");
2147 // Any CCValue of class type must already be a constant expression.
2148 Result = Value;
2149 return true;
Richard Smith610a60c2012-01-10 04:32:03 +00002150 }
2151
2152 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002153 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002154 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2155 std::distance(RD->field_begin(), RD->field_end()));
2156
2157 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2158
Richard Smith745f5142012-01-27 01:14:48 +00002159 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002160 unsigned BasesSeen = 0;
2161#ifndef NDEBUG
2162 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2163#endif
2164 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2165 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002166 LValue Subobject = This;
2167 APValue *Value = &Result;
2168
2169 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002170 if ((*I)->isBaseInitializer()) {
2171 QualType BaseType((*I)->getBaseClass(), 0);
2172#ifndef NDEBUG
2173 // Non-virtual base classes are initialized in the order in the class
Richard Smith86c3ae42012-02-13 03:54:03 +00002174 // definition. We have already checked for virtual base classes.
Richard Smith180f4792011-11-10 06:34:14 +00002175 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2176 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2177 "base class initializers not in expected order");
2178 ++BaseIt;
2179#endif
Richard Smithb4e85ed2012-01-06 16:39:00 +00002180 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smith180f4792011-11-10 06:34:14 +00002181 BaseType->getAsCXXRecordDecl(), &Layout);
Richard Smith745f5142012-01-27 01:14:48 +00002182 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002183 } else if (FieldDecl *FD = (*I)->getMember()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002184 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00002185 if (RD->isUnion()) {
2186 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002187 Value = &Result.getUnionValue();
2188 } else {
2189 Value = &Result.getStructField(FD->getFieldIndex());
2190 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002191 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002192 // Walk the indirect field decl's chain to find the object to initialize,
2193 // and make sure we've initialized every step along it.
2194 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2195 CE = IFD->chain_end();
2196 C != CE; ++C) {
2197 FieldDecl *FD = cast<FieldDecl>(*C);
2198 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2199 // Switch the union field if it differs. This happens if we had
2200 // preceding zero-initialization, and we're now initializing a union
2201 // subobject other than the first.
2202 // FIXME: In this case, the values of the other subobjects are
2203 // specified, since zero-initialization sets all padding bits to zero.
2204 if (Value->isUninit() ||
2205 (Value->isUnion() && Value->getUnionField() != FD)) {
2206 if (CD->isUnion())
2207 *Value = APValue(FD);
2208 else
2209 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2210 std::distance(CD->field_begin(), CD->field_end()));
2211 }
Richard Smith745f5142012-01-27 01:14:48 +00002212 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
Richard Smithd9b02e72012-01-25 22:15:11 +00002213 if (CD->isUnion())
2214 Value = &Value->getUnionValue();
2215 else
2216 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002217 }
Richard Smith180f4792011-11-10 06:34:14 +00002218 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002219 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002220 }
Richard Smith745f5142012-01-27 01:14:48 +00002221
Richard Smith83587db2012-02-15 02:18:13 +00002222 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2223 (*I)->isBaseInitializer()
Richard Smith745f5142012-01-27 01:14:48 +00002224 ? CCEK_Constant : CCEK_MemberInit)) {
2225 // If we're checking for a potential constant expression, evaluate all
2226 // initializers even if some of them fail.
2227 if (!Info.keepEvaluatingAfterFailure())
2228 return false;
2229 Success = false;
2230 }
Richard Smith180f4792011-11-10 06:34:14 +00002231 }
2232
Richard Smith745f5142012-01-27 01:14:48 +00002233 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002234}
2235
Richard Smithd0dccea2011-10-28 22:34:42 +00002236namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002237class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002238 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002239 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002240public:
2241
Richard Smith1e12c592011-10-16 21:26:27 +00002242 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002243
2244 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002245 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002246 return true;
2247 }
2248
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002249 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2250 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002251 return Visit(E->getResultExpr());
2252 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002253 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002254 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002255 return true;
2256 return false;
2257 }
John McCallf85e1932011-06-15 23:02:42 +00002258 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002259 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002260 return true;
2261 return false;
2262 }
2263 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002264 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002265 return true;
2266 return false;
2267 }
2268
Mike Stumpc4c90452009-10-27 22:09:17 +00002269 // We don't want to evaluate BlockExprs multiple times, as they generate
2270 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002271 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2272 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2273 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002274 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002275 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2276 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2277 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2278 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2279 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2280 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002281 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002282 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002283 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002284 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002285 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002286 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2287 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2288 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2289 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002290 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002291 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2292 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2293 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2294 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2295 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002296 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002297 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002298 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002299 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002300 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002301
2302 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002303 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002304 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2305 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002306 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002307 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002308 return false;
2309 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002310
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002311 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002312};
2313
John McCall56ca35d2011-02-17 10:25:35 +00002314class OpaqueValueEvaluation {
2315 EvalInfo &info;
2316 OpaqueValueExpr *opaqueValue;
2317
2318public:
2319 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2320 Expr *value)
2321 : info(info), opaqueValue(opaqueValue) {
2322
2323 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002324 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002325 this->opaqueValue = 0;
2326 return;
2327 }
John McCall56ca35d2011-02-17 10:25:35 +00002328 }
2329
2330 bool hasError() const { return opaqueValue == 0; }
2331
2332 ~OpaqueValueEvaluation() {
Richard Smith1e12c592011-10-16 21:26:27 +00002333 // FIXME: This will not work for recursive constexpr functions using opaque
2334 // values. Restore the former value.
John McCall56ca35d2011-02-17 10:25:35 +00002335 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2336 }
2337};
2338
Mike Stumpc4c90452009-10-27 22:09:17 +00002339} // end anonymous namespace
2340
Eli Friedman4efaa272008-11-12 09:44:48 +00002341//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002342// Generic Evaluation
2343//===----------------------------------------------------------------------===//
2344namespace {
2345
Richard Smithf48fdb02011-12-09 22:58:01 +00002346// FIXME: RetTy is always bool. Remove it.
2347template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002348class ExprEvaluatorBase
2349 : public ConstStmtVisitor<Derived, RetTy> {
2350private:
Richard Smith47a1eed2011-10-29 20:57:55 +00002351 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002352 return static_cast<Derived*>(this)->Success(V, E);
2353 }
Richard Smith51201882011-12-30 21:15:51 +00002354 RetTy DerivedZeroInitialization(const Expr *E) {
2355 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002356 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002357
2358protected:
2359 EvalInfo &Info;
2360 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2361 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2362
Richard Smithdd1f29b2011-12-12 09:28:41 +00002363 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd5093422011-12-12 09:41:58 +00002364 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002365 }
2366
2367 /// Report an evaluation error. This should only be called when an error is
2368 /// first discovered. When propagating an error, just return false.
2369 bool Error(const Expr *E, diag::kind D) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00002370 Info.Diag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002371 return false;
2372 }
2373 bool Error(const Expr *E) {
2374 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2375 }
2376
Richard Smith51201882011-12-30 21:15:51 +00002377 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00002378
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002379public:
2380 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2381
2382 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002383 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002384 }
2385 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002386 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002387 }
2388
2389 RetTy VisitParenExpr(const ParenExpr *E)
2390 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2391 RetTy VisitUnaryExtension(const UnaryOperator *E)
2392 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2393 RetTy VisitUnaryPlus(const UnaryOperator *E)
2394 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2395 RetTy VisitChooseExpr(const ChooseExpr *E)
2396 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2397 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2398 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002399 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2400 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002401 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2402 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002403 // We cannot create any objects for which cleanups are required, so there is
2404 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2405 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2406 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002407
Richard Smithc216a012011-12-12 12:46:16 +00002408 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2409 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2410 return static_cast<Derived*>(this)->VisitCastExpr(E);
2411 }
2412 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2413 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2414 return static_cast<Derived*>(this)->VisitCastExpr(E);
2415 }
2416
Richard Smithe24f5fc2011-11-17 22:56:20 +00002417 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2418 switch (E->getOpcode()) {
2419 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002420 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002421
2422 case BO_Comma:
2423 VisitIgnoredValue(E->getLHS());
2424 return StmtVisitorTy::Visit(E->getRHS());
2425
2426 case BO_PtrMemD:
2427 case BO_PtrMemI: {
2428 LValue Obj;
2429 if (!HandleMemberPointerAccess(Info, E, Obj))
2430 return false;
2431 CCValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002432 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002433 return false;
2434 return DerivedSuccess(Result, E);
2435 }
2436 }
2437 }
2438
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002439 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2440 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2441 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002442 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002443
2444 bool cond;
Richard Smithc49bd112011-10-28 17:51:58 +00002445 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002446 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002447
2448 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
2449 }
2450
2451 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002452 bool IsBcpCall = false;
2453 // If the condition (ignoring parens) is a __builtin_constant_p call,
2454 // the result is a constant expression if it can be folded without
2455 // side-effects. This is an important GNU extension. See GCC PR38377
2456 // for discussion.
2457 if (const CallExpr *CallCE =
2458 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2459 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2460 IsBcpCall = true;
2461
2462 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2463 // constant expression; we can't check whether it's potentially foldable.
2464 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2465 return false;
2466
2467 FoldConstant Fold(Info);
2468
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002469 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00002470 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002471 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002472
Richard Smithc49bd112011-10-28 17:51:58 +00002473 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Richard Smithf15fda02012-02-02 01:16:57 +00002474 if (!StmtVisitorTy::Visit(EvalExpr))
2475 return false;
2476
2477 if (IsBcpCall)
2478 Fold.Fold(Info);
2479
2480 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002481 }
2482
2483 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002484 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002485 if (!Value) {
2486 const Expr *Source = E->getSourceExpr();
2487 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002488 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002489 if (Source == E) { // sanity checking.
2490 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002491 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002492 }
2493 return StmtVisitorTy::Visit(Source);
2494 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002495 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002496 }
Richard Smithf10d9172011-10-11 21:43:33 +00002497
Richard Smithd0dccea2011-10-28 22:34:42 +00002498 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002499 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002500 QualType CalleeType = Callee->getType();
2501
Richard Smithd0dccea2011-10-28 22:34:42 +00002502 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002503 LValue *This = 0, ThisVal;
2504 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith86c3ae42012-02-13 03:54:03 +00002505 bool HasQualifier = false;
Richard Smith6c957872011-11-10 09:31:24 +00002506
Richard Smith59efe262011-11-11 04:05:33 +00002507 // Extract function decl and 'this' pointer from the callee.
2508 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002509 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002510 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2511 // Explicit bound member calls, such as x.f() or p->g();
2512 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002513 return false;
2514 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002515 This = &ThisVal;
Richard Smith86c3ae42012-02-13 03:54:03 +00002516 HasQualifier = ME->hasQualifier();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002517 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2518 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002519 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2520 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002521 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002522 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002523 return Error(Callee);
2524
2525 FD = dyn_cast<FunctionDecl>(Member);
2526 if (!FD)
2527 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002528 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002529 LValue Call;
2530 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002531 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002532
Richard Smithb4e85ed2012-01-06 16:39:00 +00002533 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002534 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002535 FD = dyn_cast_or_null<FunctionDecl>(
2536 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002537 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002538 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002539
2540 // Overloaded operator calls to member functions are represented as normal
2541 // calls with '*this' as the first argument.
2542 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2543 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002544 // FIXME: When selecting an implicit conversion for an overloaded
2545 // operator delete, we sometimes try to evaluate calls to conversion
2546 // operators without a 'this' parameter!
2547 if (Args.empty())
2548 return Error(E);
2549
Richard Smith59efe262011-11-11 04:05:33 +00002550 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2551 return false;
2552 This = &ThisVal;
2553 Args = Args.slice(1);
2554 }
2555
2556 // Don't call function pointers which have been cast to some other type.
2557 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002558 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002559 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002560 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002561
Richard Smithb04035a2012-02-01 02:39:43 +00002562 if (This && !This->checkSubobject(Info, E, CSK_This))
2563 return false;
2564
Richard Smith86c3ae42012-02-13 03:54:03 +00002565 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2566 // calls to such functions in constant expressions.
2567 if (This && !HasQualifier &&
2568 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2569 return Error(E, diag::note_constexpr_virtual_call);
2570
Richard Smithc1c5f272011-12-13 06:39:58 +00002571 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002572 Stmt *Body = FD->getBody(Definition);
Richard Smith83587db2012-02-15 02:18:13 +00002573 CCValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002574
Richard Smithc1c5f272011-12-13 06:39:58 +00002575 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002576 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2577 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002578 return false;
2579
Richard Smith83587db2012-02-15 02:18:13 +00002580 return DerivedSuccess(Result, E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002581 }
2582
Richard Smithc49bd112011-10-28 17:51:58 +00002583 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2584 return StmtVisitorTy::Visit(E->getInitializer());
2585 }
Richard Smithf10d9172011-10-11 21:43:33 +00002586 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002587 if (E->getNumInits() == 0)
2588 return DerivedZeroInitialization(E);
2589 if (E->getNumInits() == 1)
2590 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002591 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002592 }
2593 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002594 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002595 }
2596 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002597 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002598 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002599 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002600 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002601 }
Richard Smithf10d9172011-10-11 21:43:33 +00002602
Richard Smith180f4792011-11-10 06:34:14 +00002603 /// A member expression where the object is a prvalue is itself a prvalue.
2604 RetTy VisitMemberExpr(const MemberExpr *E) {
2605 assert(!E->isArrow() && "missing call to bound member function?");
2606
2607 CCValue Val;
2608 if (!Evaluate(Val, Info, E->getBase()))
2609 return false;
2610
2611 QualType BaseTy = E->getBase()->getType();
2612
2613 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002614 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002615 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2616 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2617 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2618
Richard Smithb4e85ed2012-01-06 16:39:00 +00002619 SubobjectDesignator Designator(BaseTy);
2620 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002621
Richard Smithf48fdb02011-12-09 22:58:01 +00002622 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002623 DerivedSuccess(Val, E);
2624 }
2625
Richard Smithc49bd112011-10-28 17:51:58 +00002626 RetTy VisitCastExpr(const CastExpr *E) {
2627 switch (E->getCastKind()) {
2628 default:
2629 break;
2630
David Chisnall7a7ee302012-01-16 17:27:18 +00002631 case CK_AtomicToNonAtomic:
2632 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002633 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002634 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002635 return StmtVisitorTy::Visit(E->getSubExpr());
2636
2637 case CK_LValueToRValue: {
2638 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002639 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2640 return false;
2641 CCValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00002642 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2643 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2644 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002645 return false;
2646 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002647 }
2648 }
2649
Richard Smithf48fdb02011-12-09 22:58:01 +00002650 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002651 }
2652
Richard Smith8327fad2011-10-24 18:44:57 +00002653 /// Visit a value which is evaluated, but whose value is ignored.
2654 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002655 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002656 if (!Evaluate(Scratch, Info, E))
2657 Info.EvalStatus.HasSideEffects = true;
2658 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002659};
2660
2661}
2662
2663//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002664// Common base class for lvalue and temporary evaluation.
2665//===----------------------------------------------------------------------===//
2666namespace {
2667template<class Derived>
2668class LValueExprEvaluatorBase
2669 : public ExprEvaluatorBase<Derived, bool> {
2670protected:
2671 LValue &Result;
2672 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2673 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2674
2675 bool Success(APValue::LValueBase B) {
2676 Result.set(B);
2677 return true;
2678 }
2679
2680public:
2681 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2682 ExprEvaluatorBaseTy(Info), Result(Result) {}
2683
2684 bool Success(const CCValue &V, const Expr *E) {
2685 Result.setFrom(V);
2686 return true;
2687 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002688
Richard Smithe24f5fc2011-11-17 22:56:20 +00002689 bool VisitMemberExpr(const MemberExpr *E) {
2690 // Handle non-static data members.
2691 QualType BaseTy;
2692 if (E->isArrow()) {
2693 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2694 return false;
2695 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002696 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002697 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002698 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2699 return false;
2700 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002701 } else {
2702 if (!this->Visit(E->getBase()))
2703 return false;
2704 BaseTy = E->getBase()->getType();
2705 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002706
Richard Smithd9b02e72012-01-25 22:15:11 +00002707 const ValueDecl *MD = E->getMemberDecl();
2708 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2709 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2710 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2711 (void)BaseTy;
2712 HandleLValueMember(this->Info, E, Result, FD);
2713 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2714 HandleLValueIndirectMember(this->Info, E, Result, IFD);
2715 } else
2716 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002717
Richard Smithd9b02e72012-01-25 22:15:11 +00002718 if (MD->getType()->isReferenceType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002719 CCValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002720 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002721 RefValue))
2722 return false;
2723 return Success(RefValue, E);
2724 }
2725 return true;
2726 }
2727
2728 bool VisitBinaryOperator(const BinaryOperator *E) {
2729 switch (E->getOpcode()) {
2730 default:
2731 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2732
2733 case BO_PtrMemD:
2734 case BO_PtrMemI:
2735 return HandleMemberPointerAccess(this->Info, E, Result);
2736 }
2737 }
2738
2739 bool VisitCastExpr(const CastExpr *E) {
2740 switch (E->getCastKind()) {
2741 default:
2742 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2743
2744 case CK_DerivedToBase:
2745 case CK_UncheckedDerivedToBase: {
2746 if (!this->Visit(E->getSubExpr()))
2747 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002748
2749 // Now figure out the necessary offset to add to the base LV to get from
2750 // the derived class to the base class.
2751 QualType Type = E->getSubExpr()->getType();
2752
2753 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2754 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002755 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002756 *PathI))
2757 return false;
2758 Type = (*PathI)->getType();
2759 }
2760
2761 return true;
2762 }
2763 }
2764 }
2765};
2766}
2767
2768//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002769// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002770//
2771// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2772// function designators (in C), decl references to void objects (in C), and
2773// temporaries (if building with -Wno-address-of-temporary).
2774//
2775// LValue evaluation produces values comprising a base expression of one of the
2776// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002777// - Declarations
2778// * VarDecl
2779// * FunctionDecl
2780// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002781// * CompoundLiteralExpr in C
2782// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002783// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002784// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002785// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002786// * ObjCEncodeExpr
2787// * AddrLabelExpr
2788// * BlockExpr
2789// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002790// - Locals and temporaries
Richard Smith83587db2012-02-15 02:18:13 +00002791// * Any Expr, with a CallIndex indicating the function in which the temporary
2792// was evaluated.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002793// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002794//===----------------------------------------------------------------------===//
2795namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002796class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002797 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002798public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002799 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2800 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002801
Richard Smithc49bd112011-10-28 17:51:58 +00002802 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2803
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002804 bool VisitDeclRefExpr(const DeclRefExpr *E);
2805 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002806 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002807 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2808 bool VisitMemberExpr(const MemberExpr *E);
2809 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2810 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002811 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002812 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2813 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002814
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002815 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002816 switch (E->getCastKind()) {
2817 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002818 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002819
Eli Friedmandb924222011-10-11 00:13:24 +00002820 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002821 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002822 if (!Visit(E->getSubExpr()))
2823 return false;
2824 Result.Designator.setInvalid();
2825 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002826
Richard Smithe24f5fc2011-11-17 22:56:20 +00002827 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002828 if (!Visit(E->getSubExpr()))
2829 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002830 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002831 }
2832 }
Sebastian Redlcea8d962011-09-24 17:48:14 +00002833
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002834 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002835
Eli Friedman4efaa272008-11-12 09:44:48 +00002836};
2837} // end anonymous namespace
2838
Richard Smithc49bd112011-10-28 17:51:58 +00002839/// Evaluate an expression as an lvalue. This can be legitimately called on
2840/// expressions which are not glvalues, in a few cases:
2841/// * function designators in C,
2842/// * "extern void" objects,
2843/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002844static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002845 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2846 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2847 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002848 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002849}
2850
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002851bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002852 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2853 return Success(FD);
2854 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002855 return VisitVarDecl(E, VD);
2856 return Error(E);
2857}
Richard Smith436c8892011-10-24 23:14:33 +00002858
Richard Smithc49bd112011-10-28 17:51:58 +00002859bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002860 if (!VD->getType()->isReferenceType()) {
2861 if (isa<ParmVarDecl>(VD)) {
Richard Smith83587db2012-02-15 02:18:13 +00002862 Result.set(VD, Info.CurrentCall->Index);
Richard Smith177dce72011-11-01 16:57:24 +00002863 return true;
2864 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002865 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002866 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002867
Richard Smith47a1eed2011-10-29 20:57:55 +00002868 CCValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002869 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2870 return false;
2871 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002872}
2873
Richard Smithbd552ef2011-10-31 05:52:43 +00002874bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2875 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002876 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002877 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002878 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2879
Richard Smith83587db2012-02-15 02:18:13 +00002880 Result.set(E, Info.CurrentCall->Index);
2881 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2882 Result, E->GetTemporaryExpr());
Richard Smithe24f5fc2011-11-17 22:56:20 +00002883 }
2884
2885 // Materialization of an lvalue temporary occurs when we need to force a copy
2886 // (for instance, if it's a bitfield).
2887 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2888 if (!Visit(E->GetTemporaryExpr()))
2889 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002890 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002891 Info.CurrentCall->Temporaries[E]))
2892 return false;
Richard Smith83587db2012-02-15 02:18:13 +00002893 Result.set(E, Info.CurrentCall->Index);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002894 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002895}
2896
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002897bool
2898LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002899 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2900 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2901 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002902 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002903}
2904
Richard Smith47d21452011-12-27 12:18:28 +00002905bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2906 if (E->isTypeOperand())
2907 return Success(E);
2908 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2909 if (RD && RD->isPolymorphic()) {
2910 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2911 << E->getExprOperand()->getType()
2912 << E->getExprOperand()->getSourceRange();
2913 return false;
2914 }
2915 return Success(E);
2916}
2917
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002918bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002919 // Handle static data members.
2920 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2921 VisitIgnoredValue(E->getBase());
2922 return VisitVarDecl(E, VD);
2923 }
2924
Richard Smithd0dccea2011-10-28 22:34:42 +00002925 // Handle static member functions.
2926 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2927 if (MD->isStatic()) {
2928 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002929 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002930 }
2931 }
2932
Richard Smith180f4792011-11-10 06:34:14 +00002933 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002934 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002935}
2936
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002937bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002938 // FIXME: Deal with vectors as array subscript bases.
2939 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002940 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002941
Anders Carlsson3068d112008-11-16 19:01:22 +00002942 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002943 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002944
Anders Carlsson3068d112008-11-16 19:01:22 +00002945 APSInt Index;
2946 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002947 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002948 int64_t IndexValue
2949 = Index.isSigned() ? Index.getSExtValue()
2950 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00002951
Richard Smithb4e85ed2012-01-06 16:39:00 +00002952 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00002953}
Eli Friedman4efaa272008-11-12 09:44:48 +00002954
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002955bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002956 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00002957}
2958
Eli Friedman4efaa272008-11-12 09:44:48 +00002959//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002960// Pointer Evaluation
2961//===----------------------------------------------------------------------===//
2962
Anders Carlssonc754aa62008-07-08 05:13:58 +00002963namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002964class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002965 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00002966 LValue &Result;
2967
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002968 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002969 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00002970 return true;
2971 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002972public:
Mike Stump1eb44332009-09-09 15:08:12 +00002973
John McCallefdb83e2010-05-07 21:00:08 +00002974 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002975 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002976
Richard Smith47a1eed2011-10-29 20:57:55 +00002977 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002978 Result.setFrom(V);
2979 return true;
2980 }
Richard Smith51201882011-12-30 21:15:51 +00002981 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00002982 return Success((Expr*)0);
2983 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002984
John McCallefdb83e2010-05-07 21:00:08 +00002985 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002986 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00002987 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002988 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00002989 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002990 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00002991 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002992 bool VisitCallExpr(const CallExpr *E);
2993 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00002994 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00002995 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00002996 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00002997 }
Richard Smith180f4792011-11-10 06:34:14 +00002998 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2999 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00003000 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003001 Result = *Info.CurrentCall->This;
3002 return true;
3003 }
John McCall56ca35d2011-02-17 10:25:35 +00003004
Eli Friedmanba98d6b2009-03-23 04:56:01 +00003005 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00003006};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003007} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003008
John McCallefdb83e2010-05-07 21:00:08 +00003009static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003010 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003011 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003012}
3013
John McCallefdb83e2010-05-07 21:00:08 +00003014bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003015 if (E->getOpcode() != BO_Add &&
3016 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00003017 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003018
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003019 const Expr *PExp = E->getLHS();
3020 const Expr *IExp = E->getRHS();
3021 if (IExp->getType()->isPointerType())
3022 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003023
Richard Smith745f5142012-01-27 01:14:48 +00003024 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3025 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00003026 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003027
John McCallefdb83e2010-05-07 21:00:08 +00003028 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00003029 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00003030 return false;
3031 int64_t AdditionalOffset
3032 = Offset.isSigned() ? Offset.getSExtValue()
3033 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00003034 if (E->getOpcode() == BO_Sub)
3035 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003036
Richard Smith180f4792011-11-10 06:34:14 +00003037 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00003038 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3039 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003040}
Eli Friedman4efaa272008-11-12 09:44:48 +00003041
John McCallefdb83e2010-05-07 21:00:08 +00003042bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3043 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003044}
Mike Stump1eb44332009-09-09 15:08:12 +00003045
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003046bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3047 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003048
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003049 switch (E->getCastKind()) {
3050 default:
3051 break;
3052
John McCall2de56d12010-08-25 11:45:40 +00003053 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003054 case CK_CPointerToObjCPointerCast:
3055 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00003056 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00003057 if (!Visit(SubExpr))
3058 return false;
Richard Smithc216a012011-12-12 12:46:16 +00003059 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3060 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3061 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003062 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00003063 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003064 if (SubExpr->getType()->isVoidPointerType())
3065 CCEDiag(E, diag::note_constexpr_invalid_cast)
3066 << 3 << SubExpr->getType();
3067 else
3068 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3069 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003070 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003071
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003072 case CK_DerivedToBase:
3073 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00003074 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003075 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003076 if (!Result.Base && Result.Offset.isZero())
3077 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003078
Richard Smith180f4792011-11-10 06:34:14 +00003079 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003080 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00003081 QualType Type =
3082 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003083
Richard Smith180f4792011-11-10 06:34:14 +00003084 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003085 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003086 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3087 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003088 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003089 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003090 }
3091
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003092 return true;
3093 }
3094
Richard Smithe24f5fc2011-11-17 22:56:20 +00003095 case CK_BaseToDerived:
3096 if (!Visit(E->getSubExpr()))
3097 return false;
3098 if (!Result.Base && Result.Offset.isZero())
3099 return true;
3100 return HandleBaseToDerivedCast(Info, E, Result);
3101
Richard Smith47a1eed2011-10-29 20:57:55 +00003102 case CK_NullToPointer:
Richard Smith51201882011-12-30 21:15:51 +00003103 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00003104
John McCall2de56d12010-08-25 11:45:40 +00003105 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003106 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3107
Richard Smith47a1eed2011-10-29 20:57:55 +00003108 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003109 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003110 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003111
John McCallefdb83e2010-05-07 21:00:08 +00003112 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003113 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3114 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003115 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003116 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith83587db2012-02-15 02:18:13 +00003117 Result.CallIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003118 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003119 return true;
3120 } else {
3121 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00003122 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00003123 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003124 }
3125 }
John McCall2de56d12010-08-25 11:45:40 +00003126 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003127 if (SubExpr->isGLValue()) {
3128 if (!EvaluateLValue(SubExpr, Result, Info))
3129 return false;
3130 } else {
Richard Smith83587db2012-02-15 02:18:13 +00003131 Result.set(SubExpr, Info.CurrentCall->Index);
3132 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3133 Info, Result, SubExpr))
Richard Smithe24f5fc2011-11-17 22:56:20 +00003134 return false;
3135 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003136 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003137 if (const ConstantArrayType *CAT
3138 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3139 Result.addArray(Info, E, CAT);
3140 else
3141 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003142 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003143
John McCall2de56d12010-08-25 11:45:40 +00003144 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003145 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003146 }
3147
Richard Smithc49bd112011-10-28 17:51:58 +00003148 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003149}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003150
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003151bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003152 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003153 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003154
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003155 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003156}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003157
3158//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003159// Member Pointer Evaluation
3160//===----------------------------------------------------------------------===//
3161
3162namespace {
3163class MemberPointerExprEvaluator
3164 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3165 MemberPtr &Result;
3166
3167 bool Success(const ValueDecl *D) {
3168 Result = MemberPtr(D);
3169 return true;
3170 }
3171public:
3172
3173 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3174 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3175
3176 bool Success(const CCValue &V, const Expr *E) {
3177 Result.setFrom(V);
3178 return true;
3179 }
Richard Smith51201882011-12-30 21:15:51 +00003180 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003181 return Success((const ValueDecl*)0);
3182 }
3183
3184 bool VisitCastExpr(const CastExpr *E);
3185 bool VisitUnaryAddrOf(const UnaryOperator *E);
3186};
3187} // end anonymous namespace
3188
3189static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3190 EvalInfo &Info) {
3191 assert(E->isRValue() && E->getType()->isMemberPointerType());
3192 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3193}
3194
3195bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3196 switch (E->getCastKind()) {
3197 default:
3198 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3199
3200 case CK_NullToMemberPointer:
Richard Smith51201882011-12-30 21:15:51 +00003201 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003202
3203 case CK_BaseToDerivedMemberPointer: {
3204 if (!Visit(E->getSubExpr()))
3205 return false;
3206 if (E->path_empty())
3207 return true;
3208 // Base-to-derived member pointer casts store the path in derived-to-base
3209 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3210 // the wrong end of the derived->base arc, so stagger the path by one class.
3211 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3212 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3213 PathI != PathE; ++PathI) {
3214 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3215 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3216 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003217 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003218 }
3219 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3220 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003221 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003222 return true;
3223 }
3224
3225 case CK_DerivedToBaseMemberPointer:
3226 if (!Visit(E->getSubExpr()))
3227 return false;
3228 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3229 PathE = E->path_end(); PathI != PathE; ++PathI) {
3230 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3231 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3232 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003233 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003234 }
3235 return true;
3236 }
3237}
3238
3239bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3240 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3241 // member can be formed.
3242 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3243}
3244
3245//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003246// Record Evaluation
3247//===----------------------------------------------------------------------===//
3248
3249namespace {
3250 class RecordExprEvaluator
3251 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3252 const LValue &This;
3253 APValue &Result;
3254 public:
3255
3256 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3257 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3258
3259 bool Success(const CCValue &V, const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003260 Result = V;
3261 return true;
Richard Smith180f4792011-11-10 06:34:14 +00003262 }
Richard Smith51201882011-12-30 21:15:51 +00003263 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003264
Richard Smith59efe262011-11-11 04:05:33 +00003265 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003266 bool VisitInitListExpr(const InitListExpr *E);
3267 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3268 };
3269}
3270
Richard Smith51201882011-12-30 21:15:51 +00003271/// Perform zero-initialization on an object of non-union class type.
3272/// C++11 [dcl.init]p5:
3273/// To zero-initialize an object or reference of type T means:
3274/// [...]
3275/// -- if T is a (possibly cv-qualified) non-union class type,
3276/// each non-static data member and each base-class subobject is
3277/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003278static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3279 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003280 const LValue &This, APValue &Result) {
3281 assert(!RD->isUnion() && "Expected non-union class type");
3282 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3283 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3284 std::distance(RD->field_begin(), RD->field_end()));
3285
3286 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3287
3288 if (CD) {
3289 unsigned Index = 0;
3290 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003291 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003292 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3293 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003294 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3295 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003296 Result.getStructBase(Index)))
3297 return false;
3298 }
3299 }
3300
Richard Smithb4e85ed2012-01-06 16:39:00 +00003301 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3302 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003303 // -- if T is a reference type, no initialization is performed.
3304 if ((*I)->getType()->isReferenceType())
3305 continue;
3306
3307 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003308 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smith51201882011-12-30 21:15:51 +00003309
3310 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003311 if (!EvaluateInPlace(
Richard Smith51201882011-12-30 21:15:51 +00003312 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3313 return false;
3314 }
3315
3316 return true;
3317}
3318
3319bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3320 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3321 if (RD->isUnion()) {
3322 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3323 // object's first non-static named data member is zero-initialized
3324 RecordDecl::field_iterator I = RD->field_begin();
3325 if (I == RD->field_end()) {
3326 Result = APValue((const FieldDecl*)0);
3327 return true;
3328 }
3329
3330 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003331 HandleLValueMember(Info, E, Subobject, *I);
Richard Smith51201882011-12-30 21:15:51 +00003332 Result = APValue(*I);
3333 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003334 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003335 }
3336
Richard Smithb4e85ed2012-01-06 16:39:00 +00003337 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003338}
3339
Richard Smith59efe262011-11-11 04:05:33 +00003340bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3341 switch (E->getCastKind()) {
3342 default:
3343 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3344
3345 case CK_ConstructorConversion:
3346 return Visit(E->getSubExpr());
3347
3348 case CK_DerivedToBase:
3349 case CK_UncheckedDerivedToBase: {
3350 CCValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003351 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003352 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003353 if (!DerivedObject.isStruct())
3354 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003355
3356 // Derived-to-base rvalue conversion: just slice off the derived part.
3357 APValue *Value = &DerivedObject;
3358 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3359 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3360 PathE = E->path_end(); PathI != PathE; ++PathI) {
3361 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3362 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3363 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3364 RD = Base;
3365 }
3366 Result = *Value;
3367 return true;
3368 }
3369 }
3370}
3371
Richard Smith180f4792011-11-10 06:34:14 +00003372bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3373 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3374 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3375
3376 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003377 const FieldDecl *Field = E->getInitializedFieldInUnion();
3378 Result = APValue(Field);
3379 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003380 return true;
Richard Smithec789162012-01-12 18:54:33 +00003381
3382 // If the initializer list for a union does not contain any elements, the
3383 // first element of the union is value-initialized.
3384 ImplicitValueInitExpr VIE(Field->getType());
3385 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3386
Richard Smith180f4792011-11-10 06:34:14 +00003387 LValue Subobject = This;
Richard Smithec789162012-01-12 18:54:33 +00003388 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
Richard Smith83587db2012-02-15 02:18:13 +00003389 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003390 }
3391
3392 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3393 "initializer list for class with base classes");
3394 Result = APValue(APValue::UninitStruct(), 0,
3395 std::distance(RD->field_begin(), RD->field_end()));
3396 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003397 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003398 for (RecordDecl::field_iterator Field = RD->field_begin(),
3399 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3400 // Anonymous bit-fields are not considered members of the class for
3401 // purposes of aggregate initialization.
3402 if (Field->isUnnamedBitfield())
3403 continue;
3404
3405 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003406
Richard Smith745f5142012-01-27 01:14:48 +00003407 bool HaveInit = ElementNo < E->getNumInits();
3408
3409 // FIXME: Diagnostics here should point to the end of the initializer
3410 // list, not the start.
3411 HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3412 *Field, &Layout);
3413
3414 // Perform an implicit value-initialization for members beyond the end of
3415 // the initializer list.
3416 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3417
Richard Smith83587db2012-02-15 02:18:13 +00003418 if (!EvaluateInPlace(
Richard Smith745f5142012-01-27 01:14:48 +00003419 Result.getStructField((*Field)->getFieldIndex()),
3420 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3421 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003422 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003423 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003424 }
3425 }
3426
Richard Smith745f5142012-01-27 01:14:48 +00003427 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003428}
3429
3430bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3431 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith51201882011-12-30 21:15:51 +00003432 bool ZeroInit = E->requiresZeroInitialization();
3433 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003434 // If we've already performed zero-initialization, we're already done.
3435 if (!Result.isUninit())
3436 return true;
3437
Richard Smith51201882011-12-30 21:15:51 +00003438 if (ZeroInit)
3439 return ZeroInitialization(E);
3440
Richard Smith61802452011-12-22 02:22:31 +00003441 const CXXRecordDecl *RD = FD->getParent();
3442 if (RD->isUnion())
3443 Result = APValue((FieldDecl*)0);
3444 else
3445 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3446 std::distance(RD->field_begin(), RD->field_end()));
3447 return true;
3448 }
3449
Richard Smith180f4792011-11-10 06:34:14 +00003450 const FunctionDecl *Definition = 0;
3451 FD->getBody(Definition);
3452
Richard Smithc1c5f272011-12-13 06:39:58 +00003453 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3454 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003455
Richard Smith610a60c2012-01-10 04:32:03 +00003456 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003457 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003458 if (const MaterializeTemporaryExpr *ME
3459 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3460 return Visit(ME->GetTemporaryExpr());
3461
Richard Smith51201882011-12-30 21:15:51 +00003462 if (ZeroInit && !ZeroInitialization(E))
3463 return false;
3464
Richard Smith180f4792011-11-10 06:34:14 +00003465 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003466 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003467 cast<CXXConstructorDecl>(Definition), Info,
3468 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003469}
3470
3471static bool EvaluateRecord(const Expr *E, const LValue &This,
3472 APValue &Result, EvalInfo &Info) {
3473 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003474 "can't evaluate expression as a record rvalue");
3475 return RecordExprEvaluator(Info, This, Result).Visit(E);
3476}
3477
3478//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003479// Temporary Evaluation
3480//
3481// Temporaries are represented in the AST as rvalues, but generally behave like
3482// lvalues. The full-object of which the temporary is a subobject is implicitly
3483// materialized so that a reference can bind to it.
3484//===----------------------------------------------------------------------===//
3485namespace {
3486class TemporaryExprEvaluator
3487 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3488public:
3489 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3490 LValueExprEvaluatorBaseTy(Info, Result) {}
3491
3492 /// Visit an expression which constructs the value of this temporary.
3493 bool VisitConstructExpr(const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003494 Result.set(E, Info.CurrentCall->Index);
3495 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003496 }
3497
3498 bool VisitCastExpr(const CastExpr *E) {
3499 switch (E->getCastKind()) {
3500 default:
3501 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3502
3503 case CK_ConstructorConversion:
3504 return VisitConstructExpr(E->getSubExpr());
3505 }
3506 }
3507 bool VisitInitListExpr(const InitListExpr *E) {
3508 return VisitConstructExpr(E);
3509 }
3510 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3511 return VisitConstructExpr(E);
3512 }
3513 bool VisitCallExpr(const CallExpr *E) {
3514 return VisitConstructExpr(E);
3515 }
3516};
3517} // end anonymous namespace
3518
3519/// Evaluate an expression of record type as a temporary.
3520static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003521 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003522 return TemporaryExprEvaluator(Info, Result).Visit(E);
3523}
3524
3525//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003526// Vector Evaluation
3527//===----------------------------------------------------------------------===//
3528
3529namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003530 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003531 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3532 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003533 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003534
Richard Smith07fc6572011-10-22 21:10:00 +00003535 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3536 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003537
Richard Smith07fc6572011-10-22 21:10:00 +00003538 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3539 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3540 // FIXME: remove this APValue copy.
3541 Result = APValue(V.data(), V.size());
3542 return true;
3543 }
Richard Smith69c2c502011-11-04 05:33:44 +00003544 bool Success(const CCValue &V, const Expr *E) {
3545 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003546 Result = V;
3547 return true;
3548 }
Richard Smith51201882011-12-30 21:15:51 +00003549 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003550
Richard Smith07fc6572011-10-22 21:10:00 +00003551 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003552 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003553 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003554 bool VisitInitListExpr(const InitListExpr *E);
3555 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003556 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003557 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003558 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003559 };
3560} // end anonymous namespace
3561
3562static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003563 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003564 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003565}
3566
Richard Smith07fc6572011-10-22 21:10:00 +00003567bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3568 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003569 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003570
Richard Smithd62ca372011-12-06 22:44:34 +00003571 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003572 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003573
Eli Friedman46a52322011-03-25 00:43:55 +00003574 switch (E->getCastKind()) {
3575 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003576 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003577 if (SETy->isIntegerType()) {
3578 APSInt IntResult;
3579 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003580 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003581 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003582 } else if (SETy->isRealFloatingType()) {
3583 APFloat F(0.0);
3584 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003585 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003586 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003587 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003588 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003589 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003590
3591 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003592 SmallVector<APValue, 4> Elts(NElts, Val);
3593 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003594 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003595 case CK_BitCast: {
3596 // Evaluate the operand into an APInt we can extract from.
3597 llvm::APInt SValInt;
3598 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3599 return false;
3600 // Extract the elements
3601 QualType EltTy = VTy->getElementType();
3602 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3603 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3604 SmallVector<APValue, 4> Elts;
3605 if (EltTy->isRealFloatingType()) {
3606 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3607 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3608 unsigned FloatEltSize = EltSize;
3609 if (&Sem == &APFloat::x87DoubleExtended)
3610 FloatEltSize = 80;
3611 for (unsigned i = 0; i < NElts; i++) {
3612 llvm::APInt Elt;
3613 if (BigEndian)
3614 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3615 else
3616 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3617 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3618 }
3619 } else if (EltTy->isIntegerType()) {
3620 for (unsigned i = 0; i < NElts; i++) {
3621 llvm::APInt Elt;
3622 if (BigEndian)
3623 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3624 else
3625 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3626 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3627 }
3628 } else {
3629 return Error(E);
3630 }
3631 return Success(Elts, E);
3632 }
Eli Friedman46a52322011-03-25 00:43:55 +00003633 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003634 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003635 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003636}
3637
Richard Smith07fc6572011-10-22 21:10:00 +00003638bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003639VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003640 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003641 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003642 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003643
Nate Begeman59b5da62009-01-18 03:20:47 +00003644 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003645 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003646
Eli Friedman3edd5a92012-01-03 23:24:20 +00003647 // The number of initializers can be less than the number of
3648 // vector elements. For OpenCL, this can be due to nested vector
3649 // initialization. For GCC compatibility, missing trailing elements
3650 // should be initialized with zeroes.
3651 unsigned CountInits = 0, CountElts = 0;
3652 while (CountElts < NumElements) {
3653 // Handle nested vector initialization.
3654 if (CountInits < NumInits
3655 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3656 APValue v;
3657 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3658 return Error(E);
3659 unsigned vlen = v.getVectorLength();
3660 for (unsigned j = 0; j < vlen; j++)
3661 Elements.push_back(v.getVectorElt(j));
3662 CountElts += vlen;
3663 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003664 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003665 if (CountInits < NumInits) {
3666 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3667 return Error(E);
3668 } else // trailing integer zero.
3669 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3670 Elements.push_back(APValue(sInt));
3671 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003672 } else {
3673 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003674 if (CountInits < NumInits) {
3675 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3676 return Error(E);
3677 } else // trailing float zero.
3678 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3679 Elements.push_back(APValue(f));
3680 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003681 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003682 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003683 }
Richard Smith07fc6572011-10-22 21:10:00 +00003684 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003685}
3686
Richard Smith07fc6572011-10-22 21:10:00 +00003687bool
Richard Smith51201882011-12-30 21:15:51 +00003688VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003689 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003690 QualType EltTy = VT->getElementType();
3691 APValue ZeroElement;
3692 if (EltTy->isIntegerType())
3693 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3694 else
3695 ZeroElement =
3696 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3697
Chris Lattner5f9e2722011-07-23 10:55:15 +00003698 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003699 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003700}
3701
Richard Smith07fc6572011-10-22 21:10:00 +00003702bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003703 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003704 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003705}
3706
Nate Begeman59b5da62009-01-18 03:20:47 +00003707//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003708// Array Evaluation
3709//===----------------------------------------------------------------------===//
3710
3711namespace {
3712 class ArrayExprEvaluator
3713 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003714 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003715 APValue &Result;
3716 public:
3717
Richard Smith180f4792011-11-10 06:34:14 +00003718 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3719 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003720
3721 bool Success(const APValue &V, const Expr *E) {
3722 assert(V.isArray() && "Expected array type");
3723 Result = V;
3724 return true;
3725 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003726
Richard Smith51201882011-12-30 21:15:51 +00003727 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003728 const ConstantArrayType *CAT =
3729 Info.Ctx.getAsConstantArrayType(E->getType());
3730 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003731 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003732
3733 Result = APValue(APValue::UninitArray(), 0,
3734 CAT->getSize().getZExtValue());
3735 if (!Result.hasArrayFiller()) return true;
3736
Richard Smith51201882011-12-30 21:15:51 +00003737 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003738 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003739 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003740 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003741 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith180f4792011-11-10 06:34:14 +00003742 }
3743
Richard Smithcc5d4f62011-11-07 09:22:26 +00003744 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003745 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003746 };
3747} // end anonymous namespace
3748
Richard Smith180f4792011-11-10 06:34:14 +00003749static bool EvaluateArray(const Expr *E, const LValue &This,
3750 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003751 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003752 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003753}
3754
3755bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3756 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3757 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003758 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003759
Richard Smith974c5f92011-12-22 01:07:19 +00003760 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3761 // an appropriately-typed string literal enclosed in braces.
Richard Smithec789162012-01-12 18:54:33 +00003762 if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
Richard Smith974c5f92011-12-22 01:07:19 +00003763 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3764 LValue LV;
3765 if (!EvaluateLValue(E->getInit(0), LV, Info))
3766 return false;
3767 uint64_t NumElements = CAT->getSize().getZExtValue();
3768 Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3769
3770 // Copy the string literal into the array. FIXME: Do this better.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003771 LV.addArray(Info, E, CAT);
Richard Smith974c5f92011-12-22 01:07:19 +00003772 for (uint64_t I = 0; I < NumElements; ++I) {
3773 CCValue Char;
3774 if (!HandleLValueToRValueConversion(Info, E->getInit(0),
Richard Smith83587db2012-02-15 02:18:13 +00003775 CAT->getElementType(), LV, Char))
3776 return false;
3777 Result.getArrayInitializedElt(I) = Char.toAPValue();
3778 if (!HandleLValueArrayAdjustment(Info, E->getInit(0), LV,
Richard Smithb4e85ed2012-01-06 16:39:00 +00003779 CAT->getElementType(), 1))
Richard Smith974c5f92011-12-22 01:07:19 +00003780 return false;
3781 }
3782 return true;
3783 }
3784
Richard Smith745f5142012-01-27 01:14:48 +00003785 bool Success = true;
3786
Richard Smithcc5d4f62011-11-07 09:22:26 +00003787 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3788 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003789 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003790 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003791 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003792 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003793 I != End; ++I, ++Index) {
Richard Smith83587db2012-02-15 02:18:13 +00003794 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3795 Info, Subobject, cast<Expr>(*I)) ||
Richard Smith745f5142012-01-27 01:14:48 +00003796 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3797 CAT->getElementType(), 1)) {
3798 if (!Info.keepEvaluatingAfterFailure())
3799 return false;
3800 Success = false;
3801 }
Richard Smith180f4792011-11-10 06:34:14 +00003802 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003803
Richard Smith745f5142012-01-27 01:14:48 +00003804 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003805 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003806 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3807 // but sometimes does:
3808 // struct S { constexpr S() : p(&p) {} void *p; };
3809 // S s[10] = {};
Richard Smith83587db2012-02-15 02:18:13 +00003810 return EvaluateInPlace(Result.getArrayFiller(), Info,
3811 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003812}
3813
Richard Smithe24f5fc2011-11-17 22:56:20 +00003814bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3815 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3816 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003817 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003818
Richard Smithec789162012-01-12 18:54:33 +00003819 bool HadZeroInit = !Result.isUninit();
3820 if (!HadZeroInit)
3821 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003822 if (!Result.hasArrayFiller())
3823 return true;
3824
3825 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003826
Richard Smith51201882011-12-30 21:15:51 +00003827 bool ZeroInit = E->requiresZeroInitialization();
3828 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003829 if (HadZeroInit)
3830 return true;
3831
Richard Smith51201882011-12-30 21:15:51 +00003832 if (ZeroInit) {
3833 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003834 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003835 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003836 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003837 }
3838
Richard Smith61802452011-12-22 02:22:31 +00003839 const CXXRecordDecl *RD = FD->getParent();
3840 if (RD->isUnion())
3841 Result.getArrayFiller() = APValue((FieldDecl*)0);
3842 else
3843 Result.getArrayFiller() =
3844 APValue(APValue::UninitStruct(), RD->getNumBases(),
3845 std::distance(RD->field_begin(), RD->field_end()));
3846 return true;
3847 }
3848
Richard Smithe24f5fc2011-11-17 22:56:20 +00003849 const FunctionDecl *Definition = 0;
3850 FD->getBody(Definition);
3851
Richard Smithc1c5f272011-12-13 06:39:58 +00003852 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3853 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003854
3855 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3856 // but sometimes does:
3857 // struct S { constexpr S() : p(&p) {} void *p; };
3858 // S s[10];
3859 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003860 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003861
Richard Smithec789162012-01-12 18:54:33 +00003862 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003863 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003864 if (!EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003865 return false;
3866 }
3867
Richard Smithe24f5fc2011-11-17 22:56:20 +00003868 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003869 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003870 cast<CXXConstructorDecl>(Definition),
3871 Info, Result.getArrayFiller());
3872}
3873
Richard Smithcc5d4f62011-11-07 09:22:26 +00003874//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003875// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003876//
3877// As a GNU extension, we support casting pointers to sufficiently-wide integer
3878// types and back in constant folding. Integer values are thus represented
3879// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003880//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003881
3882namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003883class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003884 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00003885 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003886public:
Richard Smith47a1eed2011-10-29 20:57:55 +00003887 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003888 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003889
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003890 bool Success(const llvm::APSInt &SI, const Expr *E) {
3891 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003892 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003893 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003894 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003895 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003896 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003897 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003898 return true;
3899 }
3900
Daniel Dunbar131eb432009-02-19 09:06:44 +00003901 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003902 assert(E->getType()->isIntegralOrEnumerationType() &&
3903 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003904 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003905 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003906 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003907 Result.getInt().setIsUnsigned(
3908 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003909 return true;
3910 }
3911
3912 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003913 assert(E->getType()->isIntegralOrEnumerationType() &&
3914 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003915 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003916 return true;
3917 }
3918
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003919 bool Success(CharUnits Size, const Expr *E) {
3920 return Success(Size.getQuantity(), E);
3921 }
3922
Richard Smith47a1eed2011-10-29 20:57:55 +00003923 bool Success(const CCValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00003924 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00003925 Result = V;
3926 return true;
3927 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003928 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003929 }
Mike Stump1eb44332009-09-09 15:08:12 +00003930
Richard Smith51201882011-12-30 21:15:51 +00003931 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00003932
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003933 //===--------------------------------------------------------------------===//
3934 // Visitor Methods
3935 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003936
Chris Lattner4c4867e2008-07-12 00:38:25 +00003937 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003938 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003939 }
3940 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003941 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003942 }
Eli Friedman04309752009-11-24 05:28:59 +00003943
3944 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3945 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003946 if (CheckReferencedDecl(E, E->getDecl()))
3947 return true;
3948
3949 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003950 }
3951 bool VisitMemberExpr(const MemberExpr *E) {
3952 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00003953 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00003954 return true;
3955 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003956
3957 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003958 }
3959
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003960 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003961 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003962 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003963 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00003964
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003965 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003966 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00003967
Anders Carlsson3068d112008-11-16 19:01:22 +00003968 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003969 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00003970 }
Mike Stump1eb44332009-09-09 15:08:12 +00003971
Richard Smithf10d9172011-10-11 21:43:33 +00003972 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00003973 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00003974 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00003975 }
3976
Sebastian Redl64b45f72009-01-05 20:52:13 +00003977 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003978 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003979 }
3980
Francois Pichet6ad6f282010-12-07 00:08:36 +00003981 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3982 return Success(E->getValue(), E);
3983 }
3984
John Wiegley21ff2e52011-04-28 00:16:57 +00003985 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3986 return Success(E->getValue(), E);
3987 }
3988
John Wiegley55262202011-04-25 06:54:41 +00003989 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3990 return Success(E->getValue(), E);
3991 }
3992
Eli Friedman722c7172009-02-28 03:59:05 +00003993 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003994 bool VisitUnaryImag(const UnaryOperator *E);
3995
Sebastian Redl295995c2010-09-10 20:55:47 +00003996 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00003997 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00003998
Chris Lattnerfcee0012008-07-11 21:24:13 +00003999private:
Ken Dyck8b752f12010-01-27 17:10:57 +00004000 CharUnits GetAlignOfExpr(const Expr *E);
4001 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004002 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004003 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004004 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004005};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004006} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00004007
Richard Smithc49bd112011-10-28 17:51:58 +00004008/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4009/// produce either the integer value or a pointer.
4010///
4011/// GCC has a heinous extension which folds casts between pointer types and
4012/// pointer-sized integral types. We support this by allowing the evaluation of
4013/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4014/// Some simple arithmetic on such values is supported (they are treated much
4015/// like char*).
Richard Smithf48fdb02011-12-09 22:58:01 +00004016static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00004017 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004018 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004019 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004020}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004021
Richard Smithf48fdb02011-12-09 22:58:01 +00004022static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004023 CCValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00004024 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004025 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004026 if (!Val.isInt()) {
4027 // FIXME: It would be better to produce the diagnostic for casting
4028 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00004029 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00004030 return false;
4031 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004032 Result = Val.getInt();
4033 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00004034}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004035
Richard Smithf48fdb02011-12-09 22:58:01 +00004036/// Check whether the given declaration can be directly converted to an integral
4037/// rvalue. If not, no diagnostic is produced; there are other things we can
4038/// try.
Eli Friedman04309752009-11-24 05:28:59 +00004039bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00004040 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004041 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004042 // Check for signedness/width mismatches between E type and ECD value.
4043 bool SameSign = (ECD->getInitVal().isSigned()
4044 == E->getType()->isSignedIntegerOrEnumerationType());
4045 bool SameWidth = (ECD->getInitVal().getBitWidth()
4046 == Info.Ctx.getIntWidth(E->getType()));
4047 if (SameSign && SameWidth)
4048 return Success(ECD->getInitVal(), E);
4049 else {
4050 // Get rid of mismatch (otherwise Success assertions will fail)
4051 // by computing a new value matching the type of E.
4052 llvm::APSInt Val = ECD->getInitVal();
4053 if (!SameSign)
4054 Val.setIsSigned(!ECD->getInitVal().isSigned());
4055 if (!SameWidth)
4056 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4057 return Success(Val, E);
4058 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004059 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004060 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00004061}
4062
Chris Lattnera4d55d82008-10-06 06:40:35 +00004063/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4064/// as GCC.
4065static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4066 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004067 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00004068 enum gcc_type_class {
4069 no_type_class = -1,
4070 void_type_class, integer_type_class, char_type_class,
4071 enumeral_type_class, boolean_type_class,
4072 pointer_type_class, reference_type_class, offset_type_class,
4073 real_type_class, complex_type_class,
4074 function_type_class, method_type_class,
4075 record_type_class, union_type_class,
4076 array_type_class, string_type_class,
4077 lang_type_class
4078 };
Mike Stump1eb44332009-09-09 15:08:12 +00004079
4080 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00004081 // ideal, however it is what gcc does.
4082 if (E->getNumArgs() == 0)
4083 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00004084
Chris Lattnera4d55d82008-10-06 06:40:35 +00004085 QualType ArgTy = E->getArg(0)->getType();
4086 if (ArgTy->isVoidType())
4087 return void_type_class;
4088 else if (ArgTy->isEnumeralType())
4089 return enumeral_type_class;
4090 else if (ArgTy->isBooleanType())
4091 return boolean_type_class;
4092 else if (ArgTy->isCharType())
4093 return string_type_class; // gcc doesn't appear to use char_type_class
4094 else if (ArgTy->isIntegerType())
4095 return integer_type_class;
4096 else if (ArgTy->isPointerType())
4097 return pointer_type_class;
4098 else if (ArgTy->isReferenceType())
4099 return reference_type_class;
4100 else if (ArgTy->isRealType())
4101 return real_type_class;
4102 else if (ArgTy->isComplexType())
4103 return complex_type_class;
4104 else if (ArgTy->isFunctionType())
4105 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004106 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004107 return record_type_class;
4108 else if (ArgTy->isUnionType())
4109 return union_type_class;
4110 else if (ArgTy->isArrayType())
4111 return array_type_class;
4112 else if (ArgTy->isUnionType())
4113 return union_type_class;
4114 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004115 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004116}
4117
Richard Smith80d4b552011-12-28 19:48:30 +00004118/// EvaluateBuiltinConstantPForLValue - Determine the result of
4119/// __builtin_constant_p when applied to the given lvalue.
4120///
4121/// An lvalue is only "constant" if it is a pointer or reference to the first
4122/// character of a string literal.
4123template<typename LValue>
4124static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
4125 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
4126 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4127}
4128
4129/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4130/// GCC as we can manage.
4131static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4132 QualType ArgType = Arg->getType();
4133
4134 // __builtin_constant_p always has one operand. The rules which gcc follows
4135 // are not precisely documented, but are as follows:
4136 //
4137 // - If the operand is of integral, floating, complex or enumeration type,
4138 // and can be folded to a known value of that type, it returns 1.
4139 // - If the operand and can be folded to a pointer to the first character
4140 // of a string literal (or such a pointer cast to an integral type), it
4141 // returns 1.
4142 //
4143 // Otherwise, it returns 0.
4144 //
4145 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4146 // its support for this does not currently work.
4147 if (ArgType->isIntegralOrEnumerationType()) {
4148 Expr::EvalResult Result;
4149 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4150 return false;
4151
4152 APValue &V = Result.Val;
4153 if (V.getKind() == APValue::Int)
4154 return true;
4155
4156 return EvaluateBuiltinConstantPForLValue(V);
4157 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4158 return Arg->isEvaluatable(Ctx);
4159 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4160 LValue LV;
4161 Expr::EvalStatus Status;
4162 EvalInfo Info(Ctx, Status);
4163 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4164 : EvaluatePointer(Arg, LV, Info)) &&
4165 !Status.HasSideEffects)
4166 return EvaluateBuiltinConstantPForLValue(LV);
4167 }
4168
4169 // Anything else isn't considered to be sufficiently constant.
4170 return false;
4171}
4172
John McCall42c8f872010-05-10 23:27:23 +00004173/// Retrieves the "underlying object type" of the given expression,
4174/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004175QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4176 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4177 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004178 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004179 } else if (const Expr *E = B.get<const Expr*>()) {
4180 if (isa<CompoundLiteralExpr>(E))
4181 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004182 }
4183
4184 return QualType();
4185}
4186
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004187bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004188 // TODO: Perhaps we should let LLVM lower this?
4189 LValue Base;
4190 if (!EvaluatePointer(E->getArg(0), Base, Info))
4191 return false;
4192
4193 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004194 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004195
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004196 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004197 if (T.isNull() ||
4198 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004199 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004200 T->isVariablyModifiedType() ||
4201 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004202 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004203
4204 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4205 CharUnits Offset = Base.getLValueOffset();
4206
4207 if (!Offset.isNegative() && Offset <= Size)
4208 Size -= Offset;
4209 else
4210 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004211 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004212}
4213
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004214bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004215 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004216 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004217 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004218
4219 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004220 if (TryEvaluateBuiltinObjectSize(E))
4221 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004222
Eric Christopherb2aaf512010-01-19 22:58:35 +00004223 // If evaluating the argument has side-effects we can't determine
4224 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004225 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004226 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004227 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004228 return Success(0, E);
4229 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004230
Richard Smithf48fdb02011-12-09 22:58:01 +00004231 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004232 }
4233
Chris Lattner019f4e82008-10-06 05:28:25 +00004234 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004235 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004236
Richard Smith80d4b552011-12-28 19:48:30 +00004237 case Builtin::BI__builtin_constant_p:
4238 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004239
Chris Lattner21fb98e2009-09-23 06:06:36 +00004240 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004241 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004242 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004243 return Success(Operand, E);
4244 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004245
4246 case Builtin::BI__builtin_expect:
4247 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004248
Douglas Gregor5726d402010-09-10 06:27:15 +00004249 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004250 // A call to strlen is not a constant expression.
4251 if (Info.getLangOpts().CPlusPlus0x)
4252 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_function)
4253 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4254 else
4255 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
4256 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004257 case Builtin::BI__builtin_strlen:
4258 // As an extension, we support strlen() and __builtin_strlen() as constant
4259 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004260 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004261 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4262 // The string literal may have embedded null characters. Find the first
4263 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004264 StringRef Str = S->getString();
4265 StringRef::size_type Pos = Str.find(0);
4266 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004267 Str = Str.substr(0, Pos);
4268
4269 return Success(Str.size(), E);
4270 }
4271
Richard Smithf48fdb02011-12-09 22:58:01 +00004272 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004273
4274 case Builtin::BI__atomic_is_lock_free: {
4275 APSInt SizeVal;
4276 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4277 return false;
4278
4279 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4280 // of two less than the maximum inline atomic width, we know it is
4281 // lock-free. If the size isn't a power of two, or greater than the
4282 // maximum alignment where we promote atomics, we know it is not lock-free
4283 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4284 // the answer can only be determined at runtime; for example, 16-byte
4285 // atomics have lock-free implementations on some, but not all,
4286 // x86-64 processors.
4287
4288 // Check power-of-two.
4289 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4290 if (!Size.isPowerOfTwo())
4291#if 0
4292 // FIXME: Suppress this folding until the ABI for the promotion width
4293 // settles.
4294 return Success(0, E);
4295#else
Richard Smithf48fdb02011-12-09 22:58:01 +00004296 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004297#endif
4298
4299#if 0
4300 // Check against promotion width.
4301 // FIXME: Suppress this folding until the ABI for the promotion width
4302 // settles.
4303 unsigned PromoteWidthBits =
4304 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
4305 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
4306 return Success(0, E);
4307#endif
4308
4309 // Check against inlining width.
4310 unsigned InlineWidthBits =
4311 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4312 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
4313 return Success(1, E);
4314
Richard Smithf48fdb02011-12-09 22:58:01 +00004315 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004316 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004317 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004318}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004319
Richard Smith625b8072011-10-31 01:37:14 +00004320static bool HasSameBase(const LValue &A, const LValue &B) {
4321 if (!A.getLValueBase())
4322 return !B.getLValueBase();
4323 if (!B.getLValueBase())
4324 return false;
4325
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004326 if (A.getLValueBase().getOpaqueValue() !=
4327 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004328 const Decl *ADecl = GetLValueBaseDecl(A);
4329 if (!ADecl)
4330 return false;
4331 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004332 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004333 return false;
4334 }
4335
4336 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith83587db2012-02-15 02:18:13 +00004337 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith625b8072011-10-31 01:37:14 +00004338}
4339
Richard Smith7b48a292012-02-01 05:53:12 +00004340/// Perform the given integer operation, which is known to need at most BitWidth
4341/// bits, and check for overflow in the original type (if that type was not an
4342/// unsigned type).
4343template<typename Operation>
4344static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4345 const APSInt &LHS, const APSInt &RHS,
4346 unsigned BitWidth, Operation Op) {
4347 if (LHS.isUnsigned())
4348 return Op(LHS, RHS);
4349
4350 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4351 APSInt Result = Value.trunc(LHS.getBitWidth());
4352 if (Result.extend(BitWidth) != Value)
4353 HandleOverflow(Info, E, Value, E->getType());
4354 return Result;
4355}
4356
Chris Lattnerb542afe2008-07-11 19:10:17 +00004357bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004358 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004359 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004360
John McCall2de56d12010-08-25 11:45:40 +00004361 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00004362 VisitIgnoredValue(E->getLHS());
4363 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00004364 }
4365
4366 if (E->isLogicalOp()) {
4367 // These need to be handled specially because the operands aren't
4368 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004369 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00004370
Richard Smithc49bd112011-10-28 17:51:58 +00004371 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00004372 // We were able to evaluate the LHS, see if we can get away with not
4373 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00004374 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004375 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004376
Richard Smithc49bd112011-10-28 17:51:58 +00004377 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00004378 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004379 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004380 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00004381 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004382 }
4383 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00004384 // FIXME: If both evaluations fail, we should produce the diagnostic from
4385 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
4386 // less clear how to diagnose this.
Richard Smithc49bd112011-10-28 17:51:58 +00004387 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004388 // We can't evaluate the LHS; however, sometimes the result
4389 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf48fdb02011-12-09 22:58:01 +00004390 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004391 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004392 // must have had side effects.
Richard Smith1e12c592011-10-16 21:26:27 +00004393 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004394
4395 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004396 }
4397 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00004398 }
Eli Friedmana6afa762008-11-13 06:09:17 +00004399
Eli Friedmana6afa762008-11-13 06:09:17 +00004400 return false;
4401 }
4402
Anders Carlsson286f85e2008-11-16 07:17:21 +00004403 QualType LHSTy = E->getLHS()->getType();
4404 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004405
4406 if (LHSTy->isAnyComplexType()) {
4407 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004408 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004409
Richard Smith745f5142012-01-27 01:14:48 +00004410 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4411 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004412 return false;
4413
Richard Smith745f5142012-01-27 01:14:48 +00004414 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004415 return false;
4416
4417 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004418 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004419 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004420 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004421 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4422
John McCall2de56d12010-08-25 11:45:40 +00004423 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004424 return Success((CR_r == APFloat::cmpEqual &&
4425 CR_i == APFloat::cmpEqual), E);
4426 else {
John McCall2de56d12010-08-25 11:45:40 +00004427 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004428 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004429 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004430 CR_r == APFloat::cmpLessThan ||
4431 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004432 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004433 CR_i == APFloat::cmpLessThan ||
4434 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004435 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004436 } else {
John McCall2de56d12010-08-25 11:45:40 +00004437 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004438 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4439 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4440 else {
John McCall2de56d12010-08-25 11:45:40 +00004441 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004442 "Invalid compex comparison.");
4443 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4444 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4445 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004446 }
4447 }
Mike Stump1eb44332009-09-09 15:08:12 +00004448
Anders Carlsson286f85e2008-11-16 07:17:21 +00004449 if (LHSTy->isRealFloatingType() &&
4450 RHSTy->isRealFloatingType()) {
4451 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004452
Richard Smith745f5142012-01-27 01:14:48 +00004453 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4454 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004455 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004456
Richard Smith745f5142012-01-27 01:14:48 +00004457 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004458 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004459
Anders Carlsson286f85e2008-11-16 07:17:21 +00004460 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004461
Anders Carlsson286f85e2008-11-16 07:17:21 +00004462 switch (E->getOpcode()) {
4463 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004464 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004465 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004466 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004467 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004468 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004469 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004470 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004471 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004472 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004473 E);
John McCall2de56d12010-08-25 11:45:40 +00004474 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004475 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004476 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004477 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004478 || CR == APFloat::cmpLessThan
4479 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004480 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004481 }
Mike Stump1eb44332009-09-09 15:08:12 +00004482
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004483 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004484 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004485 LValue LHSValue, RHSValue;
4486
4487 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4488 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004489 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004490
Richard Smith745f5142012-01-27 01:14:48 +00004491 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004492 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004493
Richard Smith625b8072011-10-31 01:37:14 +00004494 // Reject differing bases from the normal codepath; we special-case
4495 // comparisons to null.
4496 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004497 if (E->getOpcode() == BO_Sub) {
4498 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004499 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4500 return false;
4501 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4502 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4503 if (!LHSExpr || !RHSExpr)
4504 return false;
4505 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4506 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4507 if (!LHSAddrExpr || !RHSAddrExpr)
4508 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004509 // Make sure both labels come from the same function.
4510 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4511 RHSAddrExpr->getLabel()->getDeclContext())
4512 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004513 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4514 return true;
4515 }
Richard Smith9e36b532011-10-31 05:11:32 +00004516 // Inequalities and subtractions between unrelated pointers have
4517 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004518 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004519 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004520 // A constant address may compare equal to the address of a symbol.
4521 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004522 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004523 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4524 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004525 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004526 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004527 // distinct addresses. In clang, the result of such a comparison is
4528 // unspecified, so it is not a constant expression. However, we do know
4529 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004530 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4531 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004532 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004533 // We can't tell whether weak symbols will end up pointing to the same
4534 // object.
4535 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004536 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004537 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004538 // (Note that clang defaults to -fmerge-all-constants, which can
4539 // lead to inconsistent results for comparisons involving the address
4540 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004541 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004542 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004543
Richard Smith15efc4d2012-02-01 08:10:20 +00004544 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4545 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4546
Richard Smithf15fda02012-02-02 01:16:57 +00004547 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4548 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4549
John McCall2de56d12010-08-25 11:45:40 +00004550 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00004551 // C++11 [expr.add]p6:
4552 // Unless both pointers point to elements of the same array object, or
4553 // one past the last element of the array object, the behavior is
4554 // undefined.
4555 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4556 !AreElementsOfSameArray(getType(LHSValue.Base),
4557 LHSDesignator, RHSDesignator))
4558 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4559
Chris Lattner4992bdd2010-04-20 17:13:14 +00004560 QualType Type = E->getLHS()->getType();
4561 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004562
Richard Smith180f4792011-11-10 06:34:14 +00004563 CharUnits ElementSize;
4564 if (!HandleSizeof(Info, ElementType, ElementSize))
4565 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004566
Richard Smith15efc4d2012-02-01 08:10:20 +00004567 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
4568 // and produce incorrect results when it overflows. Such behavior
4569 // appears to be non-conforming, but is common, so perhaps we should
4570 // assume the standard intended for such cases to be undefined behavior
4571 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00004572
Richard Smith15efc4d2012-02-01 08:10:20 +00004573 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
4574 // overflow in the final conversion to ptrdiff_t.
4575 APSInt LHS(
4576 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
4577 APSInt RHS(
4578 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
4579 APSInt ElemSize(
4580 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
4581 APSInt TrueResult = (LHS - RHS) / ElemSize;
4582 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
4583
4584 if (Result.extend(65) != TrueResult)
4585 HandleOverflow(Info, E, TrueResult, E->getType());
4586 return Success(Result, E);
4587 }
Richard Smith82f28582012-01-31 06:41:30 +00004588
4589 // C++11 [expr.rel]p3:
4590 // Pointers to void (after pointer conversions) can be compared, with a
4591 // result defined as follows: If both pointers represent the same
4592 // address or are both the null pointer value, the result is true if the
4593 // operator is <= or >= and false otherwise; otherwise the result is
4594 // unspecified.
4595 // We interpret this as applying to pointers to *cv* void.
4596 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00004597 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00004598 CCEDiag(E, diag::note_constexpr_void_comparison);
4599
Richard Smithf15fda02012-02-02 01:16:57 +00004600 // C++11 [expr.rel]p2:
4601 // - If two pointers point to non-static data members of the same object,
4602 // or to subobjects or array elements fo such members, recursively, the
4603 // pointer to the later declared member compares greater provided the
4604 // two members have the same access control and provided their class is
4605 // not a union.
4606 // [...]
4607 // - Otherwise pointer comparisons are unspecified.
4608 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4609 E->isRelationalOp()) {
4610 bool WasArrayIndex;
4611 unsigned Mismatch =
4612 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
4613 RHSDesignator, WasArrayIndex);
4614 // At the point where the designators diverge, the comparison has a
4615 // specified value if:
4616 // - we are comparing array indices
4617 // - we are comparing fields of a union, or fields with the same access
4618 // Otherwise, the result is unspecified and thus the comparison is not a
4619 // constant expression.
4620 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
4621 Mismatch < RHSDesignator.Entries.size()) {
4622 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
4623 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
4624 if (!LF && !RF)
4625 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
4626 else if (!LF)
4627 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4628 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
4629 << RF->getParent() << RF;
4630 else if (!RF)
4631 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4632 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
4633 << LF->getParent() << LF;
4634 else if (!LF->getParent()->isUnion() &&
4635 LF->getAccess() != RF->getAccess())
4636 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
4637 << LF << LF->getAccess() << RF << RF->getAccess()
4638 << LF->getParent();
4639 }
4640 }
4641
Richard Smith625b8072011-10-31 01:37:14 +00004642 switch (E->getOpcode()) {
4643 default: llvm_unreachable("missing comparison operator");
4644 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4645 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4646 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4647 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4648 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4649 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004650 }
Anders Carlsson3068d112008-11-16 19:01:22 +00004651 }
4652 }
Richard Smithb02e4622012-02-01 01:42:44 +00004653
4654 if (LHSTy->isMemberPointerType()) {
4655 assert(E->isEqualityOp() && "unexpected member pointer operation");
4656 assert(RHSTy->isMemberPointerType() && "invalid comparison");
4657
4658 MemberPtr LHSValue, RHSValue;
4659
4660 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
4661 if (!LHSOK && Info.keepEvaluatingAfterFailure())
4662 return false;
4663
4664 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
4665 return false;
4666
4667 // C++11 [expr.eq]p2:
4668 // If both operands are null, they compare equal. Otherwise if only one is
4669 // null, they compare unequal.
4670 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
4671 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
4672 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4673 }
4674
4675 // Otherwise if either is a pointer to a virtual member function, the
4676 // result is unspecified.
4677 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
4678 if (MD->isVirtual())
4679 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4680 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
4681 if (MD->isVirtual())
4682 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4683
4684 // Otherwise they compare equal if and only if they would refer to the
4685 // same member of the same most derived object or the same subobject if
4686 // they were dereferenced with a hypothetical object of the associated
4687 // class type.
4688 bool Equal = LHSValue == RHSValue;
4689 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4690 }
4691
Richard Smith26f2cac2012-02-14 22:35:28 +00004692 if (LHSTy->isNullPtrType()) {
4693 assert(E->isComparisonOp() && "unexpected nullptr operation");
4694 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
4695 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
4696 // are compared, the result is true of the operator is <=, >= or ==, and
4697 // false otherwise.
4698 BinaryOperator::Opcode Opcode = E->getOpcode();
4699 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
4700 }
4701
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004702 if (!LHSTy->isIntegralOrEnumerationType() ||
4703 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004704 // We can't continue from here for non-integral types.
4705 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004706 }
4707
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004708 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00004709 CCValue LHSVal;
Richard Smith745f5142012-01-27 01:14:48 +00004710
4711 bool LHSOK = EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info);
4712 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Richard Smithf48fdb02011-12-09 22:58:01 +00004713 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00004714
Richard Smith745f5142012-01-27 01:14:48 +00004715 if (!Visit(E->getRHS()) || !LHSOK)
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004716 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004717
Richard Smith47a1eed2011-10-29 20:57:55 +00004718 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004719
4720 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00004721 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00004722 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4723 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00004724 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00004725 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004726 else
Richard Smith47a1eed2011-10-29 20:57:55 +00004727 LHSVal.getLValueOffset() -= AdditionalOffset;
4728 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004729 return true;
4730 }
4731
4732 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00004733 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00004734 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004735 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4736 LHSVal.getInt().getZExtValue());
4737 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00004738 return true;
4739 }
4740
Eli Friedman65639282012-01-04 23:13:47 +00004741 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4742 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedman65639282012-01-04 23:13:47 +00004743 if (!LHSVal.getLValueOffset().isZero() ||
4744 !RHSVal.getLValueOffset().isZero())
4745 return false;
4746 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4747 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4748 if (!LHSExpr || !RHSExpr)
4749 return false;
4750 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4751 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4752 if (!LHSAddrExpr || !RHSAddrExpr)
4753 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004754 // Make sure both labels come from the same function.
4755 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4756 RHSAddrExpr->getLabel()->getDeclContext())
4757 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004758 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4759 return true;
4760 }
4761
Eli Friedman42edd0d2009-03-24 01:14:50 +00004762 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00004763 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00004764 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004765
Richard Smithc49bd112011-10-28 17:51:58 +00004766 APSInt &LHS = LHSVal.getInt();
4767 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00004768
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004769 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00004770 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004771 return Error(E);
Richard Smith7b48a292012-02-01 05:53:12 +00004772 case BO_Mul:
4773 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4774 LHS.getBitWidth() * 2,
4775 std::multiplies<APSInt>()), E);
4776 case BO_Add:
4777 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4778 LHS.getBitWidth() + 1,
4779 std::plus<APSInt>()), E);
4780 case BO_Sub:
4781 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4782 LHS.getBitWidth() + 1,
4783 std::minus<APSInt>()), E);
Richard Smithc49bd112011-10-28 17:51:58 +00004784 case BO_And: return Success(LHS & RHS, E);
4785 case BO_Xor: return Success(LHS ^ RHS, E);
4786 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004787 case BO_Div:
John McCall2de56d12010-08-25 11:45:40 +00004788 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00004789 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004790 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith3df61302012-01-31 23:24:19 +00004791 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is not
4792 // actually undefined behavior in C++11 due to a language defect.
4793 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4794 LHS.isSigned() && LHS.isMinSignedValue())
4795 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4796 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004797 case BO_Shl: {
Richard Smith789f9b62012-01-31 04:08:20 +00004798 // During constant-folding, a negative shift is an opposite shift. Such a
4799 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004800 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004801 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004802 RHS = -RHS;
4803 goto shift_right;
4804 }
4805
4806 shift_left:
Richard Smith789f9b62012-01-31 04:08:20 +00004807 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4808 // shifted type.
4809 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4810 if (SA != RHS) {
4811 CCEDiag(E, diag::note_constexpr_large_shift)
4812 << RHS << E->getType() << LHS.getBitWidth();
4813 } else if (LHS.isSigned()) {
4814 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
Richard Smith925d8e72012-02-08 06:14:53 +00004815 // operand, and must not overflow the corresponding unsigned type.
Richard Smith789f9b62012-01-31 04:08:20 +00004816 if (LHS.isNegative())
4817 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
Richard Smith925d8e72012-02-08 06:14:53 +00004818 else if (LHS.countLeadingZeros() < SA)
4819 CCEDiag(E, diag::note_constexpr_lshift_discards);
Richard Smith789f9b62012-01-31 04:08:20 +00004820 }
4821
Richard Smithc49bd112011-10-28 17:51:58 +00004822 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004823 }
John McCall2de56d12010-08-25 11:45:40 +00004824 case BO_Shr: {
Richard Smith789f9b62012-01-31 04:08:20 +00004825 // During constant-folding, a negative shift is an opposite shift. Such a
4826 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004827 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004828 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004829 RHS = -RHS;
4830 goto shift_left;
4831 }
4832
4833 shift_right:
Richard Smith789f9b62012-01-31 04:08:20 +00004834 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4835 // shifted type.
4836 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4837 if (SA != RHS)
4838 CCEDiag(E, diag::note_constexpr_large_shift)
4839 << RHS << E->getType() << LHS.getBitWidth();
4840
Richard Smithc49bd112011-10-28 17:51:58 +00004841 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004842 }
Mike Stump1eb44332009-09-09 15:08:12 +00004843
Richard Smithc49bd112011-10-28 17:51:58 +00004844 case BO_LT: return Success(LHS < RHS, E);
4845 case BO_GT: return Success(LHS > RHS, E);
4846 case BO_LE: return Success(LHS <= RHS, E);
4847 case BO_GE: return Success(LHS >= RHS, E);
4848 case BO_EQ: return Success(LHS == RHS, E);
4849 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00004850 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004851}
4852
Ken Dyck8b752f12010-01-27 17:10:57 +00004853CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00004854 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4855 // the result is the size of the referenced type."
4856 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4857 // result shall be the alignment of the referenced type."
4858 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4859 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00004860
4861 // __alignof is defined to return the preferred alignment.
4862 return Info.Ctx.toCharUnitsFromBits(
4863 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00004864}
4865
Ken Dyck8b752f12010-01-27 17:10:57 +00004866CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00004867 E = E->IgnoreParens();
4868
4869 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00004870 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00004871 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004872 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4873 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00004874
Chris Lattneraf707ab2009-01-24 21:53:27 +00004875 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004876 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4877 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00004878
Chris Lattnere9feb472009-01-24 21:09:06 +00004879 return GetAlignOfType(E->getType());
4880}
4881
4882
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004883/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4884/// a result as the expression's type.
4885bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4886 const UnaryExprOrTypeTraitExpr *E) {
4887 switch(E->getKind()) {
4888 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00004889 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004890 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004891 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004892 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004893 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004894
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004895 case UETT_VecStep: {
4896 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00004897
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004898 if (Ty->isVectorType()) {
4899 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00004900
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004901 // The vec_step built-in functions that take a 3-component
4902 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4903 if (n == 3)
4904 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00004905
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004906 return Success(n, E);
4907 } else
4908 return Success(1, E);
4909 }
4910
4911 case UETT_SizeOf: {
4912 QualType SrcTy = E->getTypeOfArgument();
4913 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4914 // the result is the size of the referenced type."
4915 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4916 // result shall be the alignment of the referenced type."
4917 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4918 SrcTy = Ref->getPointeeType();
4919
Richard Smith180f4792011-11-10 06:34:14 +00004920 CharUnits Sizeof;
4921 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004922 return false;
Richard Smith180f4792011-11-10 06:34:14 +00004923 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004924 }
4925 }
4926
4927 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00004928}
4929
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004930bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004931 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004932 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004933 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004934 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004935 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004936 for (unsigned i = 0; i != n; ++i) {
4937 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4938 switch (ON.getKind()) {
4939 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004940 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004941 APSInt IdxResult;
4942 if (!EvaluateInteger(Idx, IdxResult, Info))
4943 return false;
4944 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4945 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004946 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004947 CurrentType = AT->getElementType();
4948 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4949 Result += IdxResult.getSExtValue() * ElementSize;
4950 break;
4951 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004952
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004953 case OffsetOfExpr::OffsetOfNode::Field: {
4954 FieldDecl *MemberDecl = ON.getField();
4955 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004956 if (!RT)
4957 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004958 RecordDecl *RD = RT->getDecl();
4959 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00004960 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004961 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00004962 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004963 CurrentType = MemberDecl->getType().getNonReferenceType();
4964 break;
4965 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004966
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004967 case OffsetOfExpr::OffsetOfNode::Identifier:
4968 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00004969
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004970 case OffsetOfExpr::OffsetOfNode::Base: {
4971 CXXBaseSpecifier *BaseSpec = ON.getBase();
4972 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00004973 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004974
4975 // Find the layout of the class whose base we are looking into.
4976 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004977 if (!RT)
4978 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004979 RecordDecl *RD = RT->getDecl();
4980 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4981
4982 // Find the base class itself.
4983 CurrentType = BaseSpec->getType();
4984 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4985 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004986 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004987
4988 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00004989 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004990 break;
4991 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004992 }
4993 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004994 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004995}
4996
Chris Lattnerb542afe2008-07-11 19:10:17 +00004997bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004998 switch (E->getOpcode()) {
4999 default:
5000 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5001 // See C99 6.6p3.
5002 return Error(E);
5003 case UO_Extension:
5004 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5005 // If so, we could clear the diagnostic ID.
5006 return Visit(E->getSubExpr());
5007 case UO_Plus:
5008 // The result is just the value.
5009 return Visit(E->getSubExpr());
5010 case UO_Minus: {
5011 if (!Visit(E->getSubExpr()))
5012 return false;
5013 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00005014 const APSInt &Value = Result.getInt();
5015 if (Value.isSigned() && Value.isMinSignedValue())
5016 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5017 E->getType());
5018 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00005019 }
5020 case UO_Not: {
5021 if (!Visit(E->getSubExpr()))
5022 return false;
5023 if (!Result.isInt()) return Error(E);
5024 return Success(~Result.getInt(), E);
5025 }
5026 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00005027 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00005028 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00005029 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005030 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00005031 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005032 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005033}
Mike Stump1eb44332009-09-09 15:08:12 +00005034
Chris Lattner732b2232008-07-12 01:15:53 +00005035/// HandleCast - This is used to evaluate implicit or explicit casts where the
5036/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005037bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5038 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00005039 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00005040 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00005041
Eli Friedman46a52322011-03-25 00:43:55 +00005042 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00005043 case CK_BaseToDerived:
5044 case CK_DerivedToBase:
5045 case CK_UncheckedDerivedToBase:
5046 case CK_Dynamic:
5047 case CK_ToUnion:
5048 case CK_ArrayToPointerDecay:
5049 case CK_FunctionToPointerDecay:
5050 case CK_NullToPointer:
5051 case CK_NullToMemberPointer:
5052 case CK_BaseToDerivedMemberPointer:
5053 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00005054 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00005055 case CK_ConstructorConversion:
5056 case CK_IntegralToPointer:
5057 case CK_ToVoid:
5058 case CK_VectorSplat:
5059 case CK_IntegralToFloating:
5060 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005061 case CK_CPointerToObjCPointerCast:
5062 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005063 case CK_AnyPointerToBlockPointerCast:
5064 case CK_ObjCObjectLValueCast:
5065 case CK_FloatingRealToComplex:
5066 case CK_FloatingComplexToReal:
5067 case CK_FloatingComplexCast:
5068 case CK_FloatingComplexToIntegralComplex:
5069 case CK_IntegralRealToComplex:
5070 case CK_IntegralComplexCast:
5071 case CK_IntegralComplexToFloatingComplex:
5072 llvm_unreachable("invalid cast kind for integral value");
5073
Eli Friedmane50c2972011-03-25 19:07:11 +00005074 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005075 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005076 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00005077 case CK_ARCProduceObject:
5078 case CK_ARCConsumeObject:
5079 case CK_ARCReclaimReturnedObject:
5080 case CK_ARCExtendBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00005081 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005082
Richard Smith7d580a42012-01-17 21:17:26 +00005083 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00005084 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005085 case CK_AtomicToNonAtomic:
5086 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00005087 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005088 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005089
5090 case CK_MemberPointerToBoolean:
5091 case CK_PointerToBoolean:
5092 case CK_IntegralToBoolean:
5093 case CK_FloatingToBoolean:
5094 case CK_FloatingComplexToBoolean:
5095 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005096 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00005097 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00005098 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005099 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005100 }
5101
Eli Friedman46a52322011-03-25 00:43:55 +00005102 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00005103 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005104 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00005105
Eli Friedmanbe265702009-02-20 01:15:07 +00005106 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00005107 // Allow casts of address-of-label differences if they are no-ops
5108 // or narrowing. (The narrowing case isn't actually guaranteed to
5109 // be constant-evaluatable except in some narrow cases which are hard
5110 // to detect here. We let it through on the assumption the user knows
5111 // what they are doing.)
5112 if (Result.isAddrLabelDiff())
5113 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005114 // Only allow casts of lvalues if they are lossless.
5115 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5116 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005117
Richard Smithf72fccf2012-01-30 22:27:01 +00005118 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5119 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005120 }
Mike Stump1eb44332009-09-09 15:08:12 +00005121
Eli Friedman46a52322011-03-25 00:43:55 +00005122 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005123 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5124
John McCallefdb83e2010-05-07 21:00:08 +00005125 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005126 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005127 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005128
Daniel Dunbardd211642009-02-19 22:24:01 +00005129 if (LV.getLValueBase()) {
5130 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005131 // FIXME: Allow a larger integer size than the pointer size, and allow
5132 // narrowing back down to pointer width in subsequent integral casts.
5133 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005134 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005135 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005136
Richard Smithb755a9d2011-11-16 07:18:12 +00005137 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005138 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005139 return true;
5140 }
5141
Ken Dycka7305832010-01-15 12:37:54 +00005142 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5143 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005144 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005145 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005146
Eli Friedman46a52322011-03-25 00:43:55 +00005147 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005148 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005149 if (!EvaluateComplex(SubExpr, C, Info))
5150 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005151 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005152 }
Eli Friedman2217c872009-02-22 11:46:18 +00005153
Eli Friedman46a52322011-03-25 00:43:55 +00005154 case CK_FloatingToIntegral: {
5155 APFloat F(0.0);
5156 if (!EvaluateFloat(SubExpr, F, Info))
5157 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005158
Richard Smithc1c5f272011-12-13 06:39:58 +00005159 APSInt Value;
5160 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5161 return false;
5162 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005163 }
5164 }
Mike Stump1eb44332009-09-09 15:08:12 +00005165
Eli Friedman46a52322011-03-25 00:43:55 +00005166 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005167}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005168
Eli Friedman722c7172009-02-28 03:59:05 +00005169bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5170 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005171 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005172 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5173 return false;
5174 if (!LV.isComplexInt())
5175 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005176 return Success(LV.getComplexIntReal(), E);
5177 }
5178
5179 return Visit(E->getSubExpr());
5180}
5181
Eli Friedman664a1042009-02-27 04:45:43 +00005182bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005183 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005184 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005185 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5186 return false;
5187 if (!LV.isComplexInt())
5188 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005189 return Success(LV.getComplexIntImag(), E);
5190 }
5191
Richard Smith8327fad2011-10-24 18:44:57 +00005192 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005193 return Success(0, E);
5194}
5195
Douglas Gregoree8aff02011-01-04 17:33:58 +00005196bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5197 return Success(E->getPackLength(), E);
5198}
5199
Sebastian Redl295995c2010-09-10 20:55:47 +00005200bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5201 return Success(E->getValue(), E);
5202}
5203
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005204//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005205// Float Evaluation
5206//===----------------------------------------------------------------------===//
5207
5208namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005209class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005210 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005211 APFloat &Result;
5212public:
5213 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005214 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005215
Richard Smith47a1eed2011-10-29 20:57:55 +00005216 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005217 Result = V.getFloat();
5218 return true;
5219 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005220
Richard Smith51201882011-12-30 21:15:51 +00005221 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005222 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5223 return true;
5224 }
5225
Chris Lattner019f4e82008-10-06 05:28:25 +00005226 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005227
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005228 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005229 bool VisitBinaryOperator(const BinaryOperator *E);
5230 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005231 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005232
John McCallabd3a852010-05-07 22:08:54 +00005233 bool VisitUnaryReal(const UnaryOperator *E);
5234 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005235
Richard Smith51201882011-12-30 21:15:51 +00005236 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005237};
5238} // end anonymous namespace
5239
5240static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005241 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005242 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005243}
5244
Jay Foad4ba2a172011-01-12 09:06:06 +00005245static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005246 QualType ResultTy,
5247 const Expr *Arg,
5248 bool SNaN,
5249 llvm::APFloat &Result) {
5250 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5251 if (!S) return false;
5252
5253 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5254
5255 llvm::APInt fill;
5256
5257 // Treat empty strings as if they were zero.
5258 if (S->getString().empty())
5259 fill = llvm::APInt(32, 0);
5260 else if (S->getString().getAsInteger(0, fill))
5261 return false;
5262
5263 if (SNaN)
5264 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5265 else
5266 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5267 return true;
5268}
5269
Chris Lattner019f4e82008-10-06 05:28:25 +00005270bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005271 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005272 default:
5273 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5274
Chris Lattner019f4e82008-10-06 05:28:25 +00005275 case Builtin::BI__builtin_huge_val:
5276 case Builtin::BI__builtin_huge_valf:
5277 case Builtin::BI__builtin_huge_vall:
5278 case Builtin::BI__builtin_inf:
5279 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005280 case Builtin::BI__builtin_infl: {
5281 const llvm::fltSemantics &Sem =
5282 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005283 Result = llvm::APFloat::getInf(Sem);
5284 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005285 }
Mike Stump1eb44332009-09-09 15:08:12 +00005286
John McCalldb7b72a2010-02-28 13:00:19 +00005287 case Builtin::BI__builtin_nans:
5288 case Builtin::BI__builtin_nansf:
5289 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005290 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5291 true, Result))
5292 return Error(E);
5293 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005294
Chris Lattner9e621712008-10-06 06:31:58 +00005295 case Builtin::BI__builtin_nan:
5296 case Builtin::BI__builtin_nanf:
5297 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005298 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005299 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005300 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5301 false, Result))
5302 return Error(E);
5303 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005304
5305 case Builtin::BI__builtin_fabs:
5306 case Builtin::BI__builtin_fabsf:
5307 case Builtin::BI__builtin_fabsl:
5308 if (!EvaluateFloat(E->getArg(0), Result, Info))
5309 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005310
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005311 if (Result.isNegative())
5312 Result.changeSign();
5313 return true;
5314
Mike Stump1eb44332009-09-09 15:08:12 +00005315 case Builtin::BI__builtin_copysign:
5316 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005317 case Builtin::BI__builtin_copysignl: {
5318 APFloat RHS(0.);
5319 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5320 !EvaluateFloat(E->getArg(1), RHS, Info))
5321 return false;
5322 Result.copySign(RHS);
5323 return true;
5324 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005325 }
5326}
5327
John McCallabd3a852010-05-07 22:08:54 +00005328bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005329 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5330 ComplexValue CV;
5331 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5332 return false;
5333 Result = CV.FloatReal;
5334 return true;
5335 }
5336
5337 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005338}
5339
5340bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005341 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5342 ComplexValue CV;
5343 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5344 return false;
5345 Result = CV.FloatImag;
5346 return true;
5347 }
5348
Richard Smith8327fad2011-10-24 18:44:57 +00005349 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005350 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5351 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005352 return true;
5353}
5354
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005355bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005356 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005357 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005358 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005359 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005360 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005361 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5362 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005363 Result.changeSign();
5364 return true;
5365 }
5366}
Chris Lattner019f4e82008-10-06 05:28:25 +00005367
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005368bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005369 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5370 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005371
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005372 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005373 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5374 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005375 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005376 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005377 return false;
5378
5379 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005380 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005381 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005382 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005383 break;
John McCall2de56d12010-08-25 11:45:40 +00005384 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005385 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005386 break;
John McCall2de56d12010-08-25 11:45:40 +00005387 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005388 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005389 break;
John McCall2de56d12010-08-25 11:45:40 +00005390 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005391 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005392 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005393 }
Richard Smith7b48a292012-02-01 05:53:12 +00005394
5395 if (Result.isInfinity() || Result.isNaN())
5396 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5397 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005398}
5399
5400bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5401 Result = E->getValue();
5402 return true;
5403}
5404
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005405bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5406 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005407
Eli Friedman2a523ee2011-03-25 00:54:52 +00005408 switch (E->getCastKind()) {
5409 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005410 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005411
5412 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005413 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005414 return EvaluateInteger(SubExpr, IntResult, Info) &&
5415 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5416 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005417 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005418
5419 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005420 if (!Visit(SubExpr))
5421 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005422 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5423 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005424 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005425
Eli Friedman2a523ee2011-03-25 00:54:52 +00005426 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005427 ComplexValue V;
5428 if (!EvaluateComplex(SubExpr, V, Info))
5429 return false;
5430 Result = V.getComplexFloatReal();
5431 return true;
5432 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005433 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005434}
5435
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005436//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005437// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005438//===----------------------------------------------------------------------===//
5439
5440namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005441class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005442 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005443 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005444
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005445public:
John McCallf4cf1a12010-05-07 17:22:02 +00005446 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005447 : ExprEvaluatorBaseTy(info), Result(Result) {}
5448
Richard Smith47a1eed2011-10-29 20:57:55 +00005449 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005450 Result.setFrom(V);
5451 return true;
5452 }
Mike Stump1eb44332009-09-09 15:08:12 +00005453
Eli Friedman7ead5c72012-01-10 04:58:17 +00005454 bool ZeroInitialization(const Expr *E);
5455
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005456 //===--------------------------------------------------------------------===//
5457 // Visitor Methods
5458 //===--------------------------------------------------------------------===//
5459
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005460 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005461 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005462 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005463 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005464 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005465};
5466} // end anonymous namespace
5467
John McCallf4cf1a12010-05-07 17:22:02 +00005468static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5469 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005470 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005471 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005472}
5473
Eli Friedman7ead5c72012-01-10 04:58:17 +00005474bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005475 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005476 if (ElemTy->isRealFloatingType()) {
5477 Result.makeComplexFloat();
5478 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5479 Result.FloatReal = Zero;
5480 Result.FloatImag = Zero;
5481 } else {
5482 Result.makeComplexInt();
5483 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5484 Result.IntReal = Zero;
5485 Result.IntImag = Zero;
5486 }
5487 return true;
5488}
5489
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005490bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5491 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005492
5493 if (SubExpr->getType()->isRealFloatingType()) {
5494 Result.makeComplexFloat();
5495 APFloat &Imag = Result.FloatImag;
5496 if (!EvaluateFloat(SubExpr, Imag, Info))
5497 return false;
5498
5499 Result.FloatReal = APFloat(Imag.getSemantics());
5500 return true;
5501 } else {
5502 assert(SubExpr->getType()->isIntegerType() &&
5503 "Unexpected imaginary literal.");
5504
5505 Result.makeComplexInt();
5506 APSInt &Imag = Result.IntImag;
5507 if (!EvaluateInteger(SubExpr, Imag, Info))
5508 return false;
5509
5510 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5511 return true;
5512 }
5513}
5514
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005515bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005516
John McCall8786da72010-12-14 17:51:41 +00005517 switch (E->getCastKind()) {
5518 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005519 case CK_BaseToDerived:
5520 case CK_DerivedToBase:
5521 case CK_UncheckedDerivedToBase:
5522 case CK_Dynamic:
5523 case CK_ToUnion:
5524 case CK_ArrayToPointerDecay:
5525 case CK_FunctionToPointerDecay:
5526 case CK_NullToPointer:
5527 case CK_NullToMemberPointer:
5528 case CK_BaseToDerivedMemberPointer:
5529 case CK_DerivedToBaseMemberPointer:
5530 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00005531 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00005532 case CK_ConstructorConversion:
5533 case CK_IntegralToPointer:
5534 case CK_PointerToIntegral:
5535 case CK_PointerToBoolean:
5536 case CK_ToVoid:
5537 case CK_VectorSplat:
5538 case CK_IntegralCast:
5539 case CK_IntegralToBoolean:
5540 case CK_IntegralToFloating:
5541 case CK_FloatingToIntegral:
5542 case CK_FloatingToBoolean:
5543 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005544 case CK_CPointerToObjCPointerCast:
5545 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005546 case CK_AnyPointerToBlockPointerCast:
5547 case CK_ObjCObjectLValueCast:
5548 case CK_FloatingComplexToReal:
5549 case CK_FloatingComplexToBoolean:
5550 case CK_IntegralComplexToReal:
5551 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005552 case CK_ARCProduceObject:
5553 case CK_ARCConsumeObject:
5554 case CK_ARCReclaimReturnedObject:
5555 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005556 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005557
John McCall8786da72010-12-14 17:51:41 +00005558 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005559 case CK_AtomicToNonAtomic:
5560 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005561 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005562 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005563
5564 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005565 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005566 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005567 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005568
5569 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005570 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005571 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005572 return false;
5573
John McCall8786da72010-12-14 17:51:41 +00005574 Result.makeComplexFloat();
5575 Result.FloatImag = APFloat(Real.getSemantics());
5576 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005577 }
5578
John McCall8786da72010-12-14 17:51:41 +00005579 case CK_FloatingComplexCast: {
5580 if (!Visit(E->getSubExpr()))
5581 return false;
5582
5583 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5584 QualType From
5585 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5586
Richard Smithc1c5f272011-12-13 06:39:58 +00005587 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5588 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005589 }
5590
5591 case CK_FloatingComplexToIntegralComplex: {
5592 if (!Visit(E->getSubExpr()))
5593 return false;
5594
5595 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5596 QualType From
5597 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5598 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005599 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5600 To, Result.IntReal) &&
5601 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5602 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005603 }
5604
5605 case CK_IntegralRealToComplex: {
5606 APSInt &Real = Result.IntReal;
5607 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5608 return false;
5609
5610 Result.makeComplexInt();
5611 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5612 return true;
5613 }
5614
5615 case CK_IntegralComplexCast: {
5616 if (!Visit(E->getSubExpr()))
5617 return false;
5618
5619 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5620 QualType From
5621 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5622
Richard Smithf72fccf2012-01-30 22:27:01 +00005623 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5624 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005625 return true;
5626 }
5627
5628 case CK_IntegralComplexToFloatingComplex: {
5629 if (!Visit(E->getSubExpr()))
5630 return false;
5631
5632 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5633 QualType From
5634 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5635 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005636 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5637 To, Result.FloatReal) &&
5638 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5639 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005640 }
5641 }
5642
5643 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005644}
5645
John McCallf4cf1a12010-05-07 17:22:02 +00005646bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005647 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005648 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5649
Richard Smith745f5142012-01-27 01:14:48 +00005650 bool LHSOK = Visit(E->getLHS());
5651 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005652 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005653
John McCallf4cf1a12010-05-07 17:22:02 +00005654 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005655 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005656 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005657
Daniel Dunbar3f279872009-01-29 01:32:56 +00005658 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5659 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005660 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005661 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005662 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005663 if (Result.isComplexFloat()) {
5664 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5665 APFloat::rmNearestTiesToEven);
5666 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5667 APFloat::rmNearestTiesToEven);
5668 } else {
5669 Result.getComplexIntReal() += RHS.getComplexIntReal();
5670 Result.getComplexIntImag() += RHS.getComplexIntImag();
5671 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005672 break;
John McCall2de56d12010-08-25 11:45:40 +00005673 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005674 if (Result.isComplexFloat()) {
5675 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5676 APFloat::rmNearestTiesToEven);
5677 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5678 APFloat::rmNearestTiesToEven);
5679 } else {
5680 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5681 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5682 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005683 break;
John McCall2de56d12010-08-25 11:45:40 +00005684 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005685 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005686 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005687 APFloat &LHS_r = LHS.getComplexFloatReal();
5688 APFloat &LHS_i = LHS.getComplexFloatImag();
5689 APFloat &RHS_r = RHS.getComplexFloatReal();
5690 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005691
Daniel Dunbar3f279872009-01-29 01:32:56 +00005692 APFloat Tmp = LHS_r;
5693 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5694 Result.getComplexFloatReal() = Tmp;
5695 Tmp = LHS_i;
5696 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5697 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5698
5699 Tmp = LHS_r;
5700 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5701 Result.getComplexFloatImag() = Tmp;
5702 Tmp = LHS_i;
5703 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5704 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5705 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005706 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005707 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005708 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5709 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00005710 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005711 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5712 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5713 }
5714 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005715 case BO_Div:
5716 if (Result.isComplexFloat()) {
5717 ComplexValue LHS = Result;
5718 APFloat &LHS_r = LHS.getComplexFloatReal();
5719 APFloat &LHS_i = LHS.getComplexFloatImag();
5720 APFloat &RHS_r = RHS.getComplexFloatReal();
5721 APFloat &RHS_i = RHS.getComplexFloatImag();
5722 APFloat &Res_r = Result.getComplexFloatReal();
5723 APFloat &Res_i = Result.getComplexFloatImag();
5724
5725 APFloat Den = RHS_r;
5726 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5727 APFloat Tmp = RHS_i;
5728 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5729 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5730
5731 Res_r = LHS_r;
5732 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5733 Tmp = LHS_i;
5734 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5735 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5736 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5737
5738 Res_i = LHS_i;
5739 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5740 Tmp = LHS_r;
5741 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5742 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5743 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5744 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00005745 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5746 return Error(E, diag::note_expr_divide_by_zero);
5747
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005748 ComplexValue LHS = Result;
5749 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5750 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5751 Result.getComplexIntReal() =
5752 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5753 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5754 Result.getComplexIntImag() =
5755 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5756 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5757 }
5758 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005759 }
5760
John McCallf4cf1a12010-05-07 17:22:02 +00005761 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005762}
5763
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005764bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5765 // Get the operand value into 'Result'.
5766 if (!Visit(E->getSubExpr()))
5767 return false;
5768
5769 switch (E->getOpcode()) {
5770 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00005771 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005772 case UO_Extension:
5773 return true;
5774 case UO_Plus:
5775 // The result is always just the subexpr.
5776 return true;
5777 case UO_Minus:
5778 if (Result.isComplexFloat()) {
5779 Result.getComplexFloatReal().changeSign();
5780 Result.getComplexFloatImag().changeSign();
5781 }
5782 else {
5783 Result.getComplexIntReal() = -Result.getComplexIntReal();
5784 Result.getComplexIntImag() = -Result.getComplexIntImag();
5785 }
5786 return true;
5787 case UO_Not:
5788 if (Result.isComplexFloat())
5789 Result.getComplexFloatImag().changeSign();
5790 else
5791 Result.getComplexIntImag() = -Result.getComplexIntImag();
5792 return true;
5793 }
5794}
5795
Eli Friedman7ead5c72012-01-10 04:58:17 +00005796bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5797 if (E->getNumInits() == 2) {
5798 if (E->getType()->isComplexType()) {
5799 Result.makeComplexFloat();
5800 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5801 return false;
5802 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5803 return false;
5804 } else {
5805 Result.makeComplexInt();
5806 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5807 return false;
5808 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5809 return false;
5810 }
5811 return true;
5812 }
5813 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5814}
5815
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005816//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00005817// Void expression evaluation, primarily for a cast to void on the LHS of a
5818// comma operator
5819//===----------------------------------------------------------------------===//
5820
5821namespace {
5822class VoidExprEvaluator
5823 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5824public:
5825 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5826
5827 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00005828
5829 bool VisitCastExpr(const CastExpr *E) {
5830 switch (E->getCastKind()) {
5831 default:
5832 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5833 case CK_ToVoid:
5834 VisitIgnoredValue(E->getSubExpr());
5835 return true;
5836 }
5837 }
5838};
5839} // end anonymous namespace
5840
5841static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5842 assert(E->isRValue() && E->getType()->isVoidType());
5843 return VoidExprEvaluator(Info).Visit(E);
5844}
5845
5846//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00005847// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005848//===----------------------------------------------------------------------===//
5849
Richard Smith47a1eed2011-10-29 20:57:55 +00005850static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00005851 // In C, function designators are not lvalues, but we evaluate them as if they
5852 // are.
5853 if (E->isGLValue() || E->getType()->isFunctionType()) {
5854 LValue LV;
5855 if (!EvaluateLValue(E, LV, Info))
5856 return false;
5857 LV.moveInto(Result);
5858 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005859 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00005860 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00005861 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005862 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005863 return false;
John McCallefdb83e2010-05-07 21:00:08 +00005864 } else if (E->getType()->hasPointerRepresentation()) {
5865 LValue LV;
5866 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005867 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005868 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00005869 } else if (E->getType()->isRealFloatingType()) {
5870 llvm::APFloat F(0.0);
5871 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005872 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00005873 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00005874 } else if (E->getType()->isAnyComplexType()) {
5875 ComplexValue C;
5876 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005877 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005878 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00005879 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005880 MemberPtr P;
5881 if (!EvaluateMemberPointer(E, P, Info))
5882 return false;
5883 P.moveInto(Result);
5884 return true;
Richard Smith51201882011-12-30 21:15:51 +00005885 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005886 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00005887 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00005888 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00005889 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005890 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00005891 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005892 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00005893 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00005894 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5895 return false;
5896 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00005897 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00005898 if (Info.getLangOpts().CPlusPlus0x)
5899 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5900 << E->getType();
5901 else
5902 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00005903 if (!EvaluateVoid(E, Info))
5904 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005905 } else if (Info.getLangOpts().CPlusPlus0x) {
5906 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5907 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005908 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00005909 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00005910 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005911 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005912
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00005913 return true;
5914}
5915
Richard Smith83587db2012-02-15 02:18:13 +00005916/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
5917/// cases, the in-place evaluation is essential, since later initializers for
5918/// an object can indirectly refer to subobjects which were initialized earlier.
5919static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
5920 const Expr *E, CheckConstantExpressionKind CCEK,
5921 bool AllowNonLiteralTypes) {
Richard Smith7ca48502012-02-13 22:16:19 +00005922 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smith51201882011-12-30 21:15:51 +00005923 return false;
5924
5925 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00005926 // Evaluate arrays and record types in-place, so that later initializers can
5927 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00005928 if (E->getType()->isArrayType())
5929 return EvaluateArray(E, This, Result, Info);
5930 else if (E->getType()->isRecordType())
5931 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00005932 }
5933
5934 // For any other type, in-place evaluation is unimportant.
5935 CCValue CoreConstResult;
Richard Smith83587db2012-02-15 02:18:13 +00005936 if (!Evaluate(CoreConstResult, Info, E))
5937 return false;
5938 Result = CoreConstResult.toAPValue();
5939 return true;
Richard Smith69c2c502011-11-04 05:33:44 +00005940}
5941
Richard Smithf48fdb02011-12-09 22:58:01 +00005942/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5943/// lvalue-to-rvalue cast if it is an lvalue.
5944static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00005945 if (!CheckLiteralType(Info, E))
5946 return false;
5947
Richard Smithf48fdb02011-12-09 22:58:01 +00005948 CCValue Value;
5949 if (!::Evaluate(Value, Info, E))
5950 return false;
5951
5952 if (E->isGLValue()) {
5953 LValue LV;
5954 LV.setFrom(Value);
5955 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
5956 return false;
5957 }
5958
5959 // Check this core constant expression is a constant expression, and if so,
5960 // convert it to one.
Richard Smith83587db2012-02-15 02:18:13 +00005961 Result = Value.toAPValue();
5962 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf48fdb02011-12-09 22:58:01 +00005963}
Richard Smithc49bd112011-10-28 17:51:58 +00005964
Richard Smith51f47082011-10-29 00:50:52 +00005965/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00005966/// any crazy technique (that has nothing to do with language standards) that
5967/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00005968/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
5969/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00005970bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00005971 // Fast-path evaluations of integer literals, since we sometimes see files
5972 // containing vast quantities of these.
5973 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
5974 Result.Val = APValue(APSInt(L->getValue(),
5975 L->getType()->isUnsignedIntegerType()));
5976 return true;
5977 }
5978
Richard Smith2d6a5672012-01-14 04:30:29 +00005979 // FIXME: Evaluating values of large array and record types can cause
5980 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00005981 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5982 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00005983 return false;
5984
Richard Smithf48fdb02011-12-09 22:58:01 +00005985 EvalInfo Info(Ctx, Result);
5986 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00005987}
5988
Jay Foad4ba2a172011-01-12 09:06:06 +00005989bool Expr::EvaluateAsBooleanCondition(bool &Result,
5990 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00005991 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00005992 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithb4e85ed2012-01-06 16:39:00 +00005993 HandleConversionToBool(CCValue(const_cast<ASTContext&>(Ctx),
5994 Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00005995 Result);
John McCallcd7a4452010-01-05 23:42:56 +00005996}
5997
Richard Smith80d4b552011-12-28 19:48:30 +00005998bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
5999 SideEffectsKind AllowSideEffects) const {
6000 if (!getType()->isIntegralOrEnumerationType())
6001 return false;
6002
Richard Smithc49bd112011-10-28 17:51:58 +00006003 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00006004 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6005 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00006006 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006007
Richard Smithc49bd112011-10-28 17:51:58 +00006008 Result = ExprResult.Val.getInt();
6009 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006010}
6011
Jay Foad4ba2a172011-01-12 09:06:06 +00006012bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00006013 EvalInfo Info(Ctx, Result);
6014
John McCallefdb83e2010-05-07 21:00:08 +00006015 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006016 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6017 !CheckLValueConstantExpression(Info, getExprLoc(),
6018 Ctx.getLValueReferenceType(getType()), LV))
6019 return false;
6020
6021 CCValue Tmp;
6022 LV.moveInto(Tmp);
6023 Result.Val = Tmp.toAPValue();
6024 return true;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00006025}
6026
Richard Smith099e7f62011-12-19 06:19:21 +00006027bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6028 const VarDecl *VD,
6029 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00006030 // FIXME: Evaluating initializers for large array and record types can cause
6031 // performance problems. Only do so in C++11 for now.
6032 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
6033 !Ctx.getLangOptions().CPlusPlus0x)
6034 return false;
6035
Richard Smith099e7f62011-12-19 06:19:21 +00006036 Expr::EvalStatus EStatus;
6037 EStatus.Diag = &Notes;
6038
6039 EvalInfo InitInfo(Ctx, EStatus);
6040 InitInfo.setEvaluatingDecl(VD, Value);
6041
6042 LValue LVal;
6043 LVal.set(VD);
6044
Richard Smith51201882011-12-30 21:15:51 +00006045 // C++11 [basic.start.init]p2:
6046 // Variables with static storage duration or thread storage duration shall be
6047 // zero-initialized before any other initialization takes place.
6048 // This behavior is not present in C.
6049 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
6050 !VD->getType()->isReferenceType()) {
6051 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith83587db2012-02-15 02:18:13 +00006052 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6053 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00006054 return false;
6055 }
6056
Richard Smith83587db2012-02-15 02:18:13 +00006057 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6058 /*AllowNonLiteralTypes=*/true) ||
6059 EStatus.HasSideEffects)
6060 return false;
6061
6062 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6063 Value);
Richard Smith099e7f62011-12-19 06:19:21 +00006064}
6065
Richard Smith51f47082011-10-29 00:50:52 +00006066/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6067/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00006068bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00006069 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00006070 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00006071}
Anders Carlsson51fe9962008-11-22 21:04:56 +00006072
Jay Foad4ba2a172011-01-12 09:06:06 +00006073bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00006074 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00006075}
6076
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006077APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006078 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00006079 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00006080 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00006081 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006082 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00006083
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006084 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00006085}
John McCalld905f5a2010-05-07 05:32:02 +00006086
Abramo Bagnarae17a6432010-05-14 17:07:14 +00006087 bool Expr::EvalResult::isGlobalLValue() const {
6088 assert(Val.isLValue());
6089 return IsGlobalLValue(Val.getLValueBase());
6090 }
6091
6092
John McCalld905f5a2010-05-07 05:32:02 +00006093/// isIntegerConstantExpr - this recursive routine will test if an expression is
6094/// an integer constant expression.
6095
6096/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6097/// comma, etc
6098///
6099/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
6100/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
6101/// cast+dereference.
6102
6103// CheckICE - This function does the fundamental ICE checking: the returned
6104// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
6105// Note that to reduce code duplication, this helper does no evaluation
6106// itself; the caller checks whether the expression is evaluatable, and
6107// in the rare cases where CheckICE actually cares about the evaluated
6108// value, it calls into Evalute.
6109//
6110// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00006111// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00006112// 1: This expression is not an ICE, but if it isn't evaluated, it's
6113// a legal subexpression for an ICE. This return value is used to handle
6114// the comma operator in C99 mode.
6115// 2: This expression is not an ICE, and is not a legal subexpression for one.
6116
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006117namespace {
6118
John McCalld905f5a2010-05-07 05:32:02 +00006119struct ICEDiag {
6120 unsigned Val;
6121 SourceLocation Loc;
6122
6123 public:
6124 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6125 ICEDiag() : Val(0) {}
6126};
6127
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006128}
6129
6130static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00006131
6132static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6133 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006134 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00006135 !EVResult.Val.isInt()) {
6136 return ICEDiag(2, E->getLocStart());
6137 }
6138 return NoDiag();
6139}
6140
6141static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6142 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00006143 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00006144 return ICEDiag(2, E->getLocStart());
6145 }
6146
6147 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006148#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006149#define STMT(Node, Base) case Expr::Node##Class:
6150#define EXPR(Node, Base)
6151#include "clang/AST/StmtNodes.inc"
6152 case Expr::PredefinedExprClass:
6153 case Expr::FloatingLiteralClass:
6154 case Expr::ImaginaryLiteralClass:
6155 case Expr::StringLiteralClass:
6156 case Expr::ArraySubscriptExprClass:
6157 case Expr::MemberExprClass:
6158 case Expr::CompoundAssignOperatorClass:
6159 case Expr::CompoundLiteralExprClass:
6160 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006161 case Expr::DesignatedInitExprClass:
6162 case Expr::ImplicitValueInitExprClass:
6163 case Expr::ParenListExprClass:
6164 case Expr::VAArgExprClass:
6165 case Expr::AddrLabelExprClass:
6166 case Expr::StmtExprClass:
6167 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006168 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006169 case Expr::CXXDynamicCastExprClass:
6170 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006171 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006172 case Expr::CXXNullPtrLiteralExprClass:
6173 case Expr::CXXThisExprClass:
6174 case Expr::CXXThrowExprClass:
6175 case Expr::CXXNewExprClass:
6176 case Expr::CXXDeleteExprClass:
6177 case Expr::CXXPseudoDestructorExprClass:
6178 case Expr::UnresolvedLookupExprClass:
6179 case Expr::DependentScopeDeclRefExprClass:
6180 case Expr::CXXConstructExprClass:
6181 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006182 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006183 case Expr::CXXTemporaryObjectExprClass:
6184 case Expr::CXXUnresolvedConstructExprClass:
6185 case Expr::CXXDependentScopeMemberExprClass:
6186 case Expr::UnresolvedMemberExprClass:
6187 case Expr::ObjCStringLiteralClass:
6188 case Expr::ObjCEncodeExprClass:
6189 case Expr::ObjCMessageExprClass:
6190 case Expr::ObjCSelectorExprClass:
6191 case Expr::ObjCProtocolExprClass:
6192 case Expr::ObjCIvarRefExprClass:
6193 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006194 case Expr::ObjCIsaExprClass:
6195 case Expr::ShuffleVectorExprClass:
6196 case Expr::BlockExprClass:
6197 case Expr::BlockDeclRefExprClass:
6198 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006199 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006200 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006201 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006202 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006203 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006204 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006205 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006206 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006207 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00006208 case Expr::LambdaExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006209 return ICEDiag(2, E->getLocStart());
6210
Douglas Gregoree8aff02011-01-04 17:33:58 +00006211 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006212 case Expr::GNUNullExprClass:
6213 // GCC considers the GNU __null value to be an integral constant expression.
6214 return NoDiag();
6215
John McCall91a57552011-07-15 05:09:51 +00006216 case Expr::SubstNonTypeTemplateParmExprClass:
6217 return
6218 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6219
John McCalld905f5a2010-05-07 05:32:02 +00006220 case Expr::ParenExprClass:
6221 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006222 case Expr::GenericSelectionExprClass:
6223 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006224 case Expr::IntegerLiteralClass:
6225 case Expr::CharacterLiteralClass:
6226 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006227 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006228 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006229 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006230 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006231 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006232 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006233 return NoDiag();
6234 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006235 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006236 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6237 // constant expressions, but they can never be ICEs because an ICE cannot
6238 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006239 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006240 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006241 return CheckEvalInICE(E, Ctx);
6242 return ICEDiag(2, E->getLocStart());
6243 }
6244 case Expr::DeclRefExprClass:
6245 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6246 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00006247 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006248 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
6249
6250 // Parameter variables are never constants. Without this check,
6251 // getAnyInitializer() can find a default argument, which leads
6252 // to chaos.
6253 if (isa<ParmVarDecl>(D))
6254 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6255
6256 // C++ 7.1.5.1p2
6257 // A variable of non-volatile const-qualified integral or enumeration
6258 // type initialized by an ICE can be used in ICEs.
6259 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006260 if (!Dcl->getType()->isIntegralOrEnumerationType())
6261 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6262
Richard Smith099e7f62011-12-19 06:19:21 +00006263 const VarDecl *VD;
6264 // Look for a declaration of this variable that has an initializer, and
6265 // check whether it is an ICE.
6266 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6267 return NoDiag();
6268 else
6269 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006270 }
6271 }
6272 return ICEDiag(2, E->getLocStart());
6273 case Expr::UnaryOperatorClass: {
6274 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6275 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006276 case UO_PostInc:
6277 case UO_PostDec:
6278 case UO_PreInc:
6279 case UO_PreDec:
6280 case UO_AddrOf:
6281 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006282 // C99 6.6/3 allows increment and decrement within unevaluated
6283 // subexpressions of constant expressions, but they can never be ICEs
6284 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006285 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006286 case UO_Extension:
6287 case UO_LNot:
6288 case UO_Plus:
6289 case UO_Minus:
6290 case UO_Not:
6291 case UO_Real:
6292 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006293 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006294 }
6295
6296 // OffsetOf falls through here.
6297 }
6298 case Expr::OffsetOfExprClass: {
6299 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00006300 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00006301 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00006302 // compliance: we should warn earlier for offsetof expressions with
6303 // array subscripts that aren't ICEs, and if the array subscripts
6304 // are ICEs, the value of the offsetof must be an integer constant.
6305 return CheckEvalInICE(E, Ctx);
6306 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006307 case Expr::UnaryExprOrTypeTraitExprClass: {
6308 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6309 if ((Exp->getKind() == UETT_SizeOf) &&
6310 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00006311 return ICEDiag(2, E->getLocStart());
6312 return NoDiag();
6313 }
6314 case Expr::BinaryOperatorClass: {
6315 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6316 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006317 case BO_PtrMemD:
6318 case BO_PtrMemI:
6319 case BO_Assign:
6320 case BO_MulAssign:
6321 case BO_DivAssign:
6322 case BO_RemAssign:
6323 case BO_AddAssign:
6324 case BO_SubAssign:
6325 case BO_ShlAssign:
6326 case BO_ShrAssign:
6327 case BO_AndAssign:
6328 case BO_XorAssign:
6329 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006330 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6331 // constant expressions, but they can never be ICEs because an ICE cannot
6332 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006333 return ICEDiag(2, E->getLocStart());
6334
John McCall2de56d12010-08-25 11:45:40 +00006335 case BO_Mul:
6336 case BO_Div:
6337 case BO_Rem:
6338 case BO_Add:
6339 case BO_Sub:
6340 case BO_Shl:
6341 case BO_Shr:
6342 case BO_LT:
6343 case BO_GT:
6344 case BO_LE:
6345 case BO_GE:
6346 case BO_EQ:
6347 case BO_NE:
6348 case BO_And:
6349 case BO_Xor:
6350 case BO_Or:
6351 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006352 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6353 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006354 if (Exp->getOpcode() == BO_Div ||
6355 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006356 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006357 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006358 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006359 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006360 if (REval == 0)
6361 return ICEDiag(1, E->getLocStart());
6362 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006363 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006364 if (LEval.isMinSignedValue())
6365 return ICEDiag(1, E->getLocStart());
6366 }
6367 }
6368 }
John McCall2de56d12010-08-25 11:45:40 +00006369 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00006370 if (Ctx.getLangOptions().C99) {
6371 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6372 // if it isn't evaluated.
6373 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6374 return ICEDiag(1, E->getLocStart());
6375 } else {
6376 // In both C89 and C++, commas in ICEs are illegal.
6377 return ICEDiag(2, E->getLocStart());
6378 }
6379 }
6380 if (LHSResult.Val >= RHSResult.Val)
6381 return LHSResult;
6382 return RHSResult;
6383 }
John McCall2de56d12010-08-25 11:45:40 +00006384 case BO_LAnd:
6385 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006386 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6387 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6388 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6389 // Rare case where the RHS has a comma "side-effect"; we need
6390 // to actually check the condition to see whether the side
6391 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006392 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006393 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006394 return RHSResult;
6395 return NoDiag();
6396 }
6397
6398 if (LHSResult.Val >= RHSResult.Val)
6399 return LHSResult;
6400 return RHSResult;
6401 }
6402 }
6403 }
6404 case Expr::ImplicitCastExprClass:
6405 case Expr::CStyleCastExprClass:
6406 case Expr::CXXFunctionalCastExprClass:
6407 case Expr::CXXStaticCastExprClass:
6408 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006409 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006410 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006411 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006412 if (isa<ExplicitCastExpr>(E)) {
6413 if (const FloatingLiteral *FL
6414 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6415 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6416 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6417 APSInt IgnoredVal(DestWidth, !DestSigned);
6418 bool Ignored;
6419 // If the value does not fit in the destination type, the behavior is
6420 // undefined, so we are not required to treat it as a constant
6421 // expression.
6422 if (FL->getValue().convertToInteger(IgnoredVal,
6423 llvm::APFloat::rmTowardZero,
6424 &Ignored) & APFloat::opInvalidOp)
6425 return ICEDiag(2, E->getLocStart());
6426 return NoDiag();
6427 }
6428 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006429 switch (cast<CastExpr>(E)->getCastKind()) {
6430 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006431 case CK_AtomicToNonAtomic:
6432 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006433 case CK_NoOp:
6434 case CK_IntegralToBoolean:
6435 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006436 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006437 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006438 return ICEDiag(2, E->getLocStart());
6439 }
John McCalld905f5a2010-05-07 05:32:02 +00006440 }
John McCall56ca35d2011-02-17 10:25:35 +00006441 case Expr::BinaryConditionalOperatorClass: {
6442 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6443 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6444 if (CommonResult.Val == 2) return CommonResult;
6445 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6446 if (FalseResult.Val == 2) return FalseResult;
6447 if (CommonResult.Val == 1) return CommonResult;
6448 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006449 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006450 return FalseResult;
6451 }
John McCalld905f5a2010-05-07 05:32:02 +00006452 case Expr::ConditionalOperatorClass: {
6453 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6454 // If the condition (ignoring parens) is a __builtin_constant_p call,
6455 // then only the true side is actually considered in an integer constant
6456 // expression, and it is fully evaluated. This is an important GNU
6457 // extension. See GCC PR38377 for discussion.
6458 if (const CallExpr *CallCE
6459 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006460 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6461 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006462 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006463 if (CondResult.Val == 2)
6464 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006465
Richard Smithf48fdb02011-12-09 22:58:01 +00006466 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6467 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006468
John McCalld905f5a2010-05-07 05:32:02 +00006469 if (TrueResult.Val == 2)
6470 return TrueResult;
6471 if (FalseResult.Val == 2)
6472 return FalseResult;
6473 if (CondResult.Val == 1)
6474 return CondResult;
6475 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6476 return NoDiag();
6477 // Rare case where the diagnostics depend on which side is evaluated
6478 // Note that if we get here, CondResult is 0, and at least one of
6479 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006480 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006481 return FalseResult;
6482 }
6483 return TrueResult;
6484 }
6485 case Expr::CXXDefaultArgExprClass:
6486 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6487 case Expr::ChooseExprClass: {
6488 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6489 }
6490 }
6491
David Blaikie30263482012-01-20 21:50:17 +00006492 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006493}
6494
Richard Smithf48fdb02011-12-09 22:58:01 +00006495/// Evaluate an expression as a C++11 integral constant expression.
6496static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6497 const Expr *E,
6498 llvm::APSInt *Value,
6499 SourceLocation *Loc) {
6500 if (!E->getType()->isIntegralOrEnumerationType()) {
6501 if (Loc) *Loc = E->getExprLoc();
6502 return false;
6503 }
6504
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006505 APValue Result;
6506 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006507 return false;
6508
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006509 assert(Result.isInt() && "pointer cast to int is not an ICE");
6510 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006511 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006512}
6513
Richard Smithdd1f29b2011-12-12 09:28:41 +00006514bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00006515 if (Ctx.getLangOptions().CPlusPlus0x)
6516 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6517
John McCalld905f5a2010-05-07 05:32:02 +00006518 ICEDiag d = CheckICE(this, Ctx);
6519 if (d.Val != 0) {
6520 if (Loc) *Loc = d.Loc;
6521 return false;
6522 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006523 return true;
6524}
6525
6526bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6527 SourceLocation *Loc, bool isEvaluated) const {
6528 if (Ctx.getLangOptions().CPlusPlus0x)
6529 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6530
6531 if (!isIntegerConstantExpr(Ctx, Loc))
6532 return false;
6533 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006534 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006535 return true;
6536}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006537
Richard Smith70488e22012-02-14 21:38:30 +00006538bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
6539 return CheckICE(this, Ctx).Val == 0;
6540}
6541
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006542bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6543 SourceLocation *Loc) const {
6544 // We support this checking in C++98 mode in order to diagnose compatibility
6545 // issues.
6546 assert(Ctx.getLangOptions().CPlusPlus);
6547
Richard Smith70488e22012-02-14 21:38:30 +00006548 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006549 Expr::EvalStatus Status;
6550 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6551 Status.Diag = &Diags;
6552 EvalInfo Info(Ctx, Status);
6553
6554 APValue Scratch;
6555 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6556
6557 if (!Diags.empty()) {
6558 IsConstExpr = false;
6559 if (Loc) *Loc = Diags[0].first;
6560 } else if (!IsConstExpr) {
6561 // FIXME: This shouldn't happen.
6562 if (Loc) *Loc = getExprLoc();
6563 }
6564
6565 return IsConstExpr;
6566}
Richard Smith745f5142012-01-27 01:14:48 +00006567
6568bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6569 llvm::SmallVectorImpl<
6570 PartialDiagnosticAt> &Diags) {
6571 // FIXME: It would be useful to check constexpr function templates, but at the
6572 // moment the constant expression evaluator cannot cope with the non-rigorous
6573 // ASTs which we build for dependent expressions.
6574 if (FD->isDependentContext())
6575 return true;
6576
6577 Expr::EvalStatus Status;
6578 Status.Diag = &Diags;
6579
6580 EvalInfo Info(FD->getASTContext(), Status);
6581 Info.CheckingPotentialConstantExpression = true;
6582
6583 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6584 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6585
6586 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6587 // is a temporary being used as the 'this' pointer.
6588 LValue This;
6589 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smith83587db2012-02-15 02:18:13 +00006590 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith745f5142012-01-27 01:14:48 +00006591
Richard Smith745f5142012-01-27 01:14:48 +00006592 ArrayRef<const Expr*> Args;
6593
6594 SourceLocation Loc = FD->getLocation();
6595
6596 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Richard Smith83587db2012-02-15 02:18:13 +00006597 APValue Scratch;
Richard Smith745f5142012-01-27 01:14:48 +00006598 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith83587db2012-02-15 02:18:13 +00006599 } else {
6600 CCValue Scratch;
Richard Smith745f5142012-01-27 01:14:48 +00006601 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6602 Args, FD->getBody(), Info, Scratch);
Richard Smith83587db2012-02-15 02:18:13 +00006603 }
Richard Smith745f5142012-01-27 01:14:48 +00006604
6605 return Diags.empty();
6606}