blob: 6cbb69dae575147922066a4daae4e6146c6e402e [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
Richard Smith745f5142012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
26// (under the C++11 rules only, at the moment), or, if folding failed too,
27// why the expression could not be folded.
28//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlssonc44eec62008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000038#include "clang/AST/CharUnits.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000039#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000040#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000041#include "clang/AST/TypeLoc.h"
Chris Lattner500d3292009-01-29 05:15:15 +000042#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000043#include "clang/AST/Expr.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000044#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000045#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000046#include "llvm/ADT/SmallString.h"
Mike Stump4572bab2009-05-30 03:56:50 +000047#include <cstring>
Richard Smith7b48a292012-02-01 05:53:12 +000048#include <functional>
Mike Stump4572bab2009-05-30 03:56:50 +000049
Anders Carlssonc44eec62008-07-03 04:20:39 +000050using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000051using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000052using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000053
Richard Smith83587db2012-02-15 02:18:13 +000054static bool IsGlobalLValue(APValue::LValueBase B);
55
John McCallf4cf1a12010-05-07 17:22:02 +000056namespace {
Richard Smith180f4792011-11-10 06:34:14 +000057 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000058 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000059 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000060
Richard Smith83587db2012-02-15 02:18:13 +000061 static QualType getType(APValue::LValueBase B) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +000062 if (!B) return QualType();
63 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
64 return D->getType();
65 return B.get<const Expr*>()->getType();
66 }
67
Richard Smith180f4792011-11-10 06:34:14 +000068 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smithf15fda02012-02-02 01:16:57 +000069 /// field or base class.
Richard Smith83587db2012-02-15 02:18:13 +000070 static
Richard Smithf15fda02012-02-02 01:16:57 +000071 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smith180f4792011-11-10 06:34:14 +000072 APValue::BaseOrMemberType Value;
73 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smithf15fda02012-02-02 01:16:57 +000074 return Value;
75 }
76
77 /// Get an LValue path entry, which is known to not be an array index, as a
78 /// field declaration.
Richard Smith83587db2012-02-15 02:18:13 +000079 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000080 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000081 }
82 /// Get an LValue path entry, which is known to not be an array index, as a
83 /// base class declaration.
Richard Smith83587db2012-02-15 02:18:13 +000084 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000085 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000086 }
87 /// Determine whether this LValue path entry for a base class names a virtual
88 /// base class.
Richard Smith83587db2012-02-15 02:18:13 +000089 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000090 return getAsBaseOrMember(E).getInt();
Richard Smith180f4792011-11-10 06:34:14 +000091 }
92
Richard Smithb4e85ed2012-01-06 16:39:00 +000093 /// Find the path length and type of the most-derived subobject in the given
94 /// path, and find the size of the containing array, if any.
95 static
96 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
97 ArrayRef<APValue::LValuePathEntry> Path,
98 uint64_t &ArraySize, QualType &Type) {
99 unsigned MostDerivedLength = 0;
100 Type = Base;
Richard Smith9a17a682011-11-07 05:07:52 +0000101 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000102 if (Type->isArrayType()) {
103 const ConstantArrayType *CAT =
104 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
105 Type = CAT->getElementType();
106 ArraySize = CAT->getSize().getZExtValue();
107 MostDerivedLength = I + 1;
108 } else if (const FieldDecl *FD = getAsField(Path[I])) {
109 Type = FD->getType();
110 ArraySize = 0;
111 MostDerivedLength = I + 1;
112 } else {
Richard Smith9a17a682011-11-07 05:07:52 +0000113 // Path[I] describes a base class.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000114 ArraySize = 0;
115 }
Richard Smith9a17a682011-11-07 05:07:52 +0000116 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000117 return MostDerivedLength;
Richard Smith9a17a682011-11-07 05:07:52 +0000118 }
119
Richard Smithb4e85ed2012-01-06 16:39:00 +0000120 // The order of this enum is important for diagnostics.
121 enum CheckSubobjectKind {
Richard Smithb04035a2012-02-01 02:39:43 +0000122 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
123 CSK_This
Richard Smithb4e85ed2012-01-06 16:39:00 +0000124 };
125
Richard Smith0a3bdb62011-11-04 02:25:55 +0000126 /// A path from a glvalue to a subobject of that glvalue.
127 struct SubobjectDesignator {
128 /// True if the subobject was named in a manner not supported by C++11. Such
129 /// lvalues can still be folded, but they are not core constant expressions
130 /// and we cannot perform lvalue-to-rvalue conversions on them.
131 bool Invalid : 1;
132
Richard Smithb4e85ed2012-01-06 16:39:00 +0000133 /// Is this a pointer one past the end of an object?
134 bool IsOnePastTheEnd : 1;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000135
Richard Smithb4e85ed2012-01-06 16:39:00 +0000136 /// The length of the path to the most-derived object of which this is a
137 /// subobject.
138 unsigned MostDerivedPathLength : 30;
139
140 /// The size of the array of which the most-derived object is an element, or
141 /// 0 if the most-derived object is not an array element.
142 uint64_t MostDerivedArraySize;
143
144 /// The type of the most derived object referred to by this address.
145 QualType MostDerivedType;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000146
Richard Smith9a17a682011-11-07 05:07:52 +0000147 typedef APValue::LValuePathEntry PathEntry;
148
Richard Smith0a3bdb62011-11-04 02:25:55 +0000149 /// The entries on the path from the glvalue to the designated subobject.
150 SmallVector<PathEntry, 8> Entries;
151
Richard Smithb4e85ed2012-01-06 16:39:00 +0000152 SubobjectDesignator() : Invalid(true) {}
Richard Smith0a3bdb62011-11-04 02:25:55 +0000153
Richard Smithb4e85ed2012-01-06 16:39:00 +0000154 explicit SubobjectDesignator(QualType T)
155 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
156 MostDerivedArraySize(0), MostDerivedType(T) {}
157
158 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
159 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
160 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith9a17a682011-11-07 05:07:52 +0000161 if (!Invalid) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000162 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000163 ArrayRef<PathEntry> VEntries = V.getLValuePath();
164 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
165 if (V.getLValueBase())
Richard Smithb4e85ed2012-01-06 16:39:00 +0000166 MostDerivedPathLength =
167 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
168 V.getLValuePath(), MostDerivedArraySize,
169 MostDerivedType);
Richard Smith9a17a682011-11-07 05:07:52 +0000170 }
171 }
172
Richard Smith0a3bdb62011-11-04 02:25:55 +0000173 void setInvalid() {
174 Invalid = true;
175 Entries.clear();
176 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000177
178 /// Determine whether this is a one-past-the-end pointer.
179 bool isOnePastTheEnd() const {
180 if (IsOnePastTheEnd)
181 return true;
182 if (MostDerivedArraySize &&
183 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
184 return true;
185 return false;
186 }
187
188 /// Check that this refers to a valid subobject.
189 bool isValidSubobject() const {
190 if (Invalid)
191 return false;
192 return !isOnePastTheEnd();
193 }
194 /// Check that this refers to a valid subobject, and if not, produce a
195 /// relevant diagnostic and set the designator as invalid.
196 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
197
198 /// Update this designator to refer to the first element within this array.
199 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000200 PathEntry Entry;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000201 Entry.ArrayIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000202 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000203
204 // This is a most-derived object.
205 MostDerivedType = CAT->getElementType();
206 MostDerivedArraySize = CAT->getSize().getZExtValue();
207 MostDerivedPathLength = Entries.size();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000208 }
209 /// Update this designator to refer to the given base or member of this
210 /// object.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000211 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000212 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000213 APValue::BaseOrMemberType Value(D, Virtual);
214 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000215 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000216
217 // If this isn't a base class, it's a new most-derived object.
218 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
219 MostDerivedType = FD->getType();
220 MostDerivedArraySize = 0;
221 MostDerivedPathLength = Entries.size();
222 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000223 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000224 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000225 /// Add N to the address of this subobject.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000226 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000227 if (Invalid) return;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000228 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith9a17a682011-11-07 05:07:52 +0000229 Entries.back().ArrayIndex += N;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000230 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
231 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
232 setInvalid();
233 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000234 return;
235 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000236 // [expr.add]p4: For the purposes of these operators, a pointer to a
237 // nonarray object behaves the same as a pointer to the first element of
238 // an array of length one with the type of the object as its element type.
239 if (IsOnePastTheEnd && N == (uint64_t)-1)
240 IsOnePastTheEnd = false;
241 else if (!IsOnePastTheEnd && N == 1)
242 IsOnePastTheEnd = true;
243 else if (N != 0) {
244 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000245 setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000246 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000247 }
248 };
249
Richard Smith47a1eed2011-10-29 20:57:55 +0000250 /// A core constant value. This can be the value of any constant expression,
251 /// or a pointer or reference to a non-static object or function parameter.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000252 ///
253 /// For an LValue, the base and offset are stored in the APValue subobject,
254 /// but the other information is stored in the SubobjectDesignator. For all
255 /// other value kinds, the value is stored directly in the APValue subobject.
Richard Smith47a1eed2011-10-29 20:57:55 +0000256 class CCValue : public APValue {
257 typedef llvm::APSInt APSInt;
258 typedef llvm::APFloat APFloat;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000259 /// If the value is a reference or pointer, this is a description of how the
260 /// subobject was specified.
261 SubobjectDesignator Designator;
Richard Smith47a1eed2011-10-29 20:57:55 +0000262 public:
Richard Smith177dce72011-11-01 16:57:24 +0000263 struct GlobalValue {};
264
Richard Smith47a1eed2011-10-29 20:57:55 +0000265 CCValue() {}
266 explicit CCValue(const APSInt &I) : APValue(I) {}
267 explicit CCValue(const APFloat &F) : APValue(F) {}
268 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
269 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
270 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smith83587db2012-02-15 02:18:13 +0000271 CCValue(const CCValue &V) : APValue(V), Designator(V.Designator) {}
272 CCValue(LValueBase B, const CharUnits &O, unsigned I,
Richard Smith0a3bdb62011-11-04 02:25:55 +0000273 const SubobjectDesignator &D) :
Richard Smith83587db2012-02-15 02:18:13 +0000274 APValue(B, O, APValue::NoLValuePath(), I), Designator(D) {}
Richard Smithb4e85ed2012-01-06 16:39:00 +0000275 CCValue(ASTContext &Ctx, const APValue &V, GlobalValue) :
Richard Smith83587db2012-02-15 02:18:13 +0000276 APValue(V), Designator(Ctx, V) {
277 }
Richard Smithe24f5fc2011-11-17 22:56:20 +0000278 CCValue(const ValueDecl *D, bool IsDerivedMember,
279 ArrayRef<const CXXRecordDecl*> Path) :
280 APValue(D, IsDerivedMember, Path) {}
Eli Friedman65639282012-01-04 23:13:47 +0000281 CCValue(const AddrLabelExpr* LHSExpr, const AddrLabelExpr* RHSExpr) :
282 APValue(LHSExpr, RHSExpr) {}
Richard Smith47a1eed2011-10-29 20:57:55 +0000283
Richard Smith0a3bdb62011-11-04 02:25:55 +0000284 SubobjectDesignator &getLValueDesignator() {
285 assert(getKind() == LValue);
286 return Designator;
287 }
288 const SubobjectDesignator &getLValueDesignator() const {
289 return const_cast<CCValue*>(this)->getLValueDesignator();
290 }
Richard Smith83587db2012-02-15 02:18:13 +0000291 APValue toAPValue() const {
292 if (!isLValue())
293 return *this;
294
295 if (Designator.Invalid) {
296 // This is not a core constant expression. An appropriate diagnostic
297 // will have already been produced.
298 return APValue(getLValueBase(), getLValueOffset(),
299 APValue::NoLValuePath(), getLValueCallIndex());
300 }
301
302 return APValue(getLValueBase(), getLValueOffset(),
303 Designator.Entries, Designator.IsOnePastTheEnd,
304 getLValueCallIndex());
305 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000306 };
307
Richard Smithd0dccea2011-10-28 22:34:42 +0000308 /// A stack frame in the constexpr call stack.
309 struct CallStackFrame {
310 EvalInfo &Info;
311
312 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000313 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000314
Richard Smith08d6e032011-12-16 19:06:07 +0000315 /// CallLoc - The location of the call expression for this call.
316 SourceLocation CallLoc;
317
318 /// Callee - The function which was called.
319 const FunctionDecl *Callee;
320
Richard Smith83587db2012-02-15 02:18:13 +0000321 /// Index - The call index of this call.
322 unsigned Index;
323
Richard Smith180f4792011-11-10 06:34:14 +0000324 /// This - The binding for the this pointer in this call, if any.
325 const LValue *This;
326
Richard Smithd0dccea2011-10-28 22:34:42 +0000327 /// ParmBindings - Parameter bindings for this function call, indexed by
328 /// parameters' function scope indices.
Richard Smith47a1eed2011-10-29 20:57:55 +0000329 const CCValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000330
Richard Smithbd552ef2011-10-31 05:52:43 +0000331 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
332 typedef MapTy::const_iterator temp_iterator;
333 /// Temporaries - Temporary lvalues materialized within this stack frame.
334 MapTy Temporaries;
335
Richard Smith08d6e032011-12-16 19:06:07 +0000336 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
337 const FunctionDecl *Callee, const LValue *This,
Richard Smith180f4792011-11-10 06:34:14 +0000338 const CCValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000339 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000340 };
341
Richard Smithdd1f29b2011-12-12 09:28:41 +0000342 /// A partial diagnostic which we might know in advance that we are not going
343 /// to emit.
344 class OptionalDiagnostic {
345 PartialDiagnostic *Diag;
346
347 public:
348 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
349
350 template<typename T>
351 OptionalDiagnostic &operator<<(const T &v) {
352 if (Diag)
353 *Diag << v;
354 return *this;
355 }
Richard Smith789f9b62012-01-31 04:08:20 +0000356
357 OptionalDiagnostic &operator<<(const APSInt &I) {
358 if (Diag) {
359 llvm::SmallVector<char, 32> Buffer;
360 I.toString(Buffer);
361 *Diag << StringRef(Buffer.data(), Buffer.size());
362 }
363 return *this;
364 }
365
366 OptionalDiagnostic &operator<<(const APFloat &F) {
367 if (Diag) {
368 llvm::SmallVector<char, 32> Buffer;
369 F.toString(Buffer);
370 *Diag << StringRef(Buffer.data(), Buffer.size());
371 }
372 return *this;
373 }
Richard Smithdd1f29b2011-12-12 09:28:41 +0000374 };
375
Richard Smith83587db2012-02-15 02:18:13 +0000376 /// EvalInfo - This is a private struct used by the evaluator to capture
377 /// information about a subexpression as it is folded. It retains information
378 /// about the AST context, but also maintains information about the folded
379 /// expression.
380 ///
381 /// If an expression could be evaluated, it is still possible it is not a C
382 /// "integer constant expression" or constant expression. If not, this struct
383 /// captures information about how and why not.
384 ///
385 /// One bit of information passed *into* the request for constant folding
386 /// indicates whether the subexpression is "evaluated" or not according to C
387 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
388 /// evaluate the expression regardless of what the RHS is, but C only allows
389 /// certain things in certain situations.
Richard Smithbd552ef2011-10-31 05:52:43 +0000390 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000391 ASTContext &Ctx;
Richard Smithbd552ef2011-10-31 05:52:43 +0000392
393 /// EvalStatus - Contains information about the evaluation.
394 Expr::EvalStatus &EvalStatus;
395
396 /// CurrentCall - The top of the constexpr call stack.
397 CallStackFrame *CurrentCall;
398
Richard Smithbd552ef2011-10-31 05:52:43 +0000399 /// CallStackDepth - The number of calls in the call stack right now.
400 unsigned CallStackDepth;
401
Richard Smith83587db2012-02-15 02:18:13 +0000402 /// NextCallIndex - The next call index to assign.
403 unsigned NextCallIndex;
404
Richard Smithbd552ef2011-10-31 05:52:43 +0000405 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
406 /// OpaqueValues - Values used as the common expression in a
407 /// BinaryConditionalOperator.
408 MapTy OpaqueValues;
409
410 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000411 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000412 CallStackFrame BottomFrame;
413
Richard Smith180f4792011-11-10 06:34:14 +0000414 /// EvaluatingDecl - This is the declaration whose initializer is being
415 /// evaluated, if any.
416 const VarDecl *EvaluatingDecl;
417
418 /// EvaluatingDeclValue - This is the value being constructed for the
419 /// declaration whose initializer is being evaluated, if any.
420 APValue *EvaluatingDeclValue;
421
Richard Smithc1c5f272011-12-13 06:39:58 +0000422 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
423 /// notes attached to it will also be stored, otherwise they will not be.
424 bool HasActiveDiagnostic;
425
Richard Smith745f5142012-01-27 01:14:48 +0000426 /// CheckingPotentialConstantExpression - Are we checking whether the
427 /// expression is a potential constant expression? If so, some diagnostics
428 /// are suppressed.
429 bool CheckingPotentialConstantExpression;
430
Richard Smithbd552ef2011-10-31 05:52:43 +0000431
432 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000433 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith83587db2012-02-15 02:18:13 +0000434 CallStackDepth(0), NextCallIndex(1),
435 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith745f5142012-01-27 01:14:48 +0000436 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
437 CheckingPotentialConstantExpression(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000438
Richard Smithbd552ef2011-10-31 05:52:43 +0000439 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
440 MapTy::const_iterator i = OpaqueValues.find(e);
441 if (i == OpaqueValues.end()) return 0;
442 return &i->second;
443 }
444
Richard Smith180f4792011-11-10 06:34:14 +0000445 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
446 EvaluatingDecl = VD;
447 EvaluatingDeclValue = &Value;
448 }
449
Richard Smithc18c4232011-11-21 19:36:32 +0000450 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
451
Richard Smithc1c5f272011-12-13 06:39:58 +0000452 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000453 // Don't perform any constexpr calls (other than the call we're checking)
454 // when checking a potential constant expression.
455 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
456 return false;
Richard Smith83587db2012-02-15 02:18:13 +0000457 if (NextCallIndex == 0) {
458 // NextCallIndex has wrapped around.
459 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
460 return false;
461 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000462 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
463 return true;
464 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
465 << getLangOpts().ConstexprCallDepth;
466 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000467 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000468
Richard Smith83587db2012-02-15 02:18:13 +0000469 CallStackFrame *getCallFrame(unsigned CallIndex) {
470 assert(CallIndex && "no call index in getCallFrame");
471 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
472 // be null in this loop.
473 CallStackFrame *Frame = CurrentCall;
474 while (Frame->Index > CallIndex)
475 Frame = Frame->Caller;
476 return (Frame->Index == CallIndex) ? Frame : 0;
477 }
478
Richard Smithc1c5f272011-12-13 06:39:58 +0000479 private:
480 /// Add a diagnostic to the diagnostics list.
481 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
482 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
483 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
484 return EvalStatus.Diag->back().second;
485 }
486
Richard Smith08d6e032011-12-16 19:06:07 +0000487 /// Add notes containing a call stack to the current point of evaluation.
488 void addCallStack(unsigned Limit);
489
Richard Smithc1c5f272011-12-13 06:39:58 +0000490 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000491 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000492 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
493 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000494 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000495 // If we have a prior diagnostic, it will be noting that the expression
496 // isn't a constant expression. This diagnostic is more important.
497 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000498 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000499 unsigned CallStackNotes = CallStackDepth - 1;
500 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
501 if (Limit)
502 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000503 if (CheckingPotentialConstantExpression)
504 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000505
Richard Smithc1c5f272011-12-13 06:39:58 +0000506 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000507 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000508 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
509 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000510 if (!CheckingPotentialConstantExpression)
511 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000512 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000513 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000514 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000515 return OptionalDiagnostic();
516 }
517
518 /// Diagnose that the evaluation does not produce a C++11 core constant
519 /// expression.
Richard Smith7098cbd2011-12-21 05:04:46 +0000520 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
521 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000522 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000523 // Don't override a previous diagnostic.
524 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
525 return OptionalDiagnostic();
Richard Smithc1c5f272011-12-13 06:39:58 +0000526 return Diag(Loc, DiagId, ExtraNotes);
527 }
528
529 /// Add a note to a prior diagnostic.
530 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
531 if (!HasActiveDiagnostic)
532 return OptionalDiagnostic();
533 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000534 }
Richard Smith099e7f62011-12-19 06:19:21 +0000535
536 /// Add a stack of notes to a prior diagnostic.
537 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
538 if (HasActiveDiagnostic) {
539 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
540 Diags.begin(), Diags.end());
541 }
542 }
Richard Smith745f5142012-01-27 01:14:48 +0000543
544 /// Should we continue evaluation as much as possible after encountering a
545 /// construct which can't be folded?
546 bool keepEvaluatingAfterFailure() {
Richard Smith74e1ad92012-02-16 02:46:34 +0000547 return CheckingPotentialConstantExpression &&
548 EvalStatus.Diag && EvalStatus.Diag->empty();
Richard Smith745f5142012-01-27 01:14:48 +0000549 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000550 };
Richard Smithf15fda02012-02-02 01:16:57 +0000551
552 /// Object used to treat all foldable expressions as constant expressions.
553 struct FoldConstant {
554 bool Enabled;
555
556 explicit FoldConstant(EvalInfo &Info)
557 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
558 !Info.EvalStatus.HasSideEffects) {
559 }
560 // Treat the value we've computed since this object was created as constant.
561 void Fold(EvalInfo &Info) {
562 if (Enabled && !Info.EvalStatus.Diag->empty() &&
563 !Info.EvalStatus.HasSideEffects)
564 Info.EvalStatus.Diag->clear();
565 }
566 };
Richard Smith74e1ad92012-02-16 02:46:34 +0000567
568 /// RAII object used to suppress diagnostics and side-effects from a
569 /// speculative evaluation.
570 class SpeculativeEvaluationRAII {
571 EvalInfo &Info;
572 Expr::EvalStatus Old;
573
574 public:
575 SpeculativeEvaluationRAII(EvalInfo &Info,
576 llvm::SmallVectorImpl<PartialDiagnosticAt>
577 *NewDiag = 0)
578 : Info(Info), Old(Info.EvalStatus) {
579 Info.EvalStatus.Diag = NewDiag;
580 }
581 ~SpeculativeEvaluationRAII() {
582 Info.EvalStatus = Old;
583 }
584 };
Richard Smith08d6e032011-12-16 19:06:07 +0000585}
Richard Smithbd552ef2011-10-31 05:52:43 +0000586
Richard Smithb4e85ed2012-01-06 16:39:00 +0000587bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
588 CheckSubobjectKind CSK) {
589 if (Invalid)
590 return false;
591 if (isOnePastTheEnd()) {
592 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_past_end_subobject)
593 << CSK;
594 setInvalid();
595 return false;
596 }
597 return true;
598}
599
600void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
601 const Expr *E, uint64_t N) {
602 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
603 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
604 << static_cast<int>(N) << /*array*/ 0
605 << static_cast<unsigned>(MostDerivedArraySize);
606 else
607 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
608 << static_cast<int>(N) << /*non-array*/ 1;
609 setInvalid();
610}
611
Richard Smith08d6e032011-12-16 19:06:07 +0000612CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
613 const FunctionDecl *Callee, const LValue *This,
614 const CCValue *Arguments)
615 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smith83587db2012-02-15 02:18:13 +0000616 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smith08d6e032011-12-16 19:06:07 +0000617 Info.CurrentCall = this;
618 ++Info.CallStackDepth;
619}
620
621CallStackFrame::~CallStackFrame() {
622 assert(Info.CurrentCall == this && "calls retired out of order");
623 --Info.CallStackDepth;
624 Info.CurrentCall = Caller;
625}
626
627/// Produce a string describing the given constexpr call.
628static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
629 unsigned ArgIndex = 0;
630 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith5ba73e12012-02-04 00:33:54 +0000631 !isa<CXXConstructorDecl>(Frame->Callee) &&
632 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smith08d6e032011-12-16 19:06:07 +0000633
634 if (!IsMemberCall)
635 Out << *Frame->Callee << '(';
636
637 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
638 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumi5fe31222012-01-26 09:37:36 +0000639 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smith08d6e032011-12-16 19:06:07 +0000640 Out << ", ";
641
642 const ParmVarDecl *Param = *I;
643 const CCValue &Arg = Frame->Arguments[ArgIndex];
644 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
645 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
646 else {
Richard Smith83587db2012-02-15 02:18:13 +0000647 // Convert the CCValue to an APValue without checking for constantness.
Richard Smith08d6e032011-12-16 19:06:07 +0000648 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
649 Arg.getLValueDesignator().Entries,
Richard Smith83587db2012-02-15 02:18:13 +0000650 Arg.getLValueDesignator().IsOnePastTheEnd,
651 Arg.getLValueCallIndex());
Richard Smith08d6e032011-12-16 19:06:07 +0000652 Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
653 }
654
655 if (ArgIndex == 0 && IsMemberCall)
656 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000657 }
658
Richard Smith08d6e032011-12-16 19:06:07 +0000659 Out << ')';
660}
661
662void EvalInfo::addCallStack(unsigned Limit) {
663 // Determine which calls to skip, if any.
664 unsigned ActiveCalls = CallStackDepth - 1;
665 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
666 if (Limit && Limit < ActiveCalls) {
667 SkipStart = Limit / 2 + Limit % 2;
668 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000669 }
670
Richard Smith08d6e032011-12-16 19:06:07 +0000671 // Walk the call stack and add the diagnostics.
672 unsigned CallIdx = 0;
673 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
674 Frame = Frame->Caller, ++CallIdx) {
675 // Skip this call?
676 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
677 if (CallIdx == SkipStart) {
678 // Note that we're skipping calls.
679 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
680 << unsigned(ActiveCalls - Limit);
681 }
682 continue;
683 }
684
685 llvm::SmallVector<char, 128> Buffer;
686 llvm::raw_svector_ostream Out(Buffer);
687 describeCall(Frame, Out);
688 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
689 }
690}
691
692namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000693 struct ComplexValue {
694 private:
695 bool IsInt;
696
697 public:
698 APSInt IntReal, IntImag;
699 APFloat FloatReal, FloatImag;
700
701 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
702
703 void makeComplexFloat() { IsInt = false; }
704 bool isComplexFloat() const { return !IsInt; }
705 APFloat &getComplexFloatReal() { return FloatReal; }
706 APFloat &getComplexFloatImag() { return FloatImag; }
707
708 void makeComplexInt() { IsInt = true; }
709 bool isComplexInt() const { return IsInt; }
710 APSInt &getComplexIntReal() { return IntReal; }
711 APSInt &getComplexIntImag() { return IntImag; }
712
Richard Smith47a1eed2011-10-29 20:57:55 +0000713 void moveInto(CCValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000714 if (isComplexFloat())
Richard Smith47a1eed2011-10-29 20:57:55 +0000715 v = CCValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000716 else
Richard Smith47a1eed2011-10-29 20:57:55 +0000717 v = CCValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000718 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000719 void setFrom(const CCValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000720 assert(v.isComplexFloat() || v.isComplexInt());
721 if (v.isComplexFloat()) {
722 makeComplexFloat();
723 FloatReal = v.getComplexFloatReal();
724 FloatImag = v.getComplexFloatImag();
725 } else {
726 makeComplexInt();
727 IntReal = v.getComplexIntReal();
728 IntImag = v.getComplexIntImag();
729 }
730 }
John McCallf4cf1a12010-05-07 17:22:02 +0000731 };
John McCallefdb83e2010-05-07 21:00:08 +0000732
733 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000734 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000735 CharUnits Offset;
Richard Smith83587db2012-02-15 02:18:13 +0000736 unsigned CallIndex;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000737 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000738
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000739 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000740 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000741 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith83587db2012-02-15 02:18:13 +0000742 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000743 SubobjectDesignator &getLValueDesignator() { return Designator; }
744 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000745
Richard Smith47a1eed2011-10-29 20:57:55 +0000746 void moveInto(CCValue &V) const {
Richard Smith83587db2012-02-15 02:18:13 +0000747 V = CCValue(Base, Offset, CallIndex, Designator);
John McCallefdb83e2010-05-07 21:00:08 +0000748 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000749 void setFrom(const CCValue &V) {
750 assert(V.isLValue());
751 Base = V.getLValueBase();
752 Offset = V.getLValueOffset();
Richard Smith83587db2012-02-15 02:18:13 +0000753 CallIndex = V.getLValueCallIndex();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000754 Designator = V.getLValueDesignator();
755 }
756
Richard Smith83587db2012-02-15 02:18:13 +0000757 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000758 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000759 Offset = CharUnits::Zero();
Richard Smith83587db2012-02-15 02:18:13 +0000760 CallIndex = I;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000761 Designator = SubobjectDesignator(getType(B));
762 }
763
764 // Check that this LValue is not based on a null pointer. If it is, produce
765 // a diagnostic and mark the designator as invalid.
766 bool checkNullPointer(EvalInfo &Info, const Expr *E,
767 CheckSubobjectKind CSK) {
768 if (Designator.Invalid)
769 return false;
770 if (!Base) {
771 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_null_subobject)
772 << CSK;
773 Designator.setInvalid();
774 return false;
775 }
776 return true;
777 }
778
779 // Check this LValue refers to an object. If not, set the designator to be
780 // invalid and emit a diagnostic.
781 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
782 return checkNullPointer(Info, E, CSK) &&
783 Designator.checkSubobject(Info, E, CSK);
784 }
785
786 void addDecl(EvalInfo &Info, const Expr *E,
787 const Decl *D, bool Virtual = false) {
788 checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base);
789 Designator.addDeclUnchecked(D, Virtual);
790 }
791 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
792 checkSubobject(Info, E, CSK_ArrayToPointer);
793 Designator.addArrayUnchecked(CAT);
794 }
795 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
796 if (!checkNullPointer(Info, E, CSK_ArrayIndex))
797 return;
798 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000799 }
John McCallefdb83e2010-05-07 21:00:08 +0000800 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000801
802 struct MemberPtr {
803 MemberPtr() {}
804 explicit MemberPtr(const ValueDecl *Decl) :
805 DeclAndIsDerivedMember(Decl, false), Path() {}
806
807 /// The member or (direct or indirect) field referred to by this member
808 /// pointer, or 0 if this is a null member pointer.
809 const ValueDecl *getDecl() const {
810 return DeclAndIsDerivedMember.getPointer();
811 }
812 /// Is this actually a member of some type derived from the relevant class?
813 bool isDerivedMember() const {
814 return DeclAndIsDerivedMember.getInt();
815 }
816 /// Get the class which the declaration actually lives in.
817 const CXXRecordDecl *getContainingRecord() const {
818 return cast<CXXRecordDecl>(
819 DeclAndIsDerivedMember.getPointer()->getDeclContext());
820 }
821
822 void moveInto(CCValue &V) const {
823 V = CCValue(getDecl(), isDerivedMember(), Path);
824 }
825 void setFrom(const CCValue &V) {
826 assert(V.isMemberPointer());
827 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
828 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
829 Path.clear();
830 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
831 Path.insert(Path.end(), P.begin(), P.end());
832 }
833
834 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
835 /// whether the member is a member of some class derived from the class type
836 /// of the member pointer.
837 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
838 /// Path - The path of base/derived classes from the member declaration's
839 /// class (exclusive) to the class type of the member pointer (inclusive).
840 SmallVector<const CXXRecordDecl*, 4> Path;
841
842 /// Perform a cast towards the class of the Decl (either up or down the
843 /// hierarchy).
844 bool castBack(const CXXRecordDecl *Class) {
845 assert(!Path.empty());
846 const CXXRecordDecl *Expected;
847 if (Path.size() >= 2)
848 Expected = Path[Path.size() - 2];
849 else
850 Expected = getContainingRecord();
851 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
852 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
853 // if B does not contain the original member and is not a base or
854 // derived class of the class containing the original member, the result
855 // of the cast is undefined.
856 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
857 // (D::*). We consider that to be a language defect.
858 return false;
859 }
860 Path.pop_back();
861 return true;
862 }
863 /// Perform a base-to-derived member pointer cast.
864 bool castToDerived(const CXXRecordDecl *Derived) {
865 if (!getDecl())
866 return true;
867 if (!isDerivedMember()) {
868 Path.push_back(Derived);
869 return true;
870 }
871 if (!castBack(Derived))
872 return false;
873 if (Path.empty())
874 DeclAndIsDerivedMember.setInt(false);
875 return true;
876 }
877 /// Perform a derived-to-base member pointer cast.
878 bool castToBase(const CXXRecordDecl *Base) {
879 if (!getDecl())
880 return true;
881 if (Path.empty())
882 DeclAndIsDerivedMember.setInt(true);
883 if (isDerivedMember()) {
884 Path.push_back(Base);
885 return true;
886 }
887 return castBack(Base);
888 }
889 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000890
Richard Smithb02e4622012-02-01 01:42:44 +0000891 /// Compare two member pointers, which are assumed to be of the same type.
892 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
893 if (!LHS.getDecl() || !RHS.getDecl())
894 return !LHS.getDecl() && !RHS.getDecl();
895 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
896 return false;
897 return LHS.Path == RHS.Path;
898 }
899
Richard Smithc1c5f272011-12-13 06:39:58 +0000900 /// Kinds of constant expression checking, for diagnostics.
901 enum CheckConstantExpressionKind {
902 CCEK_Constant, ///< A normal constant.
903 CCEK_ReturnValue, ///< A constexpr function return value.
904 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
905 };
John McCallf4cf1a12010-05-07 17:22:02 +0000906}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000907
Richard Smith47a1eed2011-10-29 20:57:55 +0000908static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith83587db2012-02-15 02:18:13 +0000909static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
910 const LValue &This, const Expr *E,
911 CheckConstantExpressionKind CCEK = CCEK_Constant,
912 bool AllowNonLiteralTypes = false);
John McCallefdb83e2010-05-07 21:00:08 +0000913static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
914static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000915static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
916 EvalInfo &Info);
917static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000918static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith47a1eed2011-10-29 20:57:55 +0000919static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000920 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000921static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000922static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000923
924//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000925// Misc utilities
926//===----------------------------------------------------------------------===//
927
Richard Smith180f4792011-11-10 06:34:14 +0000928/// Should this call expression be treated as a string literal?
929static bool IsStringLiteralCall(const CallExpr *E) {
930 unsigned Builtin = E->isBuiltinCall();
931 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
932 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
933}
934
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000935static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000936 // C++11 [expr.const]p3 An address constant expression is a prvalue core
937 // constant expression of pointer type that evaluates to...
938
939 // ... a null pointer value, or a prvalue core constant expression of type
940 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000941 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000942
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000943 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
944 // ... the address of an object with static storage duration,
945 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
946 return VD->hasGlobalStorage();
947 // ... the address of a function,
948 return isa<FunctionDecl>(D);
949 }
950
951 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000952 switch (E->getStmtClass()) {
953 default:
954 return false;
Richard Smith180f4792011-11-10 06:34:14 +0000955 case Expr::CompoundLiteralExprClass:
956 return cast<CompoundLiteralExpr>(E)->isFileScope();
957 // A string literal has static storage duration.
958 case Expr::StringLiteralClass:
959 case Expr::PredefinedExprClass:
960 case Expr::ObjCStringLiteralClass:
961 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000962 case Expr::CXXTypeidExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000963 return true;
964 case Expr::CallExprClass:
965 return IsStringLiteralCall(cast<CallExpr>(E));
966 // For GCC compatibility, &&label has static storage duration.
967 case Expr::AddrLabelExprClass:
968 return true;
969 // A Block literal expression may be used as the initialization value for
970 // Block variables at global or local static scope.
971 case Expr::BlockExprClass:
972 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000973 case Expr::ImplicitValueInitExprClass:
974 // FIXME:
975 // We can never form an lvalue with an implicit value initialization as its
976 // base through expression evaluation, so these only appear in one case: the
977 // implicit variable declaration we invent when checking whether a constexpr
978 // constructor can produce a constant expression. We must assume that such
979 // an expression might be a global lvalue.
980 return true;
Richard Smith180f4792011-11-10 06:34:14 +0000981 }
John McCall42c8f872010-05-10 23:27:23 +0000982}
983
Richard Smith83587db2012-02-15 02:18:13 +0000984static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
985 assert(Base && "no location for a null lvalue");
986 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
987 if (VD)
988 Info.Note(VD->getLocation(), diag::note_declared_at);
989 else
990 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
991 diag::note_constexpr_temporary_here);
992}
993
Richard Smith9a17a682011-11-07 05:07:52 +0000994/// Check that this reference or pointer core constant expression is a valid
Richard Smithb4e85ed2012-01-06 16:39:00 +0000995/// value for an address or reference constant expression. Type T should be
Richard Smith61e61622012-01-12 06:08:57 +0000996/// either LValue or CCValue. Return true if we can fold this expression,
997/// whether or not it's a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +0000998static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
999 QualType Type, const LValue &LVal) {
1000 bool IsReferenceType = Type->isReferenceType();
1001
Richard Smithc1c5f272011-12-13 06:39:58 +00001002 APValue::LValueBase Base = LVal.getLValueBase();
1003 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1004
1005 if (!IsGlobalLValue(Base)) {
1006 if (Info.getLangOpts().CPlusPlus0x) {
1007 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001008 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1009 << IsReferenceType << !Designator.Entries.empty()
1010 << !!VD << VD;
1011 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001012 } else {
Richard Smith83587db2012-02-15 02:18:13 +00001013 Info.Diag(Loc);
Richard Smithc1c5f272011-12-13 06:39:58 +00001014 }
Richard Smith61e61622012-01-12 06:08:57 +00001015 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +00001016 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001017 }
Richard Smith83587db2012-02-15 02:18:13 +00001018 assert((Info.CheckingPotentialConstantExpression ||
1019 LVal.getLValueCallIndex() == 0) &&
1020 "have call index for global lvalue");
Richard Smithb4e85ed2012-01-06 16:39:00 +00001021
1022 // Allow address constant expressions to be past-the-end pointers. This is
1023 // an extension: the standard requires them to point to an object.
1024 if (!IsReferenceType)
1025 return true;
1026
1027 // A reference constant expression must refer to an object.
1028 if (!Base) {
1029 // FIXME: diagnostic
Richard Smith83587db2012-02-15 02:18:13 +00001030 Info.CCEDiag(Loc);
Richard Smith61e61622012-01-12 06:08:57 +00001031 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001032 }
1033
Richard Smithc1c5f272011-12-13 06:39:58 +00001034 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +00001035 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001036 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001037 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smithc1c5f272011-12-13 06:39:58 +00001038 << !Designator.Entries.empty() << !!VD << VD;
Richard Smith83587db2012-02-15 02:18:13 +00001039 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001040 }
1041
Richard Smith9a17a682011-11-07 05:07:52 +00001042 return true;
1043}
1044
Richard Smith51201882011-12-30 21:15:51 +00001045/// Check that this core constant expression is of literal type, and if not,
1046/// produce an appropriate diagnostic.
1047static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1048 if (!E->isRValue() || E->getType()->isLiteralType())
1049 return true;
1050
1051 // Prvalue constant expressions must be of literal types.
1052 if (Info.getLangOpts().CPlusPlus0x)
1053 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
1054 << E->getType();
1055 else
1056 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1057 return false;
1058}
1059
Richard Smith47a1eed2011-10-29 20:57:55 +00001060/// Check that this core constant expression value is a valid value for a
Richard Smith83587db2012-02-15 02:18:13 +00001061/// constant expression. If not, report an appropriate diagnostic. Does not
1062/// check that the expression is of literal type.
1063static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1064 QualType Type, const APValue &Value) {
1065 // Core issue 1454: For a literal constant expression of array or class type,
1066 // each subobject of its value shall have been initialized by a constant
1067 // expression.
1068 if (Value.isArray()) {
1069 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1070 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1071 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1072 Value.getArrayInitializedElt(I)))
1073 return false;
1074 }
1075 if (!Value.hasArrayFiller())
1076 return true;
1077 return CheckConstantExpression(Info, DiagLoc, EltTy,
1078 Value.getArrayFiller());
Richard Smith9a17a682011-11-07 05:07:52 +00001079 }
Richard Smith83587db2012-02-15 02:18:13 +00001080 if (Value.isUnion() && Value.getUnionField()) {
1081 return CheckConstantExpression(Info, DiagLoc,
1082 Value.getUnionField()->getType(),
1083 Value.getUnionValue());
1084 }
1085 if (Value.isStruct()) {
1086 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1087 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1088 unsigned BaseIndex = 0;
1089 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1090 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1091 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1092 Value.getStructBase(BaseIndex)))
1093 return false;
1094 }
1095 }
1096 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1097 I != E; ++I) {
1098 if (!CheckConstantExpression(Info, DiagLoc, (*I)->getType(),
1099 Value.getStructField((*I)->getFieldIndex())))
1100 return false;
1101 }
1102 }
1103
1104 if (Value.isLValue()) {
1105 CCValue Val(Info.Ctx, Value, CCValue::GlobalValue());
1106 LValue LVal;
1107 LVal.setFrom(Val);
1108 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1109 }
1110
1111 // Everything else is fine.
1112 return true;
Richard Smith47a1eed2011-10-29 20:57:55 +00001113}
1114
Richard Smith9e36b532011-10-31 05:11:32 +00001115const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001116 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001117}
1118
1119static bool IsLiteralLValue(const LValue &Value) {
Richard Smith83587db2012-02-15 02:18:13 +00001120 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith9e36b532011-10-31 05:11:32 +00001121}
1122
Richard Smith65ac5982011-11-01 21:06:14 +00001123static bool IsWeakLValue(const LValue &Value) {
1124 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001125 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001126}
1127
Richard Smithe24f5fc2011-11-17 22:56:20 +00001128static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001129 // A null base expression indicates a null pointer. These are always
1130 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001131 if (!Value.getLValueBase()) {
1132 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001133 return true;
1134 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001135
Richard Smithe24f5fc2011-11-17 22:56:20 +00001136 // We have a non-null base. These are generally known to be true, but if it's
1137 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001138 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001139 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001140 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001141}
1142
Richard Smith47a1eed2011-10-29 20:57:55 +00001143static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001144 switch (Val.getKind()) {
1145 case APValue::Uninitialized:
1146 return false;
1147 case APValue::Int:
1148 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001149 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001150 case APValue::Float:
1151 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001152 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001153 case APValue::ComplexInt:
1154 Result = Val.getComplexIntReal().getBoolValue() ||
1155 Val.getComplexIntImag().getBoolValue();
1156 return true;
1157 case APValue::ComplexFloat:
1158 Result = !Val.getComplexFloatReal().isZero() ||
1159 !Val.getComplexFloatImag().isZero();
1160 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001161 case APValue::LValue:
1162 return EvalPointerValueAsBool(Val, Result);
1163 case APValue::MemberPointer:
1164 Result = Val.getMemberPointerDecl();
1165 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001166 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001167 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001168 case APValue::Struct:
1169 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001170 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001171 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001172 }
1173
Richard Smithc49bd112011-10-28 17:51:58 +00001174 llvm_unreachable("unknown APValue kind");
1175}
1176
1177static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1178 EvalInfo &Info) {
1179 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith47a1eed2011-10-29 20:57:55 +00001180 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +00001181 if (!Evaluate(Val, Info, E))
1182 return false;
1183 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001184}
1185
Richard Smithc1c5f272011-12-13 06:39:58 +00001186template<typename T>
1187static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1188 const T &SrcValue, QualType DestType) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001189 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001190 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001191 return false;
1192}
1193
1194static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1195 QualType SrcType, const APFloat &Value,
1196 QualType DestType, APSInt &Result) {
1197 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001198 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001199 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001200
Richard Smithc1c5f272011-12-13 06:39:58 +00001201 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001202 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001203 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1204 & APFloat::opInvalidOp)
1205 return HandleOverflow(Info, E, Value, DestType);
1206 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001207}
1208
Richard Smithc1c5f272011-12-13 06:39:58 +00001209static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1210 QualType SrcType, QualType DestType,
1211 APFloat &Result) {
1212 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001213 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001214 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1215 APFloat::rmNearestTiesToEven, &ignored)
1216 & APFloat::opOverflow)
1217 return HandleOverflow(Info, E, Value, DestType);
1218 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001219}
1220
Richard Smithf72fccf2012-01-30 22:27:01 +00001221static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1222 QualType DestType, QualType SrcType,
1223 APSInt &Value) {
1224 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001225 APSInt Result = Value;
1226 // Figure out if this is a truncate, extend or noop cast.
1227 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001228 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001229 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001230 return Result;
1231}
1232
Richard Smithc1c5f272011-12-13 06:39:58 +00001233static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1234 QualType SrcType, const APSInt &Value,
1235 QualType DestType, APFloat &Result) {
1236 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1237 if (Result.convertFromAPInt(Value, Value.isSigned(),
1238 APFloat::rmNearestTiesToEven)
1239 & APFloat::opOverflow)
1240 return HandleOverflow(Info, E, Value, DestType);
1241 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001242}
1243
Eli Friedmane6a24e82011-12-22 03:51:45 +00001244static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1245 llvm::APInt &Res) {
1246 CCValue SVal;
1247 if (!Evaluate(SVal, Info, E))
1248 return false;
1249 if (SVal.isInt()) {
1250 Res = SVal.getInt();
1251 return true;
1252 }
1253 if (SVal.isFloat()) {
1254 Res = SVal.getFloat().bitcastToAPInt();
1255 return true;
1256 }
1257 if (SVal.isVector()) {
1258 QualType VecTy = E->getType();
1259 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1260 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1261 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1262 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1263 Res = llvm::APInt::getNullValue(VecSize);
1264 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1265 APValue &Elt = SVal.getVectorElt(i);
1266 llvm::APInt EltAsInt;
1267 if (Elt.isInt()) {
1268 EltAsInt = Elt.getInt();
1269 } else if (Elt.isFloat()) {
1270 EltAsInt = Elt.getFloat().bitcastToAPInt();
1271 } else {
1272 // Don't try to handle vectors of anything other than int or float
1273 // (not sure if it's possible to hit this case).
1274 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1275 return false;
1276 }
1277 unsigned BaseEltSize = EltAsInt.getBitWidth();
1278 if (BigEndian)
1279 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1280 else
1281 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1282 }
1283 return true;
1284 }
1285 // Give up if the input isn't an int, float, or vector. For example, we
1286 // reject "(v4i16)(intptr_t)&a".
1287 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1288 return false;
1289}
1290
Richard Smithb4e85ed2012-01-06 16:39:00 +00001291/// Cast an lvalue referring to a base subobject to a derived class, by
1292/// truncating the lvalue's path to the given length.
1293static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1294 const RecordDecl *TruncatedType,
1295 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001296 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001297
1298 // Check we actually point to a derived class object.
1299 if (TruncatedElements == D.Entries.size())
1300 return true;
1301 assert(TruncatedElements >= D.MostDerivedPathLength &&
1302 "not casting to a derived class");
1303 if (!Result.checkSubobject(Info, E, CSK_Derived))
1304 return false;
1305
1306 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001307 const RecordDecl *RD = TruncatedType;
1308 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +00001309 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1310 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001311 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001312 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001313 else
Richard Smith180f4792011-11-10 06:34:14 +00001314 Result.Offset -= Layout.getBaseClassOffset(Base);
1315 RD = Base;
1316 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001317 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001318 return true;
1319}
1320
Richard Smithb4e85ed2012-01-06 16:39:00 +00001321static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001322 const CXXRecordDecl *Derived,
1323 const CXXRecordDecl *Base,
1324 const ASTRecordLayout *RL = 0) {
1325 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1326 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001327 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
Richard Smith180f4792011-11-10 06:34:14 +00001328}
1329
Richard Smithb4e85ed2012-01-06 16:39:00 +00001330static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001331 const CXXRecordDecl *DerivedDecl,
1332 const CXXBaseSpecifier *Base) {
1333 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1334
1335 if (!Base->isVirtual()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001336 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001337 return true;
1338 }
1339
Richard Smithb4e85ed2012-01-06 16:39:00 +00001340 SubobjectDesignator &D = Obj.Designator;
1341 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001342 return false;
1343
Richard Smithb4e85ed2012-01-06 16:39:00 +00001344 // Extract most-derived object and corresponding type.
1345 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1346 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1347 return false;
1348
1349 // Find the virtual base class.
Richard Smith180f4792011-11-10 06:34:14 +00001350 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1351 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001352 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001353 return true;
1354}
1355
1356/// Update LVal to refer to the given field, which must be a member of the type
1357/// currently described by LVal.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001358static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001359 const FieldDecl *FD,
1360 const ASTRecordLayout *RL = 0) {
1361 if (!RL)
1362 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1363
1364 unsigned I = FD->getFieldIndex();
1365 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001366 LVal.addDecl(Info, E, FD);
Richard Smith180f4792011-11-10 06:34:14 +00001367}
1368
Richard Smithd9b02e72012-01-25 22:15:11 +00001369/// Update LVal to refer to the given indirect field.
1370static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1371 LValue &LVal,
1372 const IndirectFieldDecl *IFD) {
1373 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1374 CE = IFD->chain_end(); C != CE; ++C)
1375 HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
1376}
1377
Richard Smith180f4792011-11-10 06:34:14 +00001378/// Get the size of the given type in char units.
Richard Smith74e1ad92012-02-16 02:46:34 +00001379static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1380 QualType Type, CharUnits &Size) {
Richard Smith180f4792011-11-10 06:34:14 +00001381 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1382 // extension.
1383 if (Type->isVoidType() || Type->isFunctionType()) {
1384 Size = CharUnits::One();
1385 return true;
1386 }
1387
1388 if (!Type->isConstantSizeType()) {
1389 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith74e1ad92012-02-16 02:46:34 +00001390 // FIXME: Better diagnostic.
1391 Info.Diag(Loc);
Richard Smith180f4792011-11-10 06:34:14 +00001392 return false;
1393 }
1394
1395 Size = Info.Ctx.getTypeSizeInChars(Type);
1396 return true;
1397}
1398
1399/// Update a pointer value to model pointer arithmetic.
1400/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001401/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001402/// \param LVal - The pointer value to be updated.
1403/// \param EltTy - The pointee type represented by LVal.
1404/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001405static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1406 LValue &LVal, QualType EltTy,
1407 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001408 CharUnits SizeOfPointee;
Richard Smith74e1ad92012-02-16 02:46:34 +00001409 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smith180f4792011-11-10 06:34:14 +00001410 return false;
1411
1412 // Compute the new offset in the appropriate width.
1413 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001414 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001415 return true;
1416}
1417
Richard Smith03f96112011-10-24 17:54:18 +00001418/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001419static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1420 const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +00001421 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001422 // If this is a parameter to an active constexpr function call, perform
1423 // argument substitution.
1424 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001425 // Assume arguments of a potential constant expression are unknown
1426 // constant expressions.
1427 if (Info.CheckingPotentialConstantExpression)
1428 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001429 if (!Frame || !Frame->Arguments) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001430 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001431 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001432 }
Richard Smith177dce72011-11-01 16:57:24 +00001433 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1434 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001435 }
Richard Smith03f96112011-10-24 17:54:18 +00001436
Richard Smith099e7f62011-12-19 06:19:21 +00001437 // Dig out the initializer, and use the declaration which it's attached to.
1438 const Expr *Init = VD->getAnyInitializer(VD);
1439 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001440 // If we're checking a potential constant expression, the variable could be
1441 // initialized later.
1442 if (!Info.CheckingPotentialConstantExpression)
1443 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001444 return false;
1445 }
1446
Richard Smith180f4792011-11-10 06:34:14 +00001447 // If we're currently evaluating the initializer of this declaration, use that
1448 // in-flight value.
1449 if (Info.EvaluatingDecl == VD) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001450 Result = CCValue(Info.Ctx, *Info.EvaluatingDeclValue,
1451 CCValue::GlobalValue());
Richard Smith180f4792011-11-10 06:34:14 +00001452 return !Result.isUninit();
1453 }
1454
Richard Smith65ac5982011-11-01 21:06:14 +00001455 // Never evaluate the initializer of a weak variable. We can't be sure that
1456 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001457 if (VD->isWeak()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001458 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001459 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001460 }
Richard Smith65ac5982011-11-01 21:06:14 +00001461
Richard Smith099e7f62011-12-19 06:19:21 +00001462 // Check that we can fold the initializer. In C++, we will have already done
1463 // this in the cases where it matters for conformance.
1464 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1465 if (!VD->evaluateValue(Notes)) {
1466 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1467 Notes.size() + 1) << VD;
1468 Info.Note(VD->getLocation(), diag::note_declared_at);
1469 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001470 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001471 } else if (!VD->checkInitIsICE()) {
1472 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1473 Notes.size() + 1) << VD;
1474 Info.Note(VD->getLocation(), diag::note_declared_at);
1475 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001476 }
Richard Smith03f96112011-10-24 17:54:18 +00001477
Richard Smithb4e85ed2012-01-06 16:39:00 +00001478 Result = CCValue(Info.Ctx, *VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +00001479 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001480}
1481
Richard Smithc49bd112011-10-28 17:51:58 +00001482static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001483 Qualifiers Quals = T.getQualifiers();
1484 return Quals.hasConst() && !Quals.hasVolatile();
1485}
1486
Richard Smith59efe262011-11-11 04:05:33 +00001487/// Get the base index of the given base class within an APValue representing
1488/// the given derived class.
1489static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1490 const CXXRecordDecl *Base) {
1491 Base = Base->getCanonicalDecl();
1492 unsigned Index = 0;
1493 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1494 E = Derived->bases_end(); I != E; ++I, ++Index) {
1495 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1496 return Index;
1497 }
1498
1499 llvm_unreachable("base class missing from derived class's bases list");
1500}
1501
Richard Smithf3908f22012-02-17 03:35:37 +00001502/// Extract the value of a character from a string literal.
1503static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1504 uint64_t Index) {
1505 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1506 const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1507 assert(S && "unexpected string literal expression kind");
1508
1509 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1510 Lit->getType()->getArrayElementTypeNoTypeQual()->isUnsignedIntegerType());
1511 if (Index < S->getLength())
1512 Value = S->getCodeUnit(Index);
1513 return Value;
1514}
1515
Richard Smithcc5d4f62011-11-07 09:22:26 +00001516/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001517static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1518 CCValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001519 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001520 if (Sub.Invalid)
1521 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001522 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001523 if (Sub.isOnePastTheEnd()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001524 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001525 (unsigned)diag::note_constexpr_read_past_end :
1526 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001527 return false;
1528 }
Richard Smithf64699e2011-11-11 08:28:03 +00001529 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001530 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001531 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1532 // This object might be initialized later.
1533 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001534
Richard Smithcc5d4f62011-11-07 09:22:26 +00001535 const APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001536 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001537 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001538 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001539 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001540 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001541 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001542 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001543 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001544 // Note, it should not be possible to form a pointer with a valid
1545 // designator which points more than one past the end of the array.
1546 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001547 (unsigned)diag::note_constexpr_read_past_end :
1548 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001549 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001550 }
Richard Smithf3908f22012-02-17 03:35:37 +00001551 // An array object is represented as either an Array APValue or as an
1552 // LValue which refers to a string literal.
1553 if (O->isLValue()) {
1554 assert(I == N - 1 && "extracting subobject of character?");
1555 assert(!O->hasLValuePath() || O->getLValuePath().empty());
1556 Obj = CCValue(ExtractStringLiteralCharacter(
1557 Info, O->getLValueBase().get<const Expr*>(), Index));
1558 return true;
1559 } else if (O->getArrayInitializedElts() > Index)
Richard Smithcc5d4f62011-11-07 09:22:26 +00001560 O = &O->getArrayInitializedElt(Index);
1561 else
1562 O = &O->getArrayFiller();
1563 ObjType = CAT->getElementType();
Richard Smith180f4792011-11-10 06:34:14 +00001564 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithb4e5e282012-02-09 03:29:58 +00001565 if (Field->isMutable()) {
1566 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_mutable, 1)
1567 << Field;
1568 Info.Note(Field->getLocation(), diag::note_declared_at);
1569 return false;
1570 }
1571
Richard Smith180f4792011-11-10 06:34:14 +00001572 // Next subobject is a class, struct or union field.
1573 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1574 if (RD->isUnion()) {
1575 const FieldDecl *UnionField = O->getUnionField();
1576 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001577 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001578 Info.Diag(E->getExprLoc(),
1579 diag::note_constexpr_read_inactive_union_member)
1580 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001581 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001582 }
Richard Smith180f4792011-11-10 06:34:14 +00001583 O = &O->getUnionValue();
1584 } else
1585 O = &O->getStructField(Field->getFieldIndex());
1586 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001587
1588 if (ObjType.isVolatileQualified()) {
1589 if (Info.getLangOpts().CPlusPlus) {
1590 // FIXME: Include a description of the path to the volatile subobject.
1591 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1592 << 2 << Field;
1593 Info.Note(Field->getLocation(), diag::note_declared_at);
1594 } else {
1595 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1596 }
1597 return false;
1598 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001599 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001600 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001601 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1602 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1603 O = &O->getStructBase(getBaseIndex(Derived, Base));
1604 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001605 }
Richard Smith180f4792011-11-10 06:34:14 +00001606
Richard Smithf48fdb02011-12-09 22:58:01 +00001607 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001608 if (!Info.CheckingPotentialConstantExpression)
1609 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001610 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001611 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001612 }
1613
Richard Smithb4e85ed2012-01-06 16:39:00 +00001614 Obj = CCValue(Info.Ctx, *O, CCValue::GlobalValue());
Richard Smithcc5d4f62011-11-07 09:22:26 +00001615 return true;
1616}
1617
Richard Smithf15fda02012-02-02 01:16:57 +00001618/// Find the position where two subobject designators diverge, or equivalently
1619/// the length of the common initial subsequence.
1620static unsigned FindDesignatorMismatch(QualType ObjType,
1621 const SubobjectDesignator &A,
1622 const SubobjectDesignator &B,
1623 bool &WasArrayIndex) {
1624 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1625 for (/**/; I != N; ++I) {
1626 if (!ObjType.isNull() && ObjType->isArrayType()) {
1627 // Next subobject is an array element.
1628 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1629 WasArrayIndex = true;
1630 return I;
1631 }
1632 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
1633 } else {
1634 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1635 WasArrayIndex = false;
1636 return I;
1637 }
1638 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1639 // Next subobject is a field.
1640 ObjType = FD->getType();
1641 else
1642 // Next subobject is a base class.
1643 ObjType = QualType();
1644 }
1645 }
1646 WasArrayIndex = false;
1647 return I;
1648}
1649
1650/// Determine whether the given subobject designators refer to elements of the
1651/// same array object.
1652static bool AreElementsOfSameArray(QualType ObjType,
1653 const SubobjectDesignator &A,
1654 const SubobjectDesignator &B) {
1655 if (A.Entries.size() != B.Entries.size())
1656 return false;
1657
1658 bool IsArray = A.MostDerivedArraySize != 0;
1659 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1660 // A is a subobject of the array element.
1661 return false;
1662
1663 // If A (and B) designates an array element, the last entry will be the array
1664 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1665 // of length 1' case, and the entire path must match.
1666 bool WasArrayIndex;
1667 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1668 return CommonLength >= A.Entries.size() - IsArray;
1669}
1670
Richard Smith180f4792011-11-10 06:34:14 +00001671/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1672/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1673/// for looking up the glvalue referred to by an entity of reference type.
1674///
1675/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001676/// \param Conv - The expression for which we are performing the conversion.
1677/// Used for diagnostics.
Richard Smith9ec71972012-02-05 01:23:16 +00001678/// \param Type - The type we expect this conversion to produce, before
1679/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smith180f4792011-11-10 06:34:14 +00001680/// \param LVal - The glvalue on which we are attempting to perform this action.
1681/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001682static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1683 QualType Type,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001684 const LValue &LVal, CCValue &RVal) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001685 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1686 if (!Info.getLangOpts().CPlusPlus)
1687 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1688
Richard Smithb4e85ed2012-01-06 16:39:00 +00001689 if (LVal.Designator.Invalid)
1690 // A diagnostic will have already been produced.
1691 return false;
1692
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001693 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith7098cbd2011-12-21 05:04:46 +00001694 SourceLocation Loc = Conv->getExprLoc();
Richard Smithc49bd112011-10-28 17:51:58 +00001695
Richard Smithf48fdb02011-12-09 22:58:01 +00001696 if (!LVal.Base) {
1697 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith7098cbd2011-12-21 05:04:46 +00001698 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1699 return false;
1700 }
1701
Richard Smith83587db2012-02-15 02:18:13 +00001702 CallStackFrame *Frame = 0;
1703 if (LVal.CallIndex) {
1704 Frame = Info.getCallFrame(LVal.CallIndex);
1705 if (!Frame) {
1706 Info.Diag(Loc, diag::note_constexpr_lifetime_ended, 1) << !Base;
1707 NoteLValueLocation(Info, LVal.Base);
1708 return false;
1709 }
1710 }
1711
Richard Smith7098cbd2011-12-21 05:04:46 +00001712 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1713 // is not a constant expression (even if the object is non-volatile). We also
1714 // apply this rule to C++98, in order to conform to the expected 'volatile'
1715 // semantics.
1716 if (Type.isVolatileQualified()) {
1717 if (Info.getLangOpts().CPlusPlus)
1718 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1719 else
1720 Info.Diag(Loc);
Richard Smithc49bd112011-10-28 17:51:58 +00001721 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001722 }
Richard Smithc49bd112011-10-28 17:51:58 +00001723
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001724 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001725 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1726 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001727 // expressions are constant expressions too. Inside constexpr functions,
1728 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001729 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001730 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf15fda02012-02-02 01:16:57 +00001731 if (const VarDecl *VDef = VD->getDefinition())
1732 VD = VDef;
Richard Smithf48fdb02011-12-09 22:58:01 +00001733 if (!VD || VD->isInvalidDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001734 Info.Diag(Loc);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001735 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001736 }
1737
Richard Smith7098cbd2011-12-21 05:04:46 +00001738 // DR1313: If the object is volatile-qualified but the glvalue was not,
1739 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001740 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001741 if (VT.isVolatileQualified()) {
1742 if (Info.getLangOpts().CPlusPlus) {
1743 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1744 Info.Note(VD->getLocation(), diag::note_declared_at);
1745 } else {
1746 Info.Diag(Loc);
Richard Smithf48fdb02011-12-09 22:58:01 +00001747 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001748 return false;
1749 }
1750
1751 if (!isa<ParmVarDecl>(VD)) {
1752 if (VD->isConstexpr()) {
1753 // OK, we can read this variable.
1754 } else if (VT->isIntegralOrEnumerationType()) {
1755 if (!VT.isConstQualified()) {
1756 if (Info.getLangOpts().CPlusPlus) {
1757 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1758 Info.Note(VD->getLocation(), diag::note_declared_at);
1759 } else {
1760 Info.Diag(Loc);
1761 }
1762 return false;
1763 }
1764 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1765 // We support folding of const floating-point types, in order to make
1766 // static const data members of such types (supported as an extension)
1767 // more useful.
1768 if (Info.getLangOpts().CPlusPlus0x) {
1769 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1770 Info.Note(VD->getLocation(), diag::note_declared_at);
1771 } else {
1772 Info.CCEDiag(Loc);
1773 }
1774 } else {
1775 // FIXME: Allow folding of values of any literal type in all languages.
1776 if (Info.getLangOpts().CPlusPlus0x) {
1777 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1778 Info.Note(VD->getLocation(), diag::note_declared_at);
1779 } else {
1780 Info.Diag(Loc);
1781 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001782 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001783 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001784 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001785
Richard Smithf48fdb02011-12-09 22:58:01 +00001786 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001787 return false;
1788
Richard Smith47a1eed2011-10-29 20:57:55 +00001789 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001790 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001791
1792 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1793 // conversion. This happens when the declaration and the lvalue should be
1794 // considered synonymous, for instance when initializing an array of char
1795 // from a string literal. Continue as if the initializer lvalue was the
1796 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001797 assert(RVal.getLValueOffset().isZero() &&
1798 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001799 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith83587db2012-02-15 02:18:13 +00001800
1801 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1802 Frame = Info.getCallFrame(CallIndex);
1803 if (!Frame) {
1804 Info.Diag(Loc, diag::note_constexpr_lifetime_ended, 1) << !Base;
1805 NoteLValueLocation(Info, RVal.getLValueBase());
1806 return false;
1807 }
1808 } else {
1809 Frame = 0;
1810 }
Richard Smithc49bd112011-10-28 17:51:58 +00001811 }
1812
Richard Smith7098cbd2011-12-21 05:04:46 +00001813 // Volatile temporary objects cannot be read in constant expressions.
1814 if (Base->getType().isVolatileQualified()) {
1815 if (Info.getLangOpts().CPlusPlus) {
1816 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1817 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1818 } else {
1819 Info.Diag(Loc);
1820 }
1821 return false;
1822 }
1823
Richard Smithcc5d4f62011-11-07 09:22:26 +00001824 if (Frame) {
1825 // If this is a temporary expression with a nontrivial initializer, grab the
1826 // value from the relevant stack frame.
1827 RVal = Frame->Temporaries[Base];
1828 } else if (const CompoundLiteralExpr *CLE
1829 = dyn_cast<CompoundLiteralExpr>(Base)) {
1830 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1831 // initializer until now for such expressions. Such an expression can't be
1832 // an ICE in C, so this only matters for fold.
1833 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1834 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1835 return false;
Richard Smithf3908f22012-02-17 03:35:37 +00001836 } else if (isa<StringLiteral>(Base)) {
1837 // We represent a string literal array as an lvalue pointing at the
1838 // corresponding expression, rather than building an array of chars.
1839 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1840 RVal = CCValue(Info.Ctx,
1841 APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0),
1842 CCValue::GlobalValue());
Richard Smithf48fdb02011-12-09 22:58:01 +00001843 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001844 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001845 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001846 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001847
Richard Smithf48fdb02011-12-09 22:58:01 +00001848 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1849 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001850}
1851
Richard Smith59efe262011-11-11 04:05:33 +00001852/// Build an lvalue for the object argument of a member function call.
1853static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1854 LValue &This) {
1855 if (Object->getType()->isPointerType())
1856 return EvaluatePointer(Object, This, Info);
1857
1858 if (Object->isGLValue())
1859 return EvaluateLValue(Object, This, Info);
1860
Richard Smithe24f5fc2011-11-17 22:56:20 +00001861 if (Object->getType()->isLiteralType())
1862 return EvaluateTemporary(Object, This, Info);
1863
1864 return false;
1865}
1866
1867/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1868/// lvalue referring to the result.
1869///
1870/// \param Info - Information about the ongoing evaluation.
1871/// \param BO - The member pointer access operation.
1872/// \param LV - Filled in with a reference to the resulting object.
1873/// \param IncludeMember - Specifies whether the member itself is included in
1874/// the resulting LValue subobject designator. This is not possible when
1875/// creating a bound member function.
1876/// \return The field or method declaration to which the member pointer refers,
1877/// or 0 if evaluation fails.
1878static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1879 const BinaryOperator *BO,
1880 LValue &LV,
1881 bool IncludeMember = true) {
1882 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1883
Richard Smith745f5142012-01-27 01:14:48 +00001884 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1885 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001886 return 0;
1887
1888 MemberPtr MemPtr;
1889 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1890 return 0;
1891
1892 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1893 // member value, the behavior is undefined.
1894 if (!MemPtr.getDecl())
1895 return 0;
1896
Richard Smith745f5142012-01-27 01:14:48 +00001897 if (!EvalObjOK)
1898 return 0;
1899
Richard Smithe24f5fc2011-11-17 22:56:20 +00001900 if (MemPtr.isDerivedMember()) {
1901 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001902 // The end of the derived-to-base path for the base object must match the
1903 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001904 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001905 LV.Designator.Entries.size())
1906 return 0;
1907 unsigned PathLengthToMember =
1908 LV.Designator.Entries.size() - MemPtr.Path.size();
1909 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1910 const CXXRecordDecl *LVDecl = getAsBaseClass(
1911 LV.Designator.Entries[PathLengthToMember + I]);
1912 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1913 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1914 return 0;
1915 }
1916
1917 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001918 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1919 PathLengthToMember))
1920 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001921 } else if (!MemPtr.Path.empty()) {
1922 // Extend the LValue path with the member pointer's path.
1923 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1924 MemPtr.Path.size() + IncludeMember);
1925
1926 // Walk down to the appropriate base class.
1927 QualType LVType = BO->getLHS()->getType();
1928 if (const PointerType *PT = LVType->getAs<PointerType>())
1929 LVType = PT->getPointeeType();
1930 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1931 assert(RD && "member pointer access on non-class-type expression");
1932 // The first class in the path is that of the lvalue.
1933 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1934 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smithb4e85ed2012-01-06 16:39:00 +00001935 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001936 RD = Base;
1937 }
1938 // Finally cast to the class containing the member.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001939 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smithe24f5fc2011-11-17 22:56:20 +00001940 }
1941
1942 // Add the member. Note that we cannot build bound member functions here.
1943 if (IncludeMember) {
Richard Smithd9b02e72012-01-25 22:15:11 +00001944 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
1945 HandleLValueMember(Info, BO, LV, FD);
1946 else if (const IndirectFieldDecl *IFD =
1947 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
1948 HandleLValueIndirectMember(Info, BO, LV, IFD);
1949 else
1950 llvm_unreachable("can't construct reference to bound member function");
Richard Smithe24f5fc2011-11-17 22:56:20 +00001951 }
1952
1953 return MemPtr.getDecl();
1954}
1955
1956/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1957/// the provided lvalue, which currently refers to the base object.
1958static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1959 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001960 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001961 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001962 return false;
1963
Richard Smithb4e85ed2012-01-06 16:39:00 +00001964 QualType TargetQT = E->getType();
1965 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1966 TargetQT = PT->getPointeeType();
1967
1968 // Check this cast lands within the final derived-to-base subobject path.
1969 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
1970 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1971 << D.MostDerivedType << TargetQT;
1972 return false;
1973 }
1974
Richard Smithe24f5fc2011-11-17 22:56:20 +00001975 // Check the type of the final cast. We don't need to check the path,
1976 // since a cast can only be formed if the path is unique.
1977 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001978 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1979 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001980 if (NewEntriesSize == D.MostDerivedPathLength)
1981 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
1982 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00001983 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001984 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
1985 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1986 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001987 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001988 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001989
1990 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001991 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00001992}
1993
Mike Stumpc4c90452009-10-27 22:09:17 +00001994namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00001995enum EvalStmtResult {
1996 /// Evaluation failed.
1997 ESR_Failed,
1998 /// Hit a 'return' statement.
1999 ESR_Returned,
2000 /// Evaluation succeeded.
2001 ESR_Succeeded
2002};
2003}
2004
2005// Evaluate a statement.
Richard Smith83587db2012-02-15 02:18:13 +00002006static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00002007 const Stmt *S) {
2008 switch (S->getStmtClass()) {
2009 default:
2010 return ESR_Failed;
2011
2012 case Stmt::NullStmtClass:
2013 case Stmt::DeclStmtClass:
2014 return ESR_Succeeded;
2015
Richard Smithc1c5f272011-12-13 06:39:58 +00002016 case Stmt::ReturnStmtClass: {
Richard Smithc1c5f272011-12-13 06:39:58 +00002017 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith83587db2012-02-15 02:18:13 +00002018 if (!Evaluate(Result, Info, RetExpr))
Richard Smithc1c5f272011-12-13 06:39:58 +00002019 return ESR_Failed;
2020 return ESR_Returned;
2021 }
Richard Smithd0dccea2011-10-28 22:34:42 +00002022
2023 case Stmt::CompoundStmtClass: {
2024 const CompoundStmt *CS = cast<CompoundStmt>(S);
2025 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2026 BE = CS->body_end(); BI != BE; ++BI) {
2027 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2028 if (ESR != ESR_Succeeded)
2029 return ESR;
2030 }
2031 return ESR_Succeeded;
2032 }
2033 }
2034}
2035
Richard Smith61802452011-12-22 02:22:31 +00002036/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2037/// default constructor. If so, we'll fold it whether or not it's marked as
2038/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2039/// so we need special handling.
2040static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00002041 const CXXConstructorDecl *CD,
2042 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002043 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2044 return false;
2045
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002046 // Value-initialization does not call a trivial default constructor, so such a
2047 // call is a core constant expression whether or not the constructor is
2048 // constexpr.
2049 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002050 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002051 // FIXME: If DiagDecl is an implicitly-declared special member function,
2052 // we should be much more explicit about why it's not constexpr.
2053 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2054 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2055 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00002056 } else {
2057 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2058 }
2059 }
2060 return true;
2061}
2062
Richard Smithc1c5f272011-12-13 06:39:58 +00002063/// CheckConstexprFunction - Check that a function can be called in a constant
2064/// expression.
2065static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2066 const FunctionDecl *Declaration,
2067 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00002068 // Potential constant expressions can contain calls to declared, but not yet
2069 // defined, constexpr functions.
2070 if (Info.CheckingPotentialConstantExpression && !Definition &&
2071 Declaration->isConstexpr())
2072 return false;
2073
Richard Smithc1c5f272011-12-13 06:39:58 +00002074 // Can we evaluate this function call?
2075 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2076 return true;
2077
2078 if (Info.getLangOpts().CPlusPlus0x) {
2079 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00002080 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2081 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00002082 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2083 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2084 << DiagDecl;
2085 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2086 } else {
2087 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2088 }
2089 return false;
2090}
2091
Richard Smith180f4792011-11-10 06:34:14 +00002092namespace {
Richard Smithcd99b072011-11-11 05:48:57 +00002093typedef SmallVector<CCValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00002094}
2095
2096/// EvaluateArgs - Evaluate the arguments to a function call.
2097static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2098 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00002099 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002100 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00002101 I != E; ++I) {
2102 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2103 // If we're checking for a potential constant expression, evaluate all
2104 // initializers even if some of them fail.
2105 if (!Info.keepEvaluatingAfterFailure())
2106 return false;
2107 Success = false;
2108 }
2109 }
2110 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002111}
2112
Richard Smithd0dccea2011-10-28 22:34:42 +00002113/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002114static bool HandleFunctionCall(SourceLocation CallLoc,
2115 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002116 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith83587db2012-02-15 02:18:13 +00002117 EvalInfo &Info, CCValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002118 ArgVector ArgValues(Args.size());
2119 if (!EvaluateArgs(Args, ArgValues, Info))
2120 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00002121
Richard Smith745f5142012-01-27 01:14:48 +00002122 if (!Info.CheckCallLimit(CallLoc))
2123 return false;
2124
2125 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002126 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2127}
2128
Richard Smith180f4792011-11-10 06:34:14 +00002129/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002130static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002131 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002132 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002133 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002134 ArgVector ArgValues(Args.size());
2135 if (!EvaluateArgs(Args, ArgValues, Info))
2136 return false;
2137
Richard Smith745f5142012-01-27 01:14:48 +00002138 if (!Info.CheckCallLimit(CallLoc))
2139 return false;
2140
Richard Smith86c3ae42012-02-13 03:54:03 +00002141 const CXXRecordDecl *RD = Definition->getParent();
2142 if (RD->getNumVBases()) {
2143 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2144 return false;
2145 }
2146
Richard Smith745f5142012-01-27 01:14:48 +00002147 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002148
2149 // If it's a delegating constructor, just delegate.
2150 if (Definition->isDelegatingConstructor()) {
2151 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith83587db2012-02-15 02:18:13 +00002152 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
Richard Smith180f4792011-11-10 06:34:14 +00002153 }
2154
Richard Smith610a60c2012-01-10 04:32:03 +00002155 // For a trivial copy or move constructor, perform an APValue copy. This is
2156 // essential for unions, where the operations performed by the constructor
2157 // cannot be represented by ctor-initializers.
Richard Smith610a60c2012-01-10 04:32:03 +00002158 if (Definition->isDefaulted() &&
2159 ((Definition->isCopyConstructor() && RD->hasTrivialCopyConstructor()) ||
2160 (Definition->isMoveConstructor() && RD->hasTrivialMoveConstructor()))) {
2161 LValue RHS;
2162 RHS.setFrom(ArgValues[0]);
2163 CCValue Value;
Richard Smith745f5142012-01-27 01:14:48 +00002164 if (!HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2165 RHS, Value))
2166 return false;
2167 assert((Value.isStruct() || Value.isUnion()) &&
2168 "trivial copy/move from non-class type?");
2169 // Any CCValue of class type must already be a constant expression.
2170 Result = Value;
2171 return true;
Richard Smith610a60c2012-01-10 04:32:03 +00002172 }
2173
2174 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002175 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002176 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2177 std::distance(RD->field_begin(), RD->field_end()));
2178
2179 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2180
Richard Smith745f5142012-01-27 01:14:48 +00002181 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002182 unsigned BasesSeen = 0;
2183#ifndef NDEBUG
2184 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2185#endif
2186 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2187 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002188 LValue Subobject = This;
2189 APValue *Value = &Result;
2190
2191 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002192 if ((*I)->isBaseInitializer()) {
2193 QualType BaseType((*I)->getBaseClass(), 0);
2194#ifndef NDEBUG
2195 // Non-virtual base classes are initialized in the order in the class
Richard Smith86c3ae42012-02-13 03:54:03 +00002196 // definition. We have already checked for virtual base classes.
Richard Smith180f4792011-11-10 06:34:14 +00002197 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2198 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2199 "base class initializers not in expected order");
2200 ++BaseIt;
2201#endif
Richard Smithb4e85ed2012-01-06 16:39:00 +00002202 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smith180f4792011-11-10 06:34:14 +00002203 BaseType->getAsCXXRecordDecl(), &Layout);
Richard Smith745f5142012-01-27 01:14:48 +00002204 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002205 } else if (FieldDecl *FD = (*I)->getMember()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002206 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00002207 if (RD->isUnion()) {
2208 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002209 Value = &Result.getUnionValue();
2210 } else {
2211 Value = &Result.getStructField(FD->getFieldIndex());
2212 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002213 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002214 // Walk the indirect field decl's chain to find the object to initialize,
2215 // and make sure we've initialized every step along it.
2216 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2217 CE = IFD->chain_end();
2218 C != CE; ++C) {
2219 FieldDecl *FD = cast<FieldDecl>(*C);
2220 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2221 // Switch the union field if it differs. This happens if we had
2222 // preceding zero-initialization, and we're now initializing a union
2223 // subobject other than the first.
2224 // FIXME: In this case, the values of the other subobjects are
2225 // specified, since zero-initialization sets all padding bits to zero.
2226 if (Value->isUninit() ||
2227 (Value->isUnion() && Value->getUnionField() != FD)) {
2228 if (CD->isUnion())
2229 *Value = APValue(FD);
2230 else
2231 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2232 std::distance(CD->field_begin(), CD->field_end()));
2233 }
Richard Smith745f5142012-01-27 01:14:48 +00002234 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
Richard Smithd9b02e72012-01-25 22:15:11 +00002235 if (CD->isUnion())
2236 Value = &Value->getUnionValue();
2237 else
2238 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002239 }
Richard Smith180f4792011-11-10 06:34:14 +00002240 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002241 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002242 }
Richard Smith745f5142012-01-27 01:14:48 +00002243
Richard Smith83587db2012-02-15 02:18:13 +00002244 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2245 (*I)->isBaseInitializer()
Richard Smith745f5142012-01-27 01:14:48 +00002246 ? CCEK_Constant : CCEK_MemberInit)) {
2247 // If we're checking for a potential constant expression, evaluate all
2248 // initializers even if some of them fail.
2249 if (!Info.keepEvaluatingAfterFailure())
2250 return false;
2251 Success = false;
2252 }
Richard Smith180f4792011-11-10 06:34:14 +00002253 }
2254
Richard Smith745f5142012-01-27 01:14:48 +00002255 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002256}
2257
Richard Smithd0dccea2011-10-28 22:34:42 +00002258namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002259class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002260 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002261 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002262public:
2263
Richard Smith1e12c592011-10-16 21:26:27 +00002264 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002265
2266 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002267 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002268 return true;
2269 }
2270
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002271 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2272 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002273 return Visit(E->getResultExpr());
2274 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002275 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002276 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002277 return true;
2278 return false;
2279 }
John McCallf85e1932011-06-15 23:02:42 +00002280 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002281 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002282 return true;
2283 return false;
2284 }
2285 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002286 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002287 return true;
2288 return false;
2289 }
2290
Mike Stumpc4c90452009-10-27 22:09:17 +00002291 // We don't want to evaluate BlockExprs multiple times, as they generate
2292 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002293 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2294 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2295 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002296 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002297 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2298 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2299 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2300 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2301 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2302 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002303 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002304 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002305 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002306 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002307 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002308 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2309 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2310 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2311 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002312 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002313 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2314 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2315 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2316 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2317 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002318 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002319 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002320 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002321 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002322 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002323
2324 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002325 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002326 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2327 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002328 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002329 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002330 return false;
2331 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002332
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002333 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002334};
2335
John McCall56ca35d2011-02-17 10:25:35 +00002336class OpaqueValueEvaluation {
2337 EvalInfo &info;
2338 OpaqueValueExpr *opaqueValue;
2339
2340public:
2341 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2342 Expr *value)
2343 : info(info), opaqueValue(opaqueValue) {
2344
2345 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002346 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002347 this->opaqueValue = 0;
2348 return;
2349 }
John McCall56ca35d2011-02-17 10:25:35 +00002350 }
2351
2352 bool hasError() const { return opaqueValue == 0; }
2353
2354 ~OpaqueValueEvaluation() {
Richard Smith74e1ad92012-02-16 02:46:34 +00002355 // FIXME: For a recursive constexpr call, an outer stack frame might have
2356 // been using this opaque value too, and will now have to re-evaluate the
2357 // source expression.
John McCall56ca35d2011-02-17 10:25:35 +00002358 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2359 }
2360};
2361
Mike Stumpc4c90452009-10-27 22:09:17 +00002362} // end anonymous namespace
2363
Eli Friedman4efaa272008-11-12 09:44:48 +00002364//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002365// Generic Evaluation
2366//===----------------------------------------------------------------------===//
2367namespace {
2368
Richard Smithf48fdb02011-12-09 22:58:01 +00002369// FIXME: RetTy is always bool. Remove it.
2370template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002371class ExprEvaluatorBase
2372 : public ConstStmtVisitor<Derived, RetTy> {
2373private:
Richard Smith47a1eed2011-10-29 20:57:55 +00002374 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002375 return static_cast<Derived*>(this)->Success(V, E);
2376 }
Richard Smith51201882011-12-30 21:15:51 +00002377 RetTy DerivedZeroInitialization(const Expr *E) {
2378 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002379 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002380
Richard Smith74e1ad92012-02-16 02:46:34 +00002381 // Check whether a conditional operator with a non-constant condition is a
2382 // potential constant expression. If neither arm is a potential constant
2383 // expression, then the conditional operator is not either.
2384 template<typename ConditionalOperator>
2385 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2386 assert(Info.CheckingPotentialConstantExpression);
2387
2388 // Speculatively evaluate both arms.
2389 {
2390 llvm::SmallVector<PartialDiagnosticAt, 8> Diag;
2391 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2392
2393 StmtVisitorTy::Visit(E->getFalseExpr());
2394 if (Diag.empty())
2395 return;
2396
2397 Diag.clear();
2398 StmtVisitorTy::Visit(E->getTrueExpr());
2399 if (Diag.empty())
2400 return;
2401 }
2402
2403 Error(E, diag::note_constexpr_conditional_never_const);
2404 }
2405
2406
2407 template<typename ConditionalOperator>
2408 bool HandleConditionalOperator(const ConditionalOperator *E) {
2409 bool BoolResult;
2410 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2411 if (Info.CheckingPotentialConstantExpression)
2412 CheckPotentialConstantConditional(E);
2413 return false;
2414 }
2415
2416 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2417 return StmtVisitorTy::Visit(EvalExpr);
2418 }
2419
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002420protected:
2421 EvalInfo &Info;
2422 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2423 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2424
Richard Smithdd1f29b2011-12-12 09:28:41 +00002425 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd5093422011-12-12 09:41:58 +00002426 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002427 }
2428
2429 /// Report an evaluation error. This should only be called when an error is
2430 /// first discovered. When propagating an error, just return false.
2431 bool Error(const Expr *E, diag::kind D) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00002432 Info.Diag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002433 return false;
2434 }
2435 bool Error(const Expr *E) {
2436 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2437 }
2438
Richard Smith51201882011-12-30 21:15:51 +00002439 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00002440
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002441public:
2442 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2443
2444 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002445 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002446 }
2447 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002448 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002449 }
2450
2451 RetTy VisitParenExpr(const ParenExpr *E)
2452 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2453 RetTy VisitUnaryExtension(const UnaryOperator *E)
2454 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2455 RetTy VisitUnaryPlus(const UnaryOperator *E)
2456 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2457 RetTy VisitChooseExpr(const ChooseExpr *E)
2458 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2459 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2460 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002461 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2462 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002463 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2464 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002465 // We cannot create any objects for which cleanups are required, so there is
2466 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2467 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2468 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002469
Richard Smithc216a012011-12-12 12:46:16 +00002470 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2471 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2472 return static_cast<Derived*>(this)->VisitCastExpr(E);
2473 }
2474 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2475 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2476 return static_cast<Derived*>(this)->VisitCastExpr(E);
2477 }
2478
Richard Smithe24f5fc2011-11-17 22:56:20 +00002479 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2480 switch (E->getOpcode()) {
2481 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002482 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002483
2484 case BO_Comma:
2485 VisitIgnoredValue(E->getLHS());
2486 return StmtVisitorTy::Visit(E->getRHS());
2487
2488 case BO_PtrMemD:
2489 case BO_PtrMemI: {
2490 LValue Obj;
2491 if (!HandleMemberPointerAccess(Info, E, Obj))
2492 return false;
2493 CCValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002494 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002495 return false;
2496 return DerivedSuccess(Result, E);
2497 }
2498 }
2499 }
2500
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002501 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith74e1ad92012-02-16 02:46:34 +00002502 // Cache the value of the common expression.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002503 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2504 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002505 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002506
Richard Smith74e1ad92012-02-16 02:46:34 +00002507 return HandleConditionalOperator(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002508 }
2509
2510 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002511 bool IsBcpCall = false;
2512 // If the condition (ignoring parens) is a __builtin_constant_p call,
2513 // the result is a constant expression if it can be folded without
2514 // side-effects. This is an important GNU extension. See GCC PR38377
2515 // for discussion.
2516 if (const CallExpr *CallCE =
2517 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2518 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2519 IsBcpCall = true;
2520
2521 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2522 // constant expression; we can't check whether it's potentially foldable.
2523 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2524 return false;
2525
2526 FoldConstant Fold(Info);
2527
Richard Smith74e1ad92012-02-16 02:46:34 +00002528 if (!HandleConditionalOperator(E))
Richard Smithf15fda02012-02-02 01:16:57 +00002529 return false;
2530
2531 if (IsBcpCall)
2532 Fold.Fold(Info);
2533
2534 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002535 }
2536
2537 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002538 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002539 if (!Value) {
2540 const Expr *Source = E->getSourceExpr();
2541 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002542 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002543 if (Source == E) { // sanity checking.
2544 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002545 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002546 }
2547 return StmtVisitorTy::Visit(Source);
2548 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002549 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002550 }
Richard Smithf10d9172011-10-11 21:43:33 +00002551
Richard Smithd0dccea2011-10-28 22:34:42 +00002552 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002553 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002554 QualType CalleeType = Callee->getType();
2555
Richard Smithd0dccea2011-10-28 22:34:42 +00002556 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002557 LValue *This = 0, ThisVal;
2558 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith86c3ae42012-02-13 03:54:03 +00002559 bool HasQualifier = false;
Richard Smith6c957872011-11-10 09:31:24 +00002560
Richard Smith59efe262011-11-11 04:05:33 +00002561 // Extract function decl and 'this' pointer from the callee.
2562 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002563 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002564 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2565 // Explicit bound member calls, such as x.f() or p->g();
2566 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002567 return false;
2568 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002569 This = &ThisVal;
Richard Smith86c3ae42012-02-13 03:54:03 +00002570 HasQualifier = ME->hasQualifier();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002571 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2572 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002573 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2574 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002575 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002576 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002577 return Error(Callee);
2578
2579 FD = dyn_cast<FunctionDecl>(Member);
2580 if (!FD)
2581 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002582 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002583 LValue Call;
2584 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002585 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002586
Richard Smithb4e85ed2012-01-06 16:39:00 +00002587 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002588 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002589 FD = dyn_cast_or_null<FunctionDecl>(
2590 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002591 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002592 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002593
2594 // Overloaded operator calls to member functions are represented as normal
2595 // calls with '*this' as the first argument.
2596 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2597 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002598 // FIXME: When selecting an implicit conversion for an overloaded
2599 // operator delete, we sometimes try to evaluate calls to conversion
2600 // operators without a 'this' parameter!
2601 if (Args.empty())
2602 return Error(E);
2603
Richard Smith59efe262011-11-11 04:05:33 +00002604 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2605 return false;
2606 This = &ThisVal;
2607 Args = Args.slice(1);
2608 }
2609
2610 // Don't call function pointers which have been cast to some other type.
2611 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002612 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002613 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002614 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002615
Richard Smithb04035a2012-02-01 02:39:43 +00002616 if (This && !This->checkSubobject(Info, E, CSK_This))
2617 return false;
2618
Richard Smith86c3ae42012-02-13 03:54:03 +00002619 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2620 // calls to such functions in constant expressions.
2621 if (This && !HasQualifier &&
2622 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2623 return Error(E, diag::note_constexpr_virtual_call);
2624
Richard Smithc1c5f272011-12-13 06:39:58 +00002625 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002626 Stmt *Body = FD->getBody(Definition);
Richard Smith83587db2012-02-15 02:18:13 +00002627 CCValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002628
Richard Smithc1c5f272011-12-13 06:39:58 +00002629 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002630 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2631 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002632 return false;
2633
Richard Smith83587db2012-02-15 02:18:13 +00002634 return DerivedSuccess(Result, E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002635 }
2636
Richard Smithc49bd112011-10-28 17:51:58 +00002637 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2638 return StmtVisitorTy::Visit(E->getInitializer());
2639 }
Richard Smithf10d9172011-10-11 21:43:33 +00002640 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002641 if (E->getNumInits() == 0)
2642 return DerivedZeroInitialization(E);
2643 if (E->getNumInits() == 1)
2644 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002645 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002646 }
2647 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002648 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002649 }
2650 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002651 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002652 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002653 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002654 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002655 }
Richard Smithf10d9172011-10-11 21:43:33 +00002656
Richard Smith180f4792011-11-10 06:34:14 +00002657 /// A member expression where the object is a prvalue is itself a prvalue.
2658 RetTy VisitMemberExpr(const MemberExpr *E) {
2659 assert(!E->isArrow() && "missing call to bound member function?");
2660
2661 CCValue Val;
2662 if (!Evaluate(Val, Info, E->getBase()))
2663 return false;
2664
2665 QualType BaseTy = E->getBase()->getType();
2666
2667 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002668 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002669 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2670 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2671 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2672
Richard Smithb4e85ed2012-01-06 16:39:00 +00002673 SubobjectDesignator Designator(BaseTy);
2674 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002675
Richard Smithf48fdb02011-12-09 22:58:01 +00002676 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002677 DerivedSuccess(Val, E);
2678 }
2679
Richard Smithc49bd112011-10-28 17:51:58 +00002680 RetTy VisitCastExpr(const CastExpr *E) {
2681 switch (E->getCastKind()) {
2682 default:
2683 break;
2684
David Chisnall7a7ee302012-01-16 17:27:18 +00002685 case CK_AtomicToNonAtomic:
2686 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002687 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002688 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002689 return StmtVisitorTy::Visit(E->getSubExpr());
2690
2691 case CK_LValueToRValue: {
2692 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002693 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2694 return false;
2695 CCValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00002696 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2697 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2698 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002699 return false;
2700 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002701 }
2702 }
2703
Richard Smithf48fdb02011-12-09 22:58:01 +00002704 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002705 }
2706
Richard Smith8327fad2011-10-24 18:44:57 +00002707 /// Visit a value which is evaluated, but whose value is ignored.
2708 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002709 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002710 if (!Evaluate(Scratch, Info, E))
2711 Info.EvalStatus.HasSideEffects = true;
2712 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002713};
2714
2715}
2716
2717//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002718// Common base class for lvalue and temporary evaluation.
2719//===----------------------------------------------------------------------===//
2720namespace {
2721template<class Derived>
2722class LValueExprEvaluatorBase
2723 : public ExprEvaluatorBase<Derived, bool> {
2724protected:
2725 LValue &Result;
2726 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2727 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2728
2729 bool Success(APValue::LValueBase B) {
2730 Result.set(B);
2731 return true;
2732 }
2733
2734public:
2735 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2736 ExprEvaluatorBaseTy(Info), Result(Result) {}
2737
2738 bool Success(const CCValue &V, const Expr *E) {
2739 Result.setFrom(V);
2740 return true;
2741 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002742
Richard Smithe24f5fc2011-11-17 22:56:20 +00002743 bool VisitMemberExpr(const MemberExpr *E) {
2744 // Handle non-static data members.
2745 QualType BaseTy;
2746 if (E->isArrow()) {
2747 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2748 return false;
2749 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002750 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002751 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002752 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2753 return false;
2754 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002755 } else {
2756 if (!this->Visit(E->getBase()))
2757 return false;
2758 BaseTy = E->getBase()->getType();
2759 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002760
Richard Smithd9b02e72012-01-25 22:15:11 +00002761 const ValueDecl *MD = E->getMemberDecl();
2762 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2763 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2764 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2765 (void)BaseTy;
2766 HandleLValueMember(this->Info, E, Result, FD);
2767 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2768 HandleLValueIndirectMember(this->Info, E, Result, IFD);
2769 } else
2770 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002771
Richard Smithd9b02e72012-01-25 22:15:11 +00002772 if (MD->getType()->isReferenceType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002773 CCValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002774 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002775 RefValue))
2776 return false;
2777 return Success(RefValue, E);
2778 }
2779 return true;
2780 }
2781
2782 bool VisitBinaryOperator(const BinaryOperator *E) {
2783 switch (E->getOpcode()) {
2784 default:
2785 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2786
2787 case BO_PtrMemD:
2788 case BO_PtrMemI:
2789 return HandleMemberPointerAccess(this->Info, E, Result);
2790 }
2791 }
2792
2793 bool VisitCastExpr(const CastExpr *E) {
2794 switch (E->getCastKind()) {
2795 default:
2796 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2797
2798 case CK_DerivedToBase:
2799 case CK_UncheckedDerivedToBase: {
2800 if (!this->Visit(E->getSubExpr()))
2801 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002802
2803 // Now figure out the necessary offset to add to the base LV to get from
2804 // the derived class to the base class.
2805 QualType Type = E->getSubExpr()->getType();
2806
2807 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2808 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002809 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002810 *PathI))
2811 return false;
2812 Type = (*PathI)->getType();
2813 }
2814
2815 return true;
2816 }
2817 }
2818 }
2819};
2820}
2821
2822//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002823// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002824//
2825// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2826// function designators (in C), decl references to void objects (in C), and
2827// temporaries (if building with -Wno-address-of-temporary).
2828//
2829// LValue evaluation produces values comprising a base expression of one of the
2830// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002831// - Declarations
2832// * VarDecl
2833// * FunctionDecl
2834// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002835// * CompoundLiteralExpr in C
2836// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002837// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002838// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002839// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002840// * ObjCEncodeExpr
2841// * AddrLabelExpr
2842// * BlockExpr
2843// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002844// - Locals and temporaries
Richard Smith83587db2012-02-15 02:18:13 +00002845// * Any Expr, with a CallIndex indicating the function in which the temporary
2846// was evaluated.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002847// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002848//===----------------------------------------------------------------------===//
2849namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002850class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002851 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002852public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002853 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2854 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002855
Richard Smithc49bd112011-10-28 17:51:58 +00002856 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2857
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002858 bool VisitDeclRefExpr(const DeclRefExpr *E);
2859 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002860 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002861 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2862 bool VisitMemberExpr(const MemberExpr *E);
2863 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2864 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002865 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002866 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2867 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002868
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002869 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002870 switch (E->getCastKind()) {
2871 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002872 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002873
Eli Friedmandb924222011-10-11 00:13:24 +00002874 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002875 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002876 if (!Visit(E->getSubExpr()))
2877 return false;
2878 Result.Designator.setInvalid();
2879 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002880
Richard Smithe24f5fc2011-11-17 22:56:20 +00002881 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002882 if (!Visit(E->getSubExpr()))
2883 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002884 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002885 }
2886 }
Sebastian Redlcea8d962011-09-24 17:48:14 +00002887
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002888 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002889
Eli Friedman4efaa272008-11-12 09:44:48 +00002890};
2891} // end anonymous namespace
2892
Richard Smithc49bd112011-10-28 17:51:58 +00002893/// Evaluate an expression as an lvalue. This can be legitimately called on
2894/// expressions which are not glvalues, in a few cases:
2895/// * function designators in C,
2896/// * "extern void" objects,
2897/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002898static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002899 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2900 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2901 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002902 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002903}
2904
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002905bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002906 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2907 return Success(FD);
2908 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002909 return VisitVarDecl(E, VD);
2910 return Error(E);
2911}
Richard Smith436c8892011-10-24 23:14:33 +00002912
Richard Smithc49bd112011-10-28 17:51:58 +00002913bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002914 if (!VD->getType()->isReferenceType()) {
2915 if (isa<ParmVarDecl>(VD)) {
Richard Smith83587db2012-02-15 02:18:13 +00002916 Result.set(VD, Info.CurrentCall->Index);
Richard Smith177dce72011-11-01 16:57:24 +00002917 return true;
2918 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002919 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002920 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002921
Richard Smith47a1eed2011-10-29 20:57:55 +00002922 CCValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002923 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2924 return false;
2925 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002926}
2927
Richard Smithbd552ef2011-10-31 05:52:43 +00002928bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2929 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002930 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002931 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002932 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2933
Richard Smith83587db2012-02-15 02:18:13 +00002934 Result.set(E, Info.CurrentCall->Index);
2935 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2936 Result, E->GetTemporaryExpr());
Richard Smithe24f5fc2011-11-17 22:56:20 +00002937 }
2938
2939 // Materialization of an lvalue temporary occurs when we need to force a copy
2940 // (for instance, if it's a bitfield).
2941 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2942 if (!Visit(E->GetTemporaryExpr()))
2943 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002944 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002945 Info.CurrentCall->Temporaries[E]))
2946 return false;
Richard Smith83587db2012-02-15 02:18:13 +00002947 Result.set(E, Info.CurrentCall->Index);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002948 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002949}
2950
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002951bool
2952LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002953 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2954 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2955 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002956 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002957}
2958
Richard Smith47d21452011-12-27 12:18:28 +00002959bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2960 if (E->isTypeOperand())
2961 return Success(E);
2962 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2963 if (RD && RD->isPolymorphic()) {
2964 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2965 << E->getExprOperand()->getType()
2966 << E->getExprOperand()->getSourceRange();
2967 return false;
2968 }
2969 return Success(E);
2970}
2971
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002972bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002973 // Handle static data members.
2974 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2975 VisitIgnoredValue(E->getBase());
2976 return VisitVarDecl(E, VD);
2977 }
2978
Richard Smithd0dccea2011-10-28 22:34:42 +00002979 // Handle static member functions.
2980 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2981 if (MD->isStatic()) {
2982 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002983 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002984 }
2985 }
2986
Richard Smith180f4792011-11-10 06:34:14 +00002987 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002988 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002989}
2990
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002991bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002992 // FIXME: Deal with vectors as array subscript bases.
2993 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002994 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002995
Anders Carlsson3068d112008-11-16 19:01:22 +00002996 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002997 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002998
Anders Carlsson3068d112008-11-16 19:01:22 +00002999 APSInt Index;
3000 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003001 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003002 int64_t IndexValue
3003 = Index.isSigned() ? Index.getSExtValue()
3004 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00003005
Richard Smithb4e85ed2012-01-06 16:39:00 +00003006 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00003007}
Eli Friedman4efaa272008-11-12 09:44:48 +00003008
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003009bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00003010 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00003011}
3012
Eli Friedman4efaa272008-11-12 09:44:48 +00003013//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003014// Pointer Evaluation
3015//===----------------------------------------------------------------------===//
3016
Anders Carlssonc754aa62008-07-08 05:13:58 +00003017namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003018class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003019 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00003020 LValue &Result;
3021
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003022 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003023 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00003024 return true;
3025 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003026public:
Mike Stump1eb44332009-09-09 15:08:12 +00003027
John McCallefdb83e2010-05-07 21:00:08 +00003028 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003029 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003030
Richard Smith47a1eed2011-10-29 20:57:55 +00003031 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003032 Result.setFrom(V);
3033 return true;
3034 }
Richard Smith51201882011-12-30 21:15:51 +00003035 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00003036 return Success((Expr*)0);
3037 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003038
John McCallefdb83e2010-05-07 21:00:08 +00003039 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003040 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00003041 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003042 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00003043 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003044 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00003045 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003046 bool VisitCallExpr(const CallExpr *E);
3047 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00003048 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00003049 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00003050 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00003051 }
Richard Smith180f4792011-11-10 06:34:14 +00003052 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3053 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00003054 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003055 Result = *Info.CurrentCall->This;
3056 return true;
3057 }
John McCall56ca35d2011-02-17 10:25:35 +00003058
Eli Friedmanba98d6b2009-03-23 04:56:01 +00003059 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00003060};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003061} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003062
John McCallefdb83e2010-05-07 21:00:08 +00003063static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003064 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003065 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003066}
3067
John McCallefdb83e2010-05-07 21:00:08 +00003068bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003069 if (E->getOpcode() != BO_Add &&
3070 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00003071 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003072
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003073 const Expr *PExp = E->getLHS();
3074 const Expr *IExp = E->getRHS();
3075 if (IExp->getType()->isPointerType())
3076 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003077
Richard Smith745f5142012-01-27 01:14:48 +00003078 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3079 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00003080 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003081
John McCallefdb83e2010-05-07 21:00:08 +00003082 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00003083 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00003084 return false;
3085 int64_t AdditionalOffset
3086 = Offset.isSigned() ? Offset.getSExtValue()
3087 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00003088 if (E->getOpcode() == BO_Sub)
3089 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003090
Richard Smith180f4792011-11-10 06:34:14 +00003091 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00003092 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3093 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003094}
Eli Friedman4efaa272008-11-12 09:44:48 +00003095
John McCallefdb83e2010-05-07 21:00:08 +00003096bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3097 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003098}
Mike Stump1eb44332009-09-09 15:08:12 +00003099
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003100bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3101 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003102
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003103 switch (E->getCastKind()) {
3104 default:
3105 break;
3106
John McCall2de56d12010-08-25 11:45:40 +00003107 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003108 case CK_CPointerToObjCPointerCast:
3109 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00003110 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00003111 if (!Visit(SubExpr))
3112 return false;
Richard Smithc216a012011-12-12 12:46:16 +00003113 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3114 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3115 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003116 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00003117 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003118 if (SubExpr->getType()->isVoidPointerType())
3119 CCEDiag(E, diag::note_constexpr_invalid_cast)
3120 << 3 << SubExpr->getType();
3121 else
3122 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3123 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003124 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003125
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003126 case CK_DerivedToBase:
3127 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00003128 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003129 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003130 if (!Result.Base && Result.Offset.isZero())
3131 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003132
Richard Smith180f4792011-11-10 06:34:14 +00003133 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003134 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00003135 QualType Type =
3136 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003137
Richard Smith180f4792011-11-10 06:34:14 +00003138 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003139 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003140 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3141 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003142 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003143 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003144 }
3145
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003146 return true;
3147 }
3148
Richard Smithe24f5fc2011-11-17 22:56:20 +00003149 case CK_BaseToDerived:
3150 if (!Visit(E->getSubExpr()))
3151 return false;
3152 if (!Result.Base && Result.Offset.isZero())
3153 return true;
3154 return HandleBaseToDerivedCast(Info, E, Result);
3155
Richard Smith47a1eed2011-10-29 20:57:55 +00003156 case CK_NullToPointer:
Richard Smith51201882011-12-30 21:15:51 +00003157 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00003158
John McCall2de56d12010-08-25 11:45:40 +00003159 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003160 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3161
Richard Smith47a1eed2011-10-29 20:57:55 +00003162 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003163 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003164 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003165
John McCallefdb83e2010-05-07 21:00:08 +00003166 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003167 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3168 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003169 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003170 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith83587db2012-02-15 02:18:13 +00003171 Result.CallIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003172 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003173 return true;
3174 } else {
3175 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00003176 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00003177 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003178 }
3179 }
John McCall2de56d12010-08-25 11:45:40 +00003180 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003181 if (SubExpr->isGLValue()) {
3182 if (!EvaluateLValue(SubExpr, Result, Info))
3183 return false;
3184 } else {
Richard Smith83587db2012-02-15 02:18:13 +00003185 Result.set(SubExpr, Info.CurrentCall->Index);
3186 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3187 Info, Result, SubExpr))
Richard Smithe24f5fc2011-11-17 22:56:20 +00003188 return false;
3189 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003190 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003191 if (const ConstantArrayType *CAT
3192 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3193 Result.addArray(Info, E, CAT);
3194 else
3195 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003196 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003197
John McCall2de56d12010-08-25 11:45:40 +00003198 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003199 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003200 }
3201
Richard Smithc49bd112011-10-28 17:51:58 +00003202 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003203}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003204
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003205bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003206 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003207 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003208
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003209 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003210}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003211
3212//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003213// Member Pointer Evaluation
3214//===----------------------------------------------------------------------===//
3215
3216namespace {
3217class MemberPointerExprEvaluator
3218 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3219 MemberPtr &Result;
3220
3221 bool Success(const ValueDecl *D) {
3222 Result = MemberPtr(D);
3223 return true;
3224 }
3225public:
3226
3227 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3228 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3229
3230 bool Success(const CCValue &V, const Expr *E) {
3231 Result.setFrom(V);
3232 return true;
3233 }
Richard Smith51201882011-12-30 21:15:51 +00003234 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003235 return Success((const ValueDecl*)0);
3236 }
3237
3238 bool VisitCastExpr(const CastExpr *E);
3239 bool VisitUnaryAddrOf(const UnaryOperator *E);
3240};
3241} // end anonymous namespace
3242
3243static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3244 EvalInfo &Info) {
3245 assert(E->isRValue() && E->getType()->isMemberPointerType());
3246 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3247}
3248
3249bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3250 switch (E->getCastKind()) {
3251 default:
3252 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3253
3254 case CK_NullToMemberPointer:
Richard Smith51201882011-12-30 21:15:51 +00003255 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003256
3257 case CK_BaseToDerivedMemberPointer: {
3258 if (!Visit(E->getSubExpr()))
3259 return false;
3260 if (E->path_empty())
3261 return true;
3262 // Base-to-derived member pointer casts store the path in derived-to-base
3263 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3264 // the wrong end of the derived->base arc, so stagger the path by one class.
3265 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3266 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3267 PathI != PathE; ++PathI) {
3268 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3269 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3270 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003271 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003272 }
3273 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3274 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003275 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003276 return true;
3277 }
3278
3279 case CK_DerivedToBaseMemberPointer:
3280 if (!Visit(E->getSubExpr()))
3281 return false;
3282 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3283 PathE = E->path_end(); PathI != PathE; ++PathI) {
3284 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3285 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3286 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003287 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003288 }
3289 return true;
3290 }
3291}
3292
3293bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3294 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3295 // member can be formed.
3296 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3297}
3298
3299//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003300// Record Evaluation
3301//===----------------------------------------------------------------------===//
3302
3303namespace {
3304 class RecordExprEvaluator
3305 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3306 const LValue &This;
3307 APValue &Result;
3308 public:
3309
3310 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3311 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3312
3313 bool Success(const CCValue &V, const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003314 Result = V;
3315 return true;
Richard Smith180f4792011-11-10 06:34:14 +00003316 }
Richard Smith51201882011-12-30 21:15:51 +00003317 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003318
Richard Smith59efe262011-11-11 04:05:33 +00003319 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003320 bool VisitInitListExpr(const InitListExpr *E);
3321 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3322 };
3323}
3324
Richard Smith51201882011-12-30 21:15:51 +00003325/// Perform zero-initialization on an object of non-union class type.
3326/// C++11 [dcl.init]p5:
3327/// To zero-initialize an object or reference of type T means:
3328/// [...]
3329/// -- if T is a (possibly cv-qualified) non-union class type,
3330/// each non-static data member and each base-class subobject is
3331/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003332static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3333 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003334 const LValue &This, APValue &Result) {
3335 assert(!RD->isUnion() && "Expected non-union class type");
3336 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3337 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3338 std::distance(RD->field_begin(), RD->field_end()));
3339
3340 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3341
3342 if (CD) {
3343 unsigned Index = 0;
3344 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003345 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003346 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3347 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003348 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3349 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003350 Result.getStructBase(Index)))
3351 return false;
3352 }
3353 }
3354
Richard Smithb4e85ed2012-01-06 16:39:00 +00003355 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3356 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003357 // -- if T is a reference type, no initialization is performed.
3358 if ((*I)->getType()->isReferenceType())
3359 continue;
3360
3361 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003362 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smith51201882011-12-30 21:15:51 +00003363
3364 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003365 if (!EvaluateInPlace(
Richard Smith51201882011-12-30 21:15:51 +00003366 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3367 return false;
3368 }
3369
3370 return true;
3371}
3372
3373bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3374 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3375 if (RD->isUnion()) {
3376 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3377 // object's first non-static named data member is zero-initialized
3378 RecordDecl::field_iterator I = RD->field_begin();
3379 if (I == RD->field_end()) {
3380 Result = APValue((const FieldDecl*)0);
3381 return true;
3382 }
3383
3384 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003385 HandleLValueMember(Info, E, Subobject, *I);
Richard Smith51201882011-12-30 21:15:51 +00003386 Result = APValue(*I);
3387 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003388 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003389 }
3390
Richard Smithce582fe2012-02-17 00:44:16 +00003391 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
3392 Info.Diag(E->getExprLoc(), diag::note_constexpr_virtual_base) << RD;
3393 return false;
3394 }
3395
Richard Smithb4e85ed2012-01-06 16:39:00 +00003396 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003397}
3398
Richard Smith59efe262011-11-11 04:05:33 +00003399bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3400 switch (E->getCastKind()) {
3401 default:
3402 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3403
3404 case CK_ConstructorConversion:
3405 return Visit(E->getSubExpr());
3406
3407 case CK_DerivedToBase:
3408 case CK_UncheckedDerivedToBase: {
3409 CCValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003410 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003411 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003412 if (!DerivedObject.isStruct())
3413 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003414
3415 // Derived-to-base rvalue conversion: just slice off the derived part.
3416 APValue *Value = &DerivedObject;
3417 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3418 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3419 PathE = E->path_end(); PathI != PathE; ++PathI) {
3420 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3421 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3422 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3423 RD = Base;
3424 }
3425 Result = *Value;
3426 return true;
3427 }
3428 }
3429}
3430
Richard Smith180f4792011-11-10 06:34:14 +00003431bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3432 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3433 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3434
3435 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003436 const FieldDecl *Field = E->getInitializedFieldInUnion();
3437 Result = APValue(Field);
3438 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003439 return true;
Richard Smithec789162012-01-12 18:54:33 +00003440
3441 // If the initializer list for a union does not contain any elements, the
3442 // first element of the union is value-initialized.
3443 ImplicitValueInitExpr VIE(Field->getType());
3444 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3445
Richard Smith180f4792011-11-10 06:34:14 +00003446 LValue Subobject = This;
Richard Smithec789162012-01-12 18:54:33 +00003447 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
Richard Smith83587db2012-02-15 02:18:13 +00003448 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003449 }
3450
3451 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3452 "initializer list for class with base classes");
3453 Result = APValue(APValue::UninitStruct(), 0,
3454 std::distance(RD->field_begin(), RD->field_end()));
3455 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003456 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003457 for (RecordDecl::field_iterator Field = RD->field_begin(),
3458 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3459 // Anonymous bit-fields are not considered members of the class for
3460 // purposes of aggregate initialization.
3461 if (Field->isUnnamedBitfield())
3462 continue;
3463
3464 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003465
Richard Smith745f5142012-01-27 01:14:48 +00003466 bool HaveInit = ElementNo < E->getNumInits();
3467
3468 // FIXME: Diagnostics here should point to the end of the initializer
3469 // list, not the start.
3470 HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3471 *Field, &Layout);
3472
3473 // Perform an implicit value-initialization for members beyond the end of
3474 // the initializer list.
3475 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3476
Richard Smith83587db2012-02-15 02:18:13 +00003477 if (!EvaluateInPlace(
Richard Smith745f5142012-01-27 01:14:48 +00003478 Result.getStructField((*Field)->getFieldIndex()),
3479 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3480 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003481 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003482 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003483 }
3484 }
3485
Richard Smith745f5142012-01-27 01:14:48 +00003486 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003487}
3488
3489bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3490 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith51201882011-12-30 21:15:51 +00003491 bool ZeroInit = E->requiresZeroInitialization();
3492 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003493 // If we've already performed zero-initialization, we're already done.
3494 if (!Result.isUninit())
3495 return true;
3496
Richard Smith51201882011-12-30 21:15:51 +00003497 if (ZeroInit)
3498 return ZeroInitialization(E);
3499
Richard Smith61802452011-12-22 02:22:31 +00003500 const CXXRecordDecl *RD = FD->getParent();
3501 if (RD->isUnion())
3502 Result = APValue((FieldDecl*)0);
3503 else
3504 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3505 std::distance(RD->field_begin(), RD->field_end()));
3506 return true;
3507 }
3508
Richard Smith180f4792011-11-10 06:34:14 +00003509 const FunctionDecl *Definition = 0;
3510 FD->getBody(Definition);
3511
Richard Smithc1c5f272011-12-13 06:39:58 +00003512 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3513 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003514
Richard Smith610a60c2012-01-10 04:32:03 +00003515 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003516 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003517 if (const MaterializeTemporaryExpr *ME
3518 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3519 return Visit(ME->GetTemporaryExpr());
3520
Richard Smith51201882011-12-30 21:15:51 +00003521 if (ZeroInit && !ZeroInitialization(E))
3522 return false;
3523
Richard Smith180f4792011-11-10 06:34:14 +00003524 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003525 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003526 cast<CXXConstructorDecl>(Definition), Info,
3527 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003528}
3529
3530static bool EvaluateRecord(const Expr *E, const LValue &This,
3531 APValue &Result, EvalInfo &Info) {
3532 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003533 "can't evaluate expression as a record rvalue");
3534 return RecordExprEvaluator(Info, This, Result).Visit(E);
3535}
3536
3537//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003538// Temporary Evaluation
3539//
3540// Temporaries are represented in the AST as rvalues, but generally behave like
3541// lvalues. The full-object of which the temporary is a subobject is implicitly
3542// materialized so that a reference can bind to it.
3543//===----------------------------------------------------------------------===//
3544namespace {
3545class TemporaryExprEvaluator
3546 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3547public:
3548 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3549 LValueExprEvaluatorBaseTy(Info, Result) {}
3550
3551 /// Visit an expression which constructs the value of this temporary.
3552 bool VisitConstructExpr(const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003553 Result.set(E, Info.CurrentCall->Index);
3554 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003555 }
3556
3557 bool VisitCastExpr(const CastExpr *E) {
3558 switch (E->getCastKind()) {
3559 default:
3560 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3561
3562 case CK_ConstructorConversion:
3563 return VisitConstructExpr(E->getSubExpr());
3564 }
3565 }
3566 bool VisitInitListExpr(const InitListExpr *E) {
3567 return VisitConstructExpr(E);
3568 }
3569 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3570 return VisitConstructExpr(E);
3571 }
3572 bool VisitCallExpr(const CallExpr *E) {
3573 return VisitConstructExpr(E);
3574 }
3575};
3576} // end anonymous namespace
3577
3578/// Evaluate an expression of record type as a temporary.
3579static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003580 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003581 return TemporaryExprEvaluator(Info, Result).Visit(E);
3582}
3583
3584//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003585// Vector Evaluation
3586//===----------------------------------------------------------------------===//
3587
3588namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003589 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003590 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3591 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003592 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003593
Richard Smith07fc6572011-10-22 21:10:00 +00003594 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3595 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003596
Richard Smith07fc6572011-10-22 21:10:00 +00003597 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3598 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3599 // FIXME: remove this APValue copy.
3600 Result = APValue(V.data(), V.size());
3601 return true;
3602 }
Richard Smith69c2c502011-11-04 05:33:44 +00003603 bool Success(const CCValue &V, const Expr *E) {
3604 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003605 Result = V;
3606 return true;
3607 }
Richard Smith51201882011-12-30 21:15:51 +00003608 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003609
Richard Smith07fc6572011-10-22 21:10:00 +00003610 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003611 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003612 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003613 bool VisitInitListExpr(const InitListExpr *E);
3614 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003615 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003616 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003617 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003618 };
3619} // end anonymous namespace
3620
3621static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003622 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003623 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003624}
3625
Richard Smith07fc6572011-10-22 21:10:00 +00003626bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3627 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003628 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003629
Richard Smithd62ca372011-12-06 22:44:34 +00003630 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003631 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003632
Eli Friedman46a52322011-03-25 00:43:55 +00003633 switch (E->getCastKind()) {
3634 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003635 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003636 if (SETy->isIntegerType()) {
3637 APSInt IntResult;
3638 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003639 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003640 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003641 } else if (SETy->isRealFloatingType()) {
3642 APFloat F(0.0);
3643 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003644 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003645 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003646 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003647 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003648 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003649
3650 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003651 SmallVector<APValue, 4> Elts(NElts, Val);
3652 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003653 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003654 case CK_BitCast: {
3655 // Evaluate the operand into an APInt we can extract from.
3656 llvm::APInt SValInt;
3657 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3658 return false;
3659 // Extract the elements
3660 QualType EltTy = VTy->getElementType();
3661 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3662 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3663 SmallVector<APValue, 4> Elts;
3664 if (EltTy->isRealFloatingType()) {
3665 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3666 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3667 unsigned FloatEltSize = EltSize;
3668 if (&Sem == &APFloat::x87DoubleExtended)
3669 FloatEltSize = 80;
3670 for (unsigned i = 0; i < NElts; i++) {
3671 llvm::APInt Elt;
3672 if (BigEndian)
3673 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3674 else
3675 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3676 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3677 }
3678 } else if (EltTy->isIntegerType()) {
3679 for (unsigned i = 0; i < NElts; i++) {
3680 llvm::APInt Elt;
3681 if (BigEndian)
3682 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3683 else
3684 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3685 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3686 }
3687 } else {
3688 return Error(E);
3689 }
3690 return Success(Elts, E);
3691 }
Eli Friedman46a52322011-03-25 00:43:55 +00003692 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003693 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003694 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003695}
3696
Richard Smith07fc6572011-10-22 21:10:00 +00003697bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003698VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003699 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003700 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003701 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003702
Nate Begeman59b5da62009-01-18 03:20:47 +00003703 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003704 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003705
Eli Friedman3edd5a92012-01-03 23:24:20 +00003706 // The number of initializers can be less than the number of
3707 // vector elements. For OpenCL, this can be due to nested vector
3708 // initialization. For GCC compatibility, missing trailing elements
3709 // should be initialized with zeroes.
3710 unsigned CountInits = 0, CountElts = 0;
3711 while (CountElts < NumElements) {
3712 // Handle nested vector initialization.
3713 if (CountInits < NumInits
3714 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3715 APValue v;
3716 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3717 return Error(E);
3718 unsigned vlen = v.getVectorLength();
3719 for (unsigned j = 0; j < vlen; j++)
3720 Elements.push_back(v.getVectorElt(j));
3721 CountElts += vlen;
3722 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003723 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003724 if (CountInits < NumInits) {
3725 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3726 return Error(E);
3727 } else // trailing integer zero.
3728 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3729 Elements.push_back(APValue(sInt));
3730 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003731 } else {
3732 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003733 if (CountInits < NumInits) {
3734 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3735 return Error(E);
3736 } else // trailing float zero.
3737 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3738 Elements.push_back(APValue(f));
3739 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003740 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003741 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003742 }
Richard Smith07fc6572011-10-22 21:10:00 +00003743 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003744}
3745
Richard Smith07fc6572011-10-22 21:10:00 +00003746bool
Richard Smith51201882011-12-30 21:15:51 +00003747VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003748 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003749 QualType EltTy = VT->getElementType();
3750 APValue ZeroElement;
3751 if (EltTy->isIntegerType())
3752 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3753 else
3754 ZeroElement =
3755 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3756
Chris Lattner5f9e2722011-07-23 10:55:15 +00003757 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003758 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003759}
3760
Richard Smith07fc6572011-10-22 21:10:00 +00003761bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003762 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003763 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003764}
3765
Nate Begeman59b5da62009-01-18 03:20:47 +00003766//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003767// Array Evaluation
3768//===----------------------------------------------------------------------===//
3769
3770namespace {
3771 class ArrayExprEvaluator
3772 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003773 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003774 APValue &Result;
3775 public:
3776
Richard Smith180f4792011-11-10 06:34:14 +00003777 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3778 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003779
3780 bool Success(const APValue &V, const Expr *E) {
Richard Smithf3908f22012-02-17 03:35:37 +00003781 assert((V.isArray() || V.isLValue()) &&
3782 "expected array or string literal");
Richard Smithcc5d4f62011-11-07 09:22:26 +00003783 Result = V;
3784 return true;
3785 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003786
Richard Smith51201882011-12-30 21:15:51 +00003787 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003788 const ConstantArrayType *CAT =
3789 Info.Ctx.getAsConstantArrayType(E->getType());
3790 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003791 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003792
3793 Result = APValue(APValue::UninitArray(), 0,
3794 CAT->getSize().getZExtValue());
3795 if (!Result.hasArrayFiller()) return true;
3796
Richard Smith51201882011-12-30 21:15:51 +00003797 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003798 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003799 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003800 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003801 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith180f4792011-11-10 06:34:14 +00003802 }
3803
Richard Smithcc5d4f62011-11-07 09:22:26 +00003804 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003805 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003806 };
3807} // end anonymous namespace
3808
Richard Smith180f4792011-11-10 06:34:14 +00003809static bool EvaluateArray(const Expr *E, const LValue &This,
3810 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003811 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003812 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003813}
3814
3815bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3816 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3817 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003818 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003819
Richard Smith974c5f92011-12-22 01:07:19 +00003820 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3821 // an appropriately-typed string literal enclosed in braces.
Richard Smithec789162012-01-12 18:54:33 +00003822 if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
Richard Smith974c5f92011-12-22 01:07:19 +00003823 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3824 LValue LV;
3825 if (!EvaluateLValue(E->getInit(0), LV, Info))
3826 return false;
Richard Smithf3908f22012-02-17 03:35:37 +00003827 CCValue Val;
3828 LV.moveInto(Val);
3829 return Success(Val, E);
Richard Smith974c5f92011-12-22 01:07:19 +00003830 }
3831
Richard Smith745f5142012-01-27 01:14:48 +00003832 bool Success = true;
3833
Richard Smithcc5d4f62011-11-07 09:22:26 +00003834 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3835 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003836 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003837 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003838 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003839 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003840 I != End; ++I, ++Index) {
Richard Smith83587db2012-02-15 02:18:13 +00003841 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3842 Info, Subobject, cast<Expr>(*I)) ||
Richard Smith745f5142012-01-27 01:14:48 +00003843 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3844 CAT->getElementType(), 1)) {
3845 if (!Info.keepEvaluatingAfterFailure())
3846 return false;
3847 Success = false;
3848 }
Richard Smith180f4792011-11-10 06:34:14 +00003849 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003850
Richard Smith745f5142012-01-27 01:14:48 +00003851 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003852 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003853 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3854 // but sometimes does:
3855 // struct S { constexpr S() : p(&p) {} void *p; };
3856 // S s[10] = {};
Richard Smith83587db2012-02-15 02:18:13 +00003857 return EvaluateInPlace(Result.getArrayFiller(), Info,
3858 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003859}
3860
Richard Smithe24f5fc2011-11-17 22:56:20 +00003861bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3862 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3863 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003864 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003865
Richard Smithec789162012-01-12 18:54:33 +00003866 bool HadZeroInit = !Result.isUninit();
3867 if (!HadZeroInit)
3868 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003869 if (!Result.hasArrayFiller())
3870 return true;
3871
3872 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003873
Richard Smith51201882011-12-30 21:15:51 +00003874 bool ZeroInit = E->requiresZeroInitialization();
3875 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003876 if (HadZeroInit)
3877 return true;
3878
Richard Smith51201882011-12-30 21:15:51 +00003879 if (ZeroInit) {
3880 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003881 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003882 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003883 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003884 }
3885
Richard Smith61802452011-12-22 02:22:31 +00003886 const CXXRecordDecl *RD = FD->getParent();
3887 if (RD->isUnion())
3888 Result.getArrayFiller() = APValue((FieldDecl*)0);
3889 else
3890 Result.getArrayFiller() =
3891 APValue(APValue::UninitStruct(), RD->getNumBases(),
3892 std::distance(RD->field_begin(), RD->field_end()));
3893 return true;
3894 }
3895
Richard Smithe24f5fc2011-11-17 22:56:20 +00003896 const FunctionDecl *Definition = 0;
3897 FD->getBody(Definition);
3898
Richard Smithc1c5f272011-12-13 06:39:58 +00003899 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3900 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003901
3902 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3903 // but sometimes does:
3904 // struct S { constexpr S() : p(&p) {} void *p; };
3905 // S s[10];
3906 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003907 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003908
Richard Smithec789162012-01-12 18:54:33 +00003909 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003910 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003911 if (!EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003912 return false;
3913 }
3914
Richard Smithe24f5fc2011-11-17 22:56:20 +00003915 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003916 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003917 cast<CXXConstructorDecl>(Definition),
3918 Info, Result.getArrayFiller());
3919}
3920
Richard Smithcc5d4f62011-11-07 09:22:26 +00003921//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003922// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003923//
3924// As a GNU extension, we support casting pointers to sufficiently-wide integer
3925// types and back in constant folding. Integer values are thus represented
3926// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003927//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003928
3929namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003930class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003931 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00003932 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003933public:
Richard Smith47a1eed2011-10-29 20:57:55 +00003934 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003935 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003936
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003937 bool Success(const llvm::APSInt &SI, const Expr *E) {
3938 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003939 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003940 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003941 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003942 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003943 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003944 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003945 return true;
3946 }
3947
Daniel Dunbar131eb432009-02-19 09:06:44 +00003948 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003949 assert(E->getType()->isIntegralOrEnumerationType() &&
3950 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003951 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003952 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003953 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003954 Result.getInt().setIsUnsigned(
3955 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003956 return true;
3957 }
3958
3959 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003960 assert(E->getType()->isIntegralOrEnumerationType() &&
3961 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003962 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003963 return true;
3964 }
3965
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003966 bool Success(CharUnits Size, const Expr *E) {
3967 return Success(Size.getQuantity(), E);
3968 }
3969
Richard Smith47a1eed2011-10-29 20:57:55 +00003970 bool Success(const CCValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00003971 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00003972 Result = V;
3973 return true;
3974 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003975 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003976 }
Mike Stump1eb44332009-09-09 15:08:12 +00003977
Richard Smith51201882011-12-30 21:15:51 +00003978 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00003979
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003980 //===--------------------------------------------------------------------===//
3981 // Visitor Methods
3982 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003983
Chris Lattner4c4867e2008-07-12 00:38:25 +00003984 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003985 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003986 }
3987 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003988 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003989 }
Eli Friedman04309752009-11-24 05:28:59 +00003990
3991 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3992 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003993 if (CheckReferencedDecl(E, E->getDecl()))
3994 return true;
3995
3996 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003997 }
3998 bool VisitMemberExpr(const MemberExpr *E) {
3999 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00004000 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00004001 return true;
4002 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004003
4004 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004005 }
4006
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004007 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004008 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004009 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004010 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00004011
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004012 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004013 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00004014
Anders Carlsson3068d112008-11-16 19:01:22 +00004015 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004016 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00004017 }
Mike Stump1eb44332009-09-09 15:08:12 +00004018
Richard Smithf10d9172011-10-11 21:43:33 +00004019 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00004020 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00004021 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00004022 }
4023
Sebastian Redl64b45f72009-01-05 20:52:13 +00004024 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00004025 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00004026 }
4027
Francois Pichet6ad6f282010-12-07 00:08:36 +00004028 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4029 return Success(E->getValue(), E);
4030 }
4031
John Wiegley21ff2e52011-04-28 00:16:57 +00004032 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4033 return Success(E->getValue(), E);
4034 }
4035
John Wiegley55262202011-04-25 06:54:41 +00004036 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4037 return Success(E->getValue(), E);
4038 }
4039
Eli Friedman722c7172009-02-28 03:59:05 +00004040 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004041 bool VisitUnaryImag(const UnaryOperator *E);
4042
Sebastian Redl295995c2010-09-10 20:55:47 +00004043 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00004044 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004045
Chris Lattnerfcee0012008-07-11 21:24:13 +00004046private:
Ken Dyck8b752f12010-01-27 17:10:57 +00004047 CharUnits GetAlignOfExpr(const Expr *E);
4048 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004049 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004050 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004051 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004052};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004053} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00004054
Richard Smithc49bd112011-10-28 17:51:58 +00004055/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4056/// produce either the integer value or a pointer.
4057///
4058/// GCC has a heinous extension which folds casts between pointer types and
4059/// pointer-sized integral types. We support this by allowing the evaluation of
4060/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4061/// Some simple arithmetic on such values is supported (they are treated much
4062/// like char*).
Richard Smithf48fdb02011-12-09 22:58:01 +00004063static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00004064 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004065 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004066 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004067}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004068
Richard Smithf48fdb02011-12-09 22:58:01 +00004069static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004070 CCValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00004071 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004072 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004073 if (!Val.isInt()) {
4074 // FIXME: It would be better to produce the diagnostic for casting
4075 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00004076 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00004077 return false;
4078 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004079 Result = Val.getInt();
4080 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00004081}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004082
Richard Smithf48fdb02011-12-09 22:58:01 +00004083/// Check whether the given declaration can be directly converted to an integral
4084/// rvalue. If not, no diagnostic is produced; there are other things we can
4085/// try.
Eli Friedman04309752009-11-24 05:28:59 +00004086bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00004087 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004088 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004089 // Check for signedness/width mismatches between E type and ECD value.
4090 bool SameSign = (ECD->getInitVal().isSigned()
4091 == E->getType()->isSignedIntegerOrEnumerationType());
4092 bool SameWidth = (ECD->getInitVal().getBitWidth()
4093 == Info.Ctx.getIntWidth(E->getType()));
4094 if (SameSign && SameWidth)
4095 return Success(ECD->getInitVal(), E);
4096 else {
4097 // Get rid of mismatch (otherwise Success assertions will fail)
4098 // by computing a new value matching the type of E.
4099 llvm::APSInt Val = ECD->getInitVal();
4100 if (!SameSign)
4101 Val.setIsSigned(!ECD->getInitVal().isSigned());
4102 if (!SameWidth)
4103 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4104 return Success(Val, E);
4105 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004106 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004107 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00004108}
4109
Chris Lattnera4d55d82008-10-06 06:40:35 +00004110/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4111/// as GCC.
4112static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4113 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004114 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00004115 enum gcc_type_class {
4116 no_type_class = -1,
4117 void_type_class, integer_type_class, char_type_class,
4118 enumeral_type_class, boolean_type_class,
4119 pointer_type_class, reference_type_class, offset_type_class,
4120 real_type_class, complex_type_class,
4121 function_type_class, method_type_class,
4122 record_type_class, union_type_class,
4123 array_type_class, string_type_class,
4124 lang_type_class
4125 };
Mike Stump1eb44332009-09-09 15:08:12 +00004126
4127 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00004128 // ideal, however it is what gcc does.
4129 if (E->getNumArgs() == 0)
4130 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00004131
Chris Lattnera4d55d82008-10-06 06:40:35 +00004132 QualType ArgTy = E->getArg(0)->getType();
4133 if (ArgTy->isVoidType())
4134 return void_type_class;
4135 else if (ArgTy->isEnumeralType())
4136 return enumeral_type_class;
4137 else if (ArgTy->isBooleanType())
4138 return boolean_type_class;
4139 else if (ArgTy->isCharType())
4140 return string_type_class; // gcc doesn't appear to use char_type_class
4141 else if (ArgTy->isIntegerType())
4142 return integer_type_class;
4143 else if (ArgTy->isPointerType())
4144 return pointer_type_class;
4145 else if (ArgTy->isReferenceType())
4146 return reference_type_class;
4147 else if (ArgTy->isRealType())
4148 return real_type_class;
4149 else if (ArgTy->isComplexType())
4150 return complex_type_class;
4151 else if (ArgTy->isFunctionType())
4152 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004153 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004154 return record_type_class;
4155 else if (ArgTy->isUnionType())
4156 return union_type_class;
4157 else if (ArgTy->isArrayType())
4158 return array_type_class;
4159 else if (ArgTy->isUnionType())
4160 return union_type_class;
4161 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004162 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004163}
4164
Richard Smith80d4b552011-12-28 19:48:30 +00004165/// EvaluateBuiltinConstantPForLValue - Determine the result of
4166/// __builtin_constant_p when applied to the given lvalue.
4167///
4168/// An lvalue is only "constant" if it is a pointer or reference to the first
4169/// character of a string literal.
4170template<typename LValue>
4171static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
4172 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
4173 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4174}
4175
4176/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4177/// GCC as we can manage.
4178static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4179 QualType ArgType = Arg->getType();
4180
4181 // __builtin_constant_p always has one operand. The rules which gcc follows
4182 // are not precisely documented, but are as follows:
4183 //
4184 // - If the operand is of integral, floating, complex or enumeration type,
4185 // and can be folded to a known value of that type, it returns 1.
4186 // - If the operand and can be folded to a pointer to the first character
4187 // of a string literal (or such a pointer cast to an integral type), it
4188 // returns 1.
4189 //
4190 // Otherwise, it returns 0.
4191 //
4192 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4193 // its support for this does not currently work.
4194 if (ArgType->isIntegralOrEnumerationType()) {
4195 Expr::EvalResult Result;
4196 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4197 return false;
4198
4199 APValue &V = Result.Val;
4200 if (V.getKind() == APValue::Int)
4201 return true;
4202
4203 return EvaluateBuiltinConstantPForLValue(V);
4204 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4205 return Arg->isEvaluatable(Ctx);
4206 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4207 LValue LV;
4208 Expr::EvalStatus Status;
4209 EvalInfo Info(Ctx, Status);
4210 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4211 : EvaluatePointer(Arg, LV, Info)) &&
4212 !Status.HasSideEffects)
4213 return EvaluateBuiltinConstantPForLValue(LV);
4214 }
4215
4216 // Anything else isn't considered to be sufficiently constant.
4217 return false;
4218}
4219
John McCall42c8f872010-05-10 23:27:23 +00004220/// Retrieves the "underlying object type" of the given expression,
4221/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004222QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4223 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4224 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004225 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004226 } else if (const Expr *E = B.get<const Expr*>()) {
4227 if (isa<CompoundLiteralExpr>(E))
4228 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004229 }
4230
4231 return QualType();
4232}
4233
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004234bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004235 // TODO: Perhaps we should let LLVM lower this?
4236 LValue Base;
4237 if (!EvaluatePointer(E->getArg(0), Base, Info))
4238 return false;
4239
4240 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004241 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004242
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004243 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004244 if (T.isNull() ||
4245 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004246 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004247 T->isVariablyModifiedType() ||
4248 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004249 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004250
4251 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4252 CharUnits Offset = Base.getLValueOffset();
4253
4254 if (!Offset.isNegative() && Offset <= Size)
4255 Size -= Offset;
4256 else
4257 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004258 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004259}
4260
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004261bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004262 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004263 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004264 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004265
4266 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004267 if (TryEvaluateBuiltinObjectSize(E))
4268 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004269
Eric Christopherb2aaf512010-01-19 22:58:35 +00004270 // If evaluating the argument has side-effects we can't determine
4271 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004272 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004273 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004274 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004275 return Success(0, E);
4276 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004277
Richard Smithf48fdb02011-12-09 22:58:01 +00004278 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004279 }
4280
Chris Lattner019f4e82008-10-06 05:28:25 +00004281 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004282 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004283
Richard Smith80d4b552011-12-28 19:48:30 +00004284 case Builtin::BI__builtin_constant_p:
4285 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004286
Chris Lattner21fb98e2009-09-23 06:06:36 +00004287 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004288 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004289 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004290 return Success(Operand, E);
4291 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004292
4293 case Builtin::BI__builtin_expect:
4294 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004295
Douglas Gregor5726d402010-09-10 06:27:15 +00004296 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004297 // A call to strlen is not a constant expression.
4298 if (Info.getLangOpts().CPlusPlus0x)
4299 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_function)
4300 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4301 else
4302 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
4303 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004304 case Builtin::BI__builtin_strlen:
4305 // As an extension, we support strlen() and __builtin_strlen() as constant
4306 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004307 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004308 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4309 // The string literal may have embedded null characters. Find the first
4310 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004311 StringRef Str = S->getString();
4312 StringRef::size_type Pos = Str.find(0);
4313 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004314 Str = Str.substr(0, Pos);
4315
4316 return Success(Str.size(), E);
4317 }
4318
Richard Smithf48fdb02011-12-09 22:58:01 +00004319 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004320
4321 case Builtin::BI__atomic_is_lock_free: {
4322 APSInt SizeVal;
4323 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4324 return false;
4325
4326 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4327 // of two less than the maximum inline atomic width, we know it is
4328 // lock-free. If the size isn't a power of two, or greater than the
4329 // maximum alignment where we promote atomics, we know it is not lock-free
4330 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4331 // the answer can only be determined at runtime; for example, 16-byte
4332 // atomics have lock-free implementations on some, but not all,
4333 // x86-64 processors.
4334
4335 // Check power-of-two.
4336 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4337 if (!Size.isPowerOfTwo())
4338#if 0
4339 // FIXME: Suppress this folding until the ABI for the promotion width
4340 // settles.
4341 return Success(0, E);
4342#else
Richard Smithf48fdb02011-12-09 22:58:01 +00004343 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004344#endif
4345
4346#if 0
4347 // Check against promotion width.
4348 // FIXME: Suppress this folding until the ABI for the promotion width
4349 // settles.
4350 unsigned PromoteWidthBits =
4351 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
4352 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
4353 return Success(0, E);
4354#endif
4355
4356 // Check against inlining width.
4357 unsigned InlineWidthBits =
4358 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4359 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
4360 return Success(1, E);
4361
Richard Smithf48fdb02011-12-09 22:58:01 +00004362 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004363 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004364 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004365}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004366
Richard Smith625b8072011-10-31 01:37:14 +00004367static bool HasSameBase(const LValue &A, const LValue &B) {
4368 if (!A.getLValueBase())
4369 return !B.getLValueBase();
4370 if (!B.getLValueBase())
4371 return false;
4372
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004373 if (A.getLValueBase().getOpaqueValue() !=
4374 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004375 const Decl *ADecl = GetLValueBaseDecl(A);
4376 if (!ADecl)
4377 return false;
4378 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004379 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004380 return false;
4381 }
4382
4383 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith83587db2012-02-15 02:18:13 +00004384 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith625b8072011-10-31 01:37:14 +00004385}
4386
Richard Smith7b48a292012-02-01 05:53:12 +00004387/// Perform the given integer operation, which is known to need at most BitWidth
4388/// bits, and check for overflow in the original type (if that type was not an
4389/// unsigned type).
4390template<typename Operation>
4391static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4392 const APSInt &LHS, const APSInt &RHS,
4393 unsigned BitWidth, Operation Op) {
4394 if (LHS.isUnsigned())
4395 return Op(LHS, RHS);
4396
4397 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4398 APSInt Result = Value.trunc(LHS.getBitWidth());
4399 if (Result.extend(BitWidth) != Value)
4400 HandleOverflow(Info, E, Value, E->getType());
4401 return Result;
4402}
4403
Chris Lattnerb542afe2008-07-11 19:10:17 +00004404bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004405 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004406 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004407
John McCall2de56d12010-08-25 11:45:40 +00004408 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00004409 VisitIgnoredValue(E->getLHS());
4410 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00004411 }
4412
4413 if (E->isLogicalOp()) {
4414 // These need to be handled specially because the operands aren't
Richard Smith74e1ad92012-02-16 02:46:34 +00004415 // necessarily integral nor evaluated.
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004416 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00004417
Richard Smithc49bd112011-10-28 17:51:58 +00004418 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00004419 // We were able to evaluate the LHS, see if we can get away with not
4420 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00004421 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004422 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004423
Richard Smithc49bd112011-10-28 17:51:58 +00004424 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00004425 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004426 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004427 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00004428 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004429 }
4430 } else {
Richard Smith74e1ad92012-02-16 02:46:34 +00004431 // Since we weren't able to evaluate the left hand side, it
4432 // must have had side effects.
4433 Info.EvalStatus.HasSideEffects = true;
4434
4435 // Suppress diagnostics from this arm.
4436 SpeculativeEvaluationRAII Speculative(Info);
Richard Smithc49bd112011-10-28 17:51:58 +00004437 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004438 // We can't evaluate the LHS; however, sometimes the result
4439 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smith74e1ad92012-02-16 02:46:34 +00004440 if (rhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar131eb432009-02-19 09:06:44 +00004441 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004442 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00004443 }
Eli Friedmana6afa762008-11-13 06:09:17 +00004444
Eli Friedmana6afa762008-11-13 06:09:17 +00004445 return false;
4446 }
4447
Anders Carlsson286f85e2008-11-16 07:17:21 +00004448 QualType LHSTy = E->getLHS()->getType();
4449 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004450
4451 if (LHSTy->isAnyComplexType()) {
4452 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004453 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004454
Richard Smith745f5142012-01-27 01:14:48 +00004455 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4456 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004457 return false;
4458
Richard Smith745f5142012-01-27 01:14:48 +00004459 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004460 return false;
4461
4462 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004463 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004464 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004465 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004466 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4467
John McCall2de56d12010-08-25 11:45:40 +00004468 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004469 return Success((CR_r == APFloat::cmpEqual &&
4470 CR_i == APFloat::cmpEqual), E);
4471 else {
John McCall2de56d12010-08-25 11:45:40 +00004472 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004473 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004474 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004475 CR_r == APFloat::cmpLessThan ||
4476 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004477 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004478 CR_i == APFloat::cmpLessThan ||
4479 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004480 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004481 } else {
John McCall2de56d12010-08-25 11:45:40 +00004482 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004483 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4484 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4485 else {
John McCall2de56d12010-08-25 11:45:40 +00004486 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004487 "Invalid compex comparison.");
4488 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4489 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4490 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004491 }
4492 }
Mike Stump1eb44332009-09-09 15:08:12 +00004493
Anders Carlsson286f85e2008-11-16 07:17:21 +00004494 if (LHSTy->isRealFloatingType() &&
4495 RHSTy->isRealFloatingType()) {
4496 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004497
Richard Smith745f5142012-01-27 01:14:48 +00004498 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4499 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004500 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004501
Richard Smith745f5142012-01-27 01:14:48 +00004502 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004503 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004504
Anders Carlsson286f85e2008-11-16 07:17:21 +00004505 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004506
Anders Carlsson286f85e2008-11-16 07:17:21 +00004507 switch (E->getOpcode()) {
4508 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004509 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004510 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004511 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004512 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004513 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004514 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004515 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004516 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004517 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004518 E);
John McCall2de56d12010-08-25 11:45:40 +00004519 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004520 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004521 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004522 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004523 || CR == APFloat::cmpLessThan
4524 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004525 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004526 }
Mike Stump1eb44332009-09-09 15:08:12 +00004527
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004528 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004529 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004530 LValue LHSValue, RHSValue;
4531
4532 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4533 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004534 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004535
Richard Smith745f5142012-01-27 01:14:48 +00004536 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004537 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004538
Richard Smith625b8072011-10-31 01:37:14 +00004539 // Reject differing bases from the normal codepath; we special-case
4540 // comparisons to null.
4541 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004542 if (E->getOpcode() == BO_Sub) {
4543 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004544 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4545 return false;
4546 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4547 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4548 if (!LHSExpr || !RHSExpr)
4549 return false;
4550 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4551 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4552 if (!LHSAddrExpr || !RHSAddrExpr)
4553 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004554 // Make sure both labels come from the same function.
4555 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4556 RHSAddrExpr->getLabel()->getDeclContext())
4557 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004558 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4559 return true;
4560 }
Richard Smith9e36b532011-10-31 05:11:32 +00004561 // Inequalities and subtractions between unrelated pointers have
4562 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004563 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004564 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004565 // A constant address may compare equal to the address of a symbol.
4566 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004567 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004568 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4569 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004570 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004571 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004572 // distinct addresses. In clang, the result of such a comparison is
4573 // unspecified, so it is not a constant expression. However, we do know
4574 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004575 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4576 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004577 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004578 // We can't tell whether weak symbols will end up pointing to the same
4579 // object.
4580 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004581 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004582 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004583 // (Note that clang defaults to -fmerge-all-constants, which can
4584 // lead to inconsistent results for comparisons involving the address
4585 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004586 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004587 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004588
Richard Smith15efc4d2012-02-01 08:10:20 +00004589 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4590 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4591
Richard Smithf15fda02012-02-02 01:16:57 +00004592 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4593 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4594
John McCall2de56d12010-08-25 11:45:40 +00004595 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00004596 // C++11 [expr.add]p6:
4597 // Unless both pointers point to elements of the same array object, or
4598 // one past the last element of the array object, the behavior is
4599 // undefined.
4600 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4601 !AreElementsOfSameArray(getType(LHSValue.Base),
4602 LHSDesignator, RHSDesignator))
4603 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4604
Chris Lattner4992bdd2010-04-20 17:13:14 +00004605 QualType Type = E->getLHS()->getType();
4606 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004607
Richard Smith180f4792011-11-10 06:34:14 +00004608 CharUnits ElementSize;
Richard Smith74e1ad92012-02-16 02:46:34 +00004609 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smith180f4792011-11-10 06:34:14 +00004610 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004611
Richard Smith15efc4d2012-02-01 08:10:20 +00004612 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
4613 // and produce incorrect results when it overflows. Such behavior
4614 // appears to be non-conforming, but is common, so perhaps we should
4615 // assume the standard intended for such cases to be undefined behavior
4616 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00004617
Richard Smith15efc4d2012-02-01 08:10:20 +00004618 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
4619 // overflow in the final conversion to ptrdiff_t.
4620 APSInt LHS(
4621 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
4622 APSInt RHS(
4623 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
4624 APSInt ElemSize(
4625 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
4626 APSInt TrueResult = (LHS - RHS) / ElemSize;
4627 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
4628
4629 if (Result.extend(65) != TrueResult)
4630 HandleOverflow(Info, E, TrueResult, E->getType());
4631 return Success(Result, E);
4632 }
Richard Smith82f28582012-01-31 06:41:30 +00004633
4634 // C++11 [expr.rel]p3:
4635 // Pointers to void (after pointer conversions) can be compared, with a
4636 // result defined as follows: If both pointers represent the same
4637 // address or are both the null pointer value, the result is true if the
4638 // operator is <= or >= and false otherwise; otherwise the result is
4639 // unspecified.
4640 // We interpret this as applying to pointers to *cv* void.
4641 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00004642 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00004643 CCEDiag(E, diag::note_constexpr_void_comparison);
4644
Richard Smithf15fda02012-02-02 01:16:57 +00004645 // C++11 [expr.rel]p2:
4646 // - If two pointers point to non-static data members of the same object,
4647 // or to subobjects or array elements fo such members, recursively, the
4648 // pointer to the later declared member compares greater provided the
4649 // two members have the same access control and provided their class is
4650 // not a union.
4651 // [...]
4652 // - Otherwise pointer comparisons are unspecified.
4653 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4654 E->isRelationalOp()) {
4655 bool WasArrayIndex;
4656 unsigned Mismatch =
4657 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
4658 RHSDesignator, WasArrayIndex);
4659 // At the point where the designators diverge, the comparison has a
4660 // specified value if:
4661 // - we are comparing array indices
4662 // - we are comparing fields of a union, or fields with the same access
4663 // Otherwise, the result is unspecified and thus the comparison is not a
4664 // constant expression.
4665 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
4666 Mismatch < RHSDesignator.Entries.size()) {
4667 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
4668 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
4669 if (!LF && !RF)
4670 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
4671 else if (!LF)
4672 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4673 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
4674 << RF->getParent() << RF;
4675 else if (!RF)
4676 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4677 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
4678 << LF->getParent() << LF;
4679 else if (!LF->getParent()->isUnion() &&
4680 LF->getAccess() != RF->getAccess())
4681 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
4682 << LF << LF->getAccess() << RF << RF->getAccess()
4683 << LF->getParent();
4684 }
4685 }
4686
Richard Smith625b8072011-10-31 01:37:14 +00004687 switch (E->getOpcode()) {
4688 default: llvm_unreachable("missing comparison operator");
4689 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4690 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4691 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4692 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4693 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4694 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004695 }
Anders Carlsson3068d112008-11-16 19:01:22 +00004696 }
4697 }
Richard Smithb02e4622012-02-01 01:42:44 +00004698
4699 if (LHSTy->isMemberPointerType()) {
4700 assert(E->isEqualityOp() && "unexpected member pointer operation");
4701 assert(RHSTy->isMemberPointerType() && "invalid comparison");
4702
4703 MemberPtr LHSValue, RHSValue;
4704
4705 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
4706 if (!LHSOK && Info.keepEvaluatingAfterFailure())
4707 return false;
4708
4709 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
4710 return false;
4711
4712 // C++11 [expr.eq]p2:
4713 // If both operands are null, they compare equal. Otherwise if only one is
4714 // null, they compare unequal.
4715 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
4716 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
4717 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4718 }
4719
4720 // Otherwise if either is a pointer to a virtual member function, the
4721 // result is unspecified.
4722 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
4723 if (MD->isVirtual())
4724 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4725 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
4726 if (MD->isVirtual())
4727 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4728
4729 // Otherwise they compare equal if and only if they would refer to the
4730 // same member of the same most derived object or the same subobject if
4731 // they were dereferenced with a hypothetical object of the associated
4732 // class type.
4733 bool Equal = LHSValue == RHSValue;
4734 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4735 }
4736
Richard Smith26f2cac2012-02-14 22:35:28 +00004737 if (LHSTy->isNullPtrType()) {
4738 assert(E->isComparisonOp() && "unexpected nullptr operation");
4739 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
4740 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
4741 // are compared, the result is true of the operator is <=, >= or ==, and
4742 // false otherwise.
4743 BinaryOperator::Opcode Opcode = E->getOpcode();
4744 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
4745 }
4746
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004747 if (!LHSTy->isIntegralOrEnumerationType() ||
4748 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004749 // We can't continue from here for non-integral types.
4750 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004751 }
4752
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004753 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00004754 CCValue LHSVal;
Richard Smith745f5142012-01-27 01:14:48 +00004755
4756 bool LHSOK = EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info);
4757 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Richard Smithf48fdb02011-12-09 22:58:01 +00004758 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00004759
Richard Smith745f5142012-01-27 01:14:48 +00004760 if (!Visit(E->getRHS()) || !LHSOK)
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004761 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004762
Richard Smith47a1eed2011-10-29 20:57:55 +00004763 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004764
4765 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00004766 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00004767 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4768 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00004769 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00004770 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004771 else
Richard Smith47a1eed2011-10-29 20:57:55 +00004772 LHSVal.getLValueOffset() -= AdditionalOffset;
4773 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004774 return true;
4775 }
4776
4777 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00004778 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00004779 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004780 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4781 LHSVal.getInt().getZExtValue());
4782 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00004783 return true;
4784 }
4785
Eli Friedman65639282012-01-04 23:13:47 +00004786 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4787 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedman65639282012-01-04 23:13:47 +00004788 if (!LHSVal.getLValueOffset().isZero() ||
4789 !RHSVal.getLValueOffset().isZero())
4790 return false;
4791 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4792 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4793 if (!LHSExpr || !RHSExpr)
4794 return false;
4795 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4796 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4797 if (!LHSAddrExpr || !RHSAddrExpr)
4798 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004799 // Make sure both labels come from the same function.
4800 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4801 RHSAddrExpr->getLabel()->getDeclContext())
4802 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004803 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4804 return true;
4805 }
4806
Eli Friedman42edd0d2009-03-24 01:14:50 +00004807 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00004808 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00004809 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004810
Richard Smithc49bd112011-10-28 17:51:58 +00004811 APSInt &LHS = LHSVal.getInt();
4812 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00004813
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004814 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00004815 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004816 return Error(E);
Richard Smith7b48a292012-02-01 05:53:12 +00004817 case BO_Mul:
4818 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4819 LHS.getBitWidth() * 2,
4820 std::multiplies<APSInt>()), E);
4821 case BO_Add:
4822 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4823 LHS.getBitWidth() + 1,
4824 std::plus<APSInt>()), E);
4825 case BO_Sub:
4826 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4827 LHS.getBitWidth() + 1,
4828 std::minus<APSInt>()), E);
Richard Smithc49bd112011-10-28 17:51:58 +00004829 case BO_And: return Success(LHS & RHS, E);
4830 case BO_Xor: return Success(LHS ^ RHS, E);
4831 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004832 case BO_Div:
John McCall2de56d12010-08-25 11:45:40 +00004833 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00004834 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004835 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith3df61302012-01-31 23:24:19 +00004836 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is not
4837 // actually undefined behavior in C++11 due to a language defect.
4838 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4839 LHS.isSigned() && LHS.isMinSignedValue())
4840 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4841 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004842 case BO_Shl: {
Richard Smith789f9b62012-01-31 04:08:20 +00004843 // During constant-folding, a negative shift is an opposite shift. Such a
4844 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004845 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004846 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004847 RHS = -RHS;
4848 goto shift_right;
4849 }
4850
4851 shift_left:
Richard Smith789f9b62012-01-31 04:08:20 +00004852 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4853 // shifted type.
4854 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4855 if (SA != RHS) {
4856 CCEDiag(E, diag::note_constexpr_large_shift)
4857 << RHS << E->getType() << LHS.getBitWidth();
4858 } else if (LHS.isSigned()) {
4859 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
Richard Smith925d8e72012-02-08 06:14:53 +00004860 // operand, and must not overflow the corresponding unsigned type.
Richard Smith789f9b62012-01-31 04:08:20 +00004861 if (LHS.isNegative())
4862 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
Richard Smith925d8e72012-02-08 06:14:53 +00004863 else if (LHS.countLeadingZeros() < SA)
4864 CCEDiag(E, diag::note_constexpr_lshift_discards);
Richard Smith789f9b62012-01-31 04:08:20 +00004865 }
4866
Richard Smithc49bd112011-10-28 17:51:58 +00004867 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004868 }
John McCall2de56d12010-08-25 11:45:40 +00004869 case BO_Shr: {
Richard Smith789f9b62012-01-31 04:08:20 +00004870 // During constant-folding, a negative shift is an opposite shift. Such a
4871 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004872 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004873 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004874 RHS = -RHS;
4875 goto shift_left;
4876 }
4877
4878 shift_right:
Richard Smith789f9b62012-01-31 04:08:20 +00004879 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4880 // shifted type.
4881 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4882 if (SA != RHS)
4883 CCEDiag(E, diag::note_constexpr_large_shift)
4884 << RHS << E->getType() << LHS.getBitWidth();
4885
Richard Smithc49bd112011-10-28 17:51:58 +00004886 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004887 }
Mike Stump1eb44332009-09-09 15:08:12 +00004888
Richard Smithc49bd112011-10-28 17:51:58 +00004889 case BO_LT: return Success(LHS < RHS, E);
4890 case BO_GT: return Success(LHS > RHS, E);
4891 case BO_LE: return Success(LHS <= RHS, E);
4892 case BO_GE: return Success(LHS >= RHS, E);
4893 case BO_EQ: return Success(LHS == RHS, E);
4894 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00004895 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004896}
4897
Ken Dyck8b752f12010-01-27 17:10:57 +00004898CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00004899 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4900 // result shall be the alignment of the referenced type."
4901 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4902 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00004903
4904 // __alignof is defined to return the preferred alignment.
4905 return Info.Ctx.toCharUnitsFromBits(
4906 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00004907}
4908
Ken Dyck8b752f12010-01-27 17:10:57 +00004909CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00004910 E = E->IgnoreParens();
4911
4912 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00004913 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00004914 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004915 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4916 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00004917
Chris Lattneraf707ab2009-01-24 21:53:27 +00004918 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004919 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4920 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00004921
Chris Lattnere9feb472009-01-24 21:09:06 +00004922 return GetAlignOfType(E->getType());
4923}
4924
4925
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004926/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4927/// a result as the expression's type.
4928bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4929 const UnaryExprOrTypeTraitExpr *E) {
4930 switch(E->getKind()) {
4931 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00004932 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004933 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004934 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004935 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004936 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004937
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004938 case UETT_VecStep: {
4939 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00004940
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004941 if (Ty->isVectorType()) {
4942 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00004943
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004944 // The vec_step built-in functions that take a 3-component
4945 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4946 if (n == 3)
4947 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00004948
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004949 return Success(n, E);
4950 } else
4951 return Success(1, E);
4952 }
4953
4954 case UETT_SizeOf: {
4955 QualType SrcTy = E->getTypeOfArgument();
4956 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4957 // the result is the size of the referenced type."
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004958 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4959 SrcTy = Ref->getPointeeType();
4960
Richard Smith180f4792011-11-10 06:34:14 +00004961 CharUnits Sizeof;
Richard Smith74e1ad92012-02-16 02:46:34 +00004962 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004963 return false;
Richard Smith180f4792011-11-10 06:34:14 +00004964 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004965 }
4966 }
4967
4968 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00004969}
4970
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004971bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004972 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004973 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004974 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004975 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004976 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004977 for (unsigned i = 0; i != n; ++i) {
4978 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4979 switch (ON.getKind()) {
4980 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004981 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004982 APSInt IdxResult;
4983 if (!EvaluateInteger(Idx, IdxResult, Info))
4984 return false;
4985 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4986 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004987 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004988 CurrentType = AT->getElementType();
4989 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4990 Result += IdxResult.getSExtValue() * ElementSize;
4991 break;
4992 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004993
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004994 case OffsetOfExpr::OffsetOfNode::Field: {
4995 FieldDecl *MemberDecl = ON.getField();
4996 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004997 if (!RT)
4998 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004999 RecordDecl *RD = RT->getDecl();
5000 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00005001 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005002 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00005003 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005004 CurrentType = MemberDecl->getType().getNonReferenceType();
5005 break;
5006 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005007
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005008 case OffsetOfExpr::OffsetOfNode::Identifier:
5009 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00005010
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005011 case OffsetOfExpr::OffsetOfNode::Base: {
5012 CXXBaseSpecifier *BaseSpec = ON.getBase();
5013 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00005014 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005015
5016 // Find the layout of the class whose base we are looking into.
5017 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005018 if (!RT)
5019 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005020 RecordDecl *RD = RT->getDecl();
5021 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5022
5023 // Find the base class itself.
5024 CurrentType = BaseSpec->getType();
5025 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5026 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005027 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005028
5029 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00005030 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005031 break;
5032 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005033 }
5034 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005035 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005036}
5037
Chris Lattnerb542afe2008-07-11 19:10:17 +00005038bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005039 switch (E->getOpcode()) {
5040 default:
5041 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5042 // See C99 6.6p3.
5043 return Error(E);
5044 case UO_Extension:
5045 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5046 // If so, we could clear the diagnostic ID.
5047 return Visit(E->getSubExpr());
5048 case UO_Plus:
5049 // The result is just the value.
5050 return Visit(E->getSubExpr());
5051 case UO_Minus: {
5052 if (!Visit(E->getSubExpr()))
5053 return false;
5054 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00005055 const APSInt &Value = Result.getInt();
5056 if (Value.isSigned() && Value.isMinSignedValue())
5057 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5058 E->getType());
5059 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00005060 }
5061 case UO_Not: {
5062 if (!Visit(E->getSubExpr()))
5063 return false;
5064 if (!Result.isInt()) return Error(E);
5065 return Success(~Result.getInt(), E);
5066 }
5067 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00005068 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00005069 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00005070 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005071 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00005072 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005073 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005074}
Mike Stump1eb44332009-09-09 15:08:12 +00005075
Chris Lattner732b2232008-07-12 01:15:53 +00005076/// HandleCast - This is used to evaluate implicit or explicit casts where the
5077/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005078bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5079 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00005080 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00005081 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00005082
Eli Friedman46a52322011-03-25 00:43:55 +00005083 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00005084 case CK_BaseToDerived:
5085 case CK_DerivedToBase:
5086 case CK_UncheckedDerivedToBase:
5087 case CK_Dynamic:
5088 case CK_ToUnion:
5089 case CK_ArrayToPointerDecay:
5090 case CK_FunctionToPointerDecay:
5091 case CK_NullToPointer:
5092 case CK_NullToMemberPointer:
5093 case CK_BaseToDerivedMemberPointer:
5094 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00005095 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00005096 case CK_ConstructorConversion:
5097 case CK_IntegralToPointer:
5098 case CK_ToVoid:
5099 case CK_VectorSplat:
5100 case CK_IntegralToFloating:
5101 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005102 case CK_CPointerToObjCPointerCast:
5103 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005104 case CK_AnyPointerToBlockPointerCast:
5105 case CK_ObjCObjectLValueCast:
5106 case CK_FloatingRealToComplex:
5107 case CK_FloatingComplexToReal:
5108 case CK_FloatingComplexCast:
5109 case CK_FloatingComplexToIntegralComplex:
5110 case CK_IntegralRealToComplex:
5111 case CK_IntegralComplexCast:
5112 case CK_IntegralComplexToFloatingComplex:
5113 llvm_unreachable("invalid cast kind for integral value");
5114
Eli Friedmane50c2972011-03-25 19:07:11 +00005115 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005116 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005117 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00005118 case CK_ARCProduceObject:
5119 case CK_ARCConsumeObject:
5120 case CK_ARCReclaimReturnedObject:
5121 case CK_ARCExtendBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00005122 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005123
Richard Smith7d580a42012-01-17 21:17:26 +00005124 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00005125 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005126 case CK_AtomicToNonAtomic:
5127 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00005128 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005129 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005130
5131 case CK_MemberPointerToBoolean:
5132 case CK_PointerToBoolean:
5133 case CK_IntegralToBoolean:
5134 case CK_FloatingToBoolean:
5135 case CK_FloatingComplexToBoolean:
5136 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005137 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00005138 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00005139 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005140 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005141 }
5142
Eli Friedman46a52322011-03-25 00:43:55 +00005143 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00005144 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005145 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00005146
Eli Friedmanbe265702009-02-20 01:15:07 +00005147 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00005148 // Allow casts of address-of-label differences if they are no-ops
5149 // or narrowing. (The narrowing case isn't actually guaranteed to
5150 // be constant-evaluatable except in some narrow cases which are hard
5151 // to detect here. We let it through on the assumption the user knows
5152 // what they are doing.)
5153 if (Result.isAddrLabelDiff())
5154 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005155 // Only allow casts of lvalues if they are lossless.
5156 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5157 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005158
Richard Smithf72fccf2012-01-30 22:27:01 +00005159 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5160 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005161 }
Mike Stump1eb44332009-09-09 15:08:12 +00005162
Eli Friedman46a52322011-03-25 00:43:55 +00005163 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005164 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5165
John McCallefdb83e2010-05-07 21:00:08 +00005166 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005167 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005168 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005169
Daniel Dunbardd211642009-02-19 22:24:01 +00005170 if (LV.getLValueBase()) {
5171 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005172 // FIXME: Allow a larger integer size than the pointer size, and allow
5173 // narrowing back down to pointer width in subsequent integral casts.
5174 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005175 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005176 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005177
Richard Smithb755a9d2011-11-16 07:18:12 +00005178 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005179 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005180 return true;
5181 }
5182
Ken Dycka7305832010-01-15 12:37:54 +00005183 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5184 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005185 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005186 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005187
Eli Friedman46a52322011-03-25 00:43:55 +00005188 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005189 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005190 if (!EvaluateComplex(SubExpr, C, Info))
5191 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005192 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005193 }
Eli Friedman2217c872009-02-22 11:46:18 +00005194
Eli Friedman46a52322011-03-25 00:43:55 +00005195 case CK_FloatingToIntegral: {
5196 APFloat F(0.0);
5197 if (!EvaluateFloat(SubExpr, F, Info))
5198 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005199
Richard Smithc1c5f272011-12-13 06:39:58 +00005200 APSInt Value;
5201 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5202 return false;
5203 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005204 }
5205 }
Mike Stump1eb44332009-09-09 15:08:12 +00005206
Eli Friedman46a52322011-03-25 00:43:55 +00005207 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005208}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005209
Eli Friedman722c7172009-02-28 03:59:05 +00005210bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5211 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005212 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005213 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5214 return false;
5215 if (!LV.isComplexInt())
5216 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005217 return Success(LV.getComplexIntReal(), E);
5218 }
5219
5220 return Visit(E->getSubExpr());
5221}
5222
Eli Friedman664a1042009-02-27 04:45:43 +00005223bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005224 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005225 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005226 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5227 return false;
5228 if (!LV.isComplexInt())
5229 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005230 return Success(LV.getComplexIntImag(), E);
5231 }
5232
Richard Smith8327fad2011-10-24 18:44:57 +00005233 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005234 return Success(0, E);
5235}
5236
Douglas Gregoree8aff02011-01-04 17:33:58 +00005237bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5238 return Success(E->getPackLength(), E);
5239}
5240
Sebastian Redl295995c2010-09-10 20:55:47 +00005241bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5242 return Success(E->getValue(), E);
5243}
5244
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005245//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005246// Float Evaluation
5247//===----------------------------------------------------------------------===//
5248
5249namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005250class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005251 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005252 APFloat &Result;
5253public:
5254 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005255 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005256
Richard Smith47a1eed2011-10-29 20:57:55 +00005257 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005258 Result = V.getFloat();
5259 return true;
5260 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005261
Richard Smith51201882011-12-30 21:15:51 +00005262 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005263 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5264 return true;
5265 }
5266
Chris Lattner019f4e82008-10-06 05:28:25 +00005267 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005268
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005269 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005270 bool VisitBinaryOperator(const BinaryOperator *E);
5271 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005272 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005273
John McCallabd3a852010-05-07 22:08:54 +00005274 bool VisitUnaryReal(const UnaryOperator *E);
5275 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005276
Richard Smith51201882011-12-30 21:15:51 +00005277 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005278};
5279} // end anonymous namespace
5280
5281static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005282 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005283 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005284}
5285
Jay Foad4ba2a172011-01-12 09:06:06 +00005286static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005287 QualType ResultTy,
5288 const Expr *Arg,
5289 bool SNaN,
5290 llvm::APFloat &Result) {
5291 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5292 if (!S) return false;
5293
5294 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5295
5296 llvm::APInt fill;
5297
5298 // Treat empty strings as if they were zero.
5299 if (S->getString().empty())
5300 fill = llvm::APInt(32, 0);
5301 else if (S->getString().getAsInteger(0, fill))
5302 return false;
5303
5304 if (SNaN)
5305 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5306 else
5307 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5308 return true;
5309}
5310
Chris Lattner019f4e82008-10-06 05:28:25 +00005311bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005312 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005313 default:
5314 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5315
Chris Lattner019f4e82008-10-06 05:28:25 +00005316 case Builtin::BI__builtin_huge_val:
5317 case Builtin::BI__builtin_huge_valf:
5318 case Builtin::BI__builtin_huge_vall:
5319 case Builtin::BI__builtin_inf:
5320 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005321 case Builtin::BI__builtin_infl: {
5322 const llvm::fltSemantics &Sem =
5323 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005324 Result = llvm::APFloat::getInf(Sem);
5325 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005326 }
Mike Stump1eb44332009-09-09 15:08:12 +00005327
John McCalldb7b72a2010-02-28 13:00:19 +00005328 case Builtin::BI__builtin_nans:
5329 case Builtin::BI__builtin_nansf:
5330 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005331 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5332 true, Result))
5333 return Error(E);
5334 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005335
Chris Lattner9e621712008-10-06 06:31:58 +00005336 case Builtin::BI__builtin_nan:
5337 case Builtin::BI__builtin_nanf:
5338 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005339 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005340 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005341 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5342 false, Result))
5343 return Error(E);
5344 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005345
5346 case Builtin::BI__builtin_fabs:
5347 case Builtin::BI__builtin_fabsf:
5348 case Builtin::BI__builtin_fabsl:
5349 if (!EvaluateFloat(E->getArg(0), Result, Info))
5350 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005351
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005352 if (Result.isNegative())
5353 Result.changeSign();
5354 return true;
5355
Mike Stump1eb44332009-09-09 15:08:12 +00005356 case Builtin::BI__builtin_copysign:
5357 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005358 case Builtin::BI__builtin_copysignl: {
5359 APFloat RHS(0.);
5360 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5361 !EvaluateFloat(E->getArg(1), RHS, Info))
5362 return false;
5363 Result.copySign(RHS);
5364 return true;
5365 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005366 }
5367}
5368
John McCallabd3a852010-05-07 22:08:54 +00005369bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005370 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5371 ComplexValue CV;
5372 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5373 return false;
5374 Result = CV.FloatReal;
5375 return true;
5376 }
5377
5378 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005379}
5380
5381bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005382 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5383 ComplexValue CV;
5384 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5385 return false;
5386 Result = CV.FloatImag;
5387 return true;
5388 }
5389
Richard Smith8327fad2011-10-24 18:44:57 +00005390 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005391 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5392 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005393 return true;
5394}
5395
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005396bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005397 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005398 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005399 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005400 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005401 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005402 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5403 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005404 Result.changeSign();
5405 return true;
5406 }
5407}
Chris Lattner019f4e82008-10-06 05:28:25 +00005408
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005409bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005410 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5411 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005412
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005413 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005414 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5415 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005416 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005417 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005418 return false;
5419
5420 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005421 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005422 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005423 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005424 break;
John McCall2de56d12010-08-25 11:45:40 +00005425 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005426 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005427 break;
John McCall2de56d12010-08-25 11:45:40 +00005428 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005429 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005430 break;
John McCall2de56d12010-08-25 11:45:40 +00005431 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005432 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005433 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005434 }
Richard Smith7b48a292012-02-01 05:53:12 +00005435
5436 if (Result.isInfinity() || Result.isNaN())
5437 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5438 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005439}
5440
5441bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5442 Result = E->getValue();
5443 return true;
5444}
5445
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005446bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5447 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005448
Eli Friedman2a523ee2011-03-25 00:54:52 +00005449 switch (E->getCastKind()) {
5450 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005451 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005452
5453 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005454 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005455 return EvaluateInteger(SubExpr, IntResult, Info) &&
5456 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5457 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005458 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005459
5460 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005461 if (!Visit(SubExpr))
5462 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005463 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5464 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005465 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005466
Eli Friedman2a523ee2011-03-25 00:54:52 +00005467 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005468 ComplexValue V;
5469 if (!EvaluateComplex(SubExpr, V, Info))
5470 return false;
5471 Result = V.getComplexFloatReal();
5472 return true;
5473 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005474 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005475}
5476
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005477//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005478// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005479//===----------------------------------------------------------------------===//
5480
5481namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005482class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005483 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005484 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005485
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005486public:
John McCallf4cf1a12010-05-07 17:22:02 +00005487 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005488 : ExprEvaluatorBaseTy(info), Result(Result) {}
5489
Richard Smith47a1eed2011-10-29 20:57:55 +00005490 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005491 Result.setFrom(V);
5492 return true;
5493 }
Mike Stump1eb44332009-09-09 15:08:12 +00005494
Eli Friedman7ead5c72012-01-10 04:58:17 +00005495 bool ZeroInitialization(const Expr *E);
5496
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005497 //===--------------------------------------------------------------------===//
5498 // Visitor Methods
5499 //===--------------------------------------------------------------------===//
5500
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005501 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005502 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005503 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005504 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005505 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005506};
5507} // end anonymous namespace
5508
John McCallf4cf1a12010-05-07 17:22:02 +00005509static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5510 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005511 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005512 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005513}
5514
Eli Friedman7ead5c72012-01-10 04:58:17 +00005515bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005516 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005517 if (ElemTy->isRealFloatingType()) {
5518 Result.makeComplexFloat();
5519 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5520 Result.FloatReal = Zero;
5521 Result.FloatImag = Zero;
5522 } else {
5523 Result.makeComplexInt();
5524 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5525 Result.IntReal = Zero;
5526 Result.IntImag = Zero;
5527 }
5528 return true;
5529}
5530
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005531bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5532 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005533
5534 if (SubExpr->getType()->isRealFloatingType()) {
5535 Result.makeComplexFloat();
5536 APFloat &Imag = Result.FloatImag;
5537 if (!EvaluateFloat(SubExpr, Imag, Info))
5538 return false;
5539
5540 Result.FloatReal = APFloat(Imag.getSemantics());
5541 return true;
5542 } else {
5543 assert(SubExpr->getType()->isIntegerType() &&
5544 "Unexpected imaginary literal.");
5545
5546 Result.makeComplexInt();
5547 APSInt &Imag = Result.IntImag;
5548 if (!EvaluateInteger(SubExpr, Imag, Info))
5549 return false;
5550
5551 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5552 return true;
5553 }
5554}
5555
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005556bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005557
John McCall8786da72010-12-14 17:51:41 +00005558 switch (E->getCastKind()) {
5559 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005560 case CK_BaseToDerived:
5561 case CK_DerivedToBase:
5562 case CK_UncheckedDerivedToBase:
5563 case CK_Dynamic:
5564 case CK_ToUnion:
5565 case CK_ArrayToPointerDecay:
5566 case CK_FunctionToPointerDecay:
5567 case CK_NullToPointer:
5568 case CK_NullToMemberPointer:
5569 case CK_BaseToDerivedMemberPointer:
5570 case CK_DerivedToBaseMemberPointer:
5571 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00005572 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00005573 case CK_ConstructorConversion:
5574 case CK_IntegralToPointer:
5575 case CK_PointerToIntegral:
5576 case CK_PointerToBoolean:
5577 case CK_ToVoid:
5578 case CK_VectorSplat:
5579 case CK_IntegralCast:
5580 case CK_IntegralToBoolean:
5581 case CK_IntegralToFloating:
5582 case CK_FloatingToIntegral:
5583 case CK_FloatingToBoolean:
5584 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005585 case CK_CPointerToObjCPointerCast:
5586 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005587 case CK_AnyPointerToBlockPointerCast:
5588 case CK_ObjCObjectLValueCast:
5589 case CK_FloatingComplexToReal:
5590 case CK_FloatingComplexToBoolean:
5591 case CK_IntegralComplexToReal:
5592 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005593 case CK_ARCProduceObject:
5594 case CK_ARCConsumeObject:
5595 case CK_ARCReclaimReturnedObject:
5596 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005597 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005598
John McCall8786da72010-12-14 17:51:41 +00005599 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005600 case CK_AtomicToNonAtomic:
5601 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005602 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005603 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005604
5605 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005606 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005607 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005608 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005609
5610 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005611 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005612 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005613 return false;
5614
John McCall8786da72010-12-14 17:51:41 +00005615 Result.makeComplexFloat();
5616 Result.FloatImag = APFloat(Real.getSemantics());
5617 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005618 }
5619
John McCall8786da72010-12-14 17:51:41 +00005620 case CK_FloatingComplexCast: {
5621 if (!Visit(E->getSubExpr()))
5622 return false;
5623
5624 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5625 QualType From
5626 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5627
Richard Smithc1c5f272011-12-13 06:39:58 +00005628 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5629 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005630 }
5631
5632 case CK_FloatingComplexToIntegralComplex: {
5633 if (!Visit(E->getSubExpr()))
5634 return false;
5635
5636 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5637 QualType From
5638 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5639 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005640 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5641 To, Result.IntReal) &&
5642 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5643 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005644 }
5645
5646 case CK_IntegralRealToComplex: {
5647 APSInt &Real = Result.IntReal;
5648 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5649 return false;
5650
5651 Result.makeComplexInt();
5652 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5653 return true;
5654 }
5655
5656 case CK_IntegralComplexCast: {
5657 if (!Visit(E->getSubExpr()))
5658 return false;
5659
5660 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5661 QualType From
5662 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5663
Richard Smithf72fccf2012-01-30 22:27:01 +00005664 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5665 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005666 return true;
5667 }
5668
5669 case CK_IntegralComplexToFloatingComplex: {
5670 if (!Visit(E->getSubExpr()))
5671 return false;
5672
5673 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5674 QualType From
5675 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5676 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005677 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5678 To, Result.FloatReal) &&
5679 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5680 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005681 }
5682 }
5683
5684 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005685}
5686
John McCallf4cf1a12010-05-07 17:22:02 +00005687bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005688 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005689 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5690
Richard Smith745f5142012-01-27 01:14:48 +00005691 bool LHSOK = Visit(E->getLHS());
5692 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005693 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005694
John McCallf4cf1a12010-05-07 17:22:02 +00005695 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005696 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005697 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005698
Daniel Dunbar3f279872009-01-29 01:32:56 +00005699 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5700 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005701 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005702 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005703 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005704 if (Result.isComplexFloat()) {
5705 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5706 APFloat::rmNearestTiesToEven);
5707 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5708 APFloat::rmNearestTiesToEven);
5709 } else {
5710 Result.getComplexIntReal() += RHS.getComplexIntReal();
5711 Result.getComplexIntImag() += RHS.getComplexIntImag();
5712 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005713 break;
John McCall2de56d12010-08-25 11:45:40 +00005714 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005715 if (Result.isComplexFloat()) {
5716 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5717 APFloat::rmNearestTiesToEven);
5718 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5719 APFloat::rmNearestTiesToEven);
5720 } else {
5721 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5722 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5723 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005724 break;
John McCall2de56d12010-08-25 11:45:40 +00005725 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005726 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005727 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005728 APFloat &LHS_r = LHS.getComplexFloatReal();
5729 APFloat &LHS_i = LHS.getComplexFloatImag();
5730 APFloat &RHS_r = RHS.getComplexFloatReal();
5731 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005732
Daniel Dunbar3f279872009-01-29 01:32:56 +00005733 APFloat Tmp = LHS_r;
5734 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5735 Result.getComplexFloatReal() = Tmp;
5736 Tmp = LHS_i;
5737 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5738 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5739
5740 Tmp = LHS_r;
5741 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5742 Result.getComplexFloatImag() = Tmp;
5743 Tmp = LHS_i;
5744 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5745 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5746 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005747 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005748 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005749 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5750 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00005751 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005752 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5753 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5754 }
5755 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005756 case BO_Div:
5757 if (Result.isComplexFloat()) {
5758 ComplexValue LHS = Result;
5759 APFloat &LHS_r = LHS.getComplexFloatReal();
5760 APFloat &LHS_i = LHS.getComplexFloatImag();
5761 APFloat &RHS_r = RHS.getComplexFloatReal();
5762 APFloat &RHS_i = RHS.getComplexFloatImag();
5763 APFloat &Res_r = Result.getComplexFloatReal();
5764 APFloat &Res_i = Result.getComplexFloatImag();
5765
5766 APFloat Den = RHS_r;
5767 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5768 APFloat Tmp = RHS_i;
5769 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5770 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5771
5772 Res_r = LHS_r;
5773 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5774 Tmp = LHS_i;
5775 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5776 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5777 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5778
5779 Res_i = LHS_i;
5780 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5781 Tmp = LHS_r;
5782 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5783 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5784 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5785 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00005786 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5787 return Error(E, diag::note_expr_divide_by_zero);
5788
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005789 ComplexValue LHS = Result;
5790 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5791 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5792 Result.getComplexIntReal() =
5793 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5794 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5795 Result.getComplexIntImag() =
5796 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5797 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5798 }
5799 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005800 }
5801
John McCallf4cf1a12010-05-07 17:22:02 +00005802 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005803}
5804
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005805bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5806 // Get the operand value into 'Result'.
5807 if (!Visit(E->getSubExpr()))
5808 return false;
5809
5810 switch (E->getOpcode()) {
5811 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00005812 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005813 case UO_Extension:
5814 return true;
5815 case UO_Plus:
5816 // The result is always just the subexpr.
5817 return true;
5818 case UO_Minus:
5819 if (Result.isComplexFloat()) {
5820 Result.getComplexFloatReal().changeSign();
5821 Result.getComplexFloatImag().changeSign();
5822 }
5823 else {
5824 Result.getComplexIntReal() = -Result.getComplexIntReal();
5825 Result.getComplexIntImag() = -Result.getComplexIntImag();
5826 }
5827 return true;
5828 case UO_Not:
5829 if (Result.isComplexFloat())
5830 Result.getComplexFloatImag().changeSign();
5831 else
5832 Result.getComplexIntImag() = -Result.getComplexIntImag();
5833 return true;
5834 }
5835}
5836
Eli Friedman7ead5c72012-01-10 04:58:17 +00005837bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5838 if (E->getNumInits() == 2) {
5839 if (E->getType()->isComplexType()) {
5840 Result.makeComplexFloat();
5841 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5842 return false;
5843 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5844 return false;
5845 } else {
5846 Result.makeComplexInt();
5847 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5848 return false;
5849 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5850 return false;
5851 }
5852 return true;
5853 }
5854 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5855}
5856
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005857//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00005858// Void expression evaluation, primarily for a cast to void on the LHS of a
5859// comma operator
5860//===----------------------------------------------------------------------===//
5861
5862namespace {
5863class VoidExprEvaluator
5864 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5865public:
5866 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5867
5868 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00005869
5870 bool VisitCastExpr(const CastExpr *E) {
5871 switch (E->getCastKind()) {
5872 default:
5873 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5874 case CK_ToVoid:
5875 VisitIgnoredValue(E->getSubExpr());
5876 return true;
5877 }
5878 }
5879};
5880} // end anonymous namespace
5881
5882static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5883 assert(E->isRValue() && E->getType()->isVoidType());
5884 return VoidExprEvaluator(Info).Visit(E);
5885}
5886
5887//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00005888// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005889//===----------------------------------------------------------------------===//
5890
Richard Smith47a1eed2011-10-29 20:57:55 +00005891static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00005892 // In C, function designators are not lvalues, but we evaluate them as if they
5893 // are.
5894 if (E->isGLValue() || E->getType()->isFunctionType()) {
5895 LValue LV;
5896 if (!EvaluateLValue(E, LV, Info))
5897 return false;
5898 LV.moveInto(Result);
5899 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005900 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00005901 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00005902 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005903 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005904 return false;
John McCallefdb83e2010-05-07 21:00:08 +00005905 } else if (E->getType()->hasPointerRepresentation()) {
5906 LValue LV;
5907 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005908 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005909 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00005910 } else if (E->getType()->isRealFloatingType()) {
5911 llvm::APFloat F(0.0);
5912 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005913 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00005914 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00005915 } else if (E->getType()->isAnyComplexType()) {
5916 ComplexValue C;
5917 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005918 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005919 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00005920 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005921 MemberPtr P;
5922 if (!EvaluateMemberPointer(E, P, Info))
5923 return false;
5924 P.moveInto(Result);
5925 return true;
Richard Smith51201882011-12-30 21:15:51 +00005926 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005927 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00005928 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00005929 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00005930 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005931 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00005932 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005933 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00005934 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00005935 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5936 return false;
5937 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00005938 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00005939 if (Info.getLangOpts().CPlusPlus0x)
5940 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5941 << E->getType();
5942 else
5943 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00005944 if (!EvaluateVoid(E, Info))
5945 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005946 } else if (Info.getLangOpts().CPlusPlus0x) {
5947 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5948 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005949 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00005950 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00005951 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005952 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005953
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00005954 return true;
5955}
5956
Richard Smith83587db2012-02-15 02:18:13 +00005957/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
5958/// cases, the in-place evaluation is essential, since later initializers for
5959/// an object can indirectly refer to subobjects which were initialized earlier.
5960static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
5961 const Expr *E, CheckConstantExpressionKind CCEK,
5962 bool AllowNonLiteralTypes) {
Richard Smith7ca48502012-02-13 22:16:19 +00005963 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smith51201882011-12-30 21:15:51 +00005964 return false;
5965
5966 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00005967 // Evaluate arrays and record types in-place, so that later initializers can
5968 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00005969 if (E->getType()->isArrayType())
5970 return EvaluateArray(E, This, Result, Info);
5971 else if (E->getType()->isRecordType())
5972 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00005973 }
5974
5975 // For any other type, in-place evaluation is unimportant.
5976 CCValue CoreConstResult;
Richard Smith83587db2012-02-15 02:18:13 +00005977 if (!Evaluate(CoreConstResult, Info, E))
5978 return false;
5979 Result = CoreConstResult.toAPValue();
5980 return true;
Richard Smith69c2c502011-11-04 05:33:44 +00005981}
5982
Richard Smithf48fdb02011-12-09 22:58:01 +00005983/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5984/// lvalue-to-rvalue cast if it is an lvalue.
5985static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00005986 if (!CheckLiteralType(Info, E))
5987 return false;
5988
Richard Smithf48fdb02011-12-09 22:58:01 +00005989 CCValue Value;
5990 if (!::Evaluate(Value, Info, E))
5991 return false;
5992
5993 if (E->isGLValue()) {
5994 LValue LV;
5995 LV.setFrom(Value);
5996 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
5997 return false;
5998 }
5999
6000 // Check this core constant expression is a constant expression, and if so,
6001 // convert it to one.
Richard Smith83587db2012-02-15 02:18:13 +00006002 Result = Value.toAPValue();
6003 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf48fdb02011-12-09 22:58:01 +00006004}
Richard Smithc49bd112011-10-28 17:51:58 +00006005
Richard Smith51f47082011-10-29 00:50:52 +00006006/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00006007/// any crazy technique (that has nothing to do with language standards) that
6008/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00006009/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6010/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00006011bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00006012 // Fast-path evaluations of integer literals, since we sometimes see files
6013 // containing vast quantities of these.
6014 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
6015 Result.Val = APValue(APSInt(L->getValue(),
6016 L->getType()->isUnsignedIntegerType()));
6017 return true;
6018 }
6019
Richard Smith2d6a5672012-01-14 04:30:29 +00006020 // FIXME: Evaluating values of large array and record types can cause
6021 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00006022 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
6023 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00006024 return false;
6025
Richard Smithf48fdb02011-12-09 22:58:01 +00006026 EvalInfo Info(Ctx, Result);
6027 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00006028}
6029
Jay Foad4ba2a172011-01-12 09:06:06 +00006030bool Expr::EvaluateAsBooleanCondition(bool &Result,
6031 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00006032 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00006033 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithb4e85ed2012-01-06 16:39:00 +00006034 HandleConversionToBool(CCValue(const_cast<ASTContext&>(Ctx),
6035 Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00006036 Result);
John McCallcd7a4452010-01-05 23:42:56 +00006037}
6038
Richard Smith80d4b552011-12-28 19:48:30 +00006039bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6040 SideEffectsKind AllowSideEffects) const {
6041 if (!getType()->isIntegralOrEnumerationType())
6042 return false;
6043
Richard Smithc49bd112011-10-28 17:51:58 +00006044 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00006045 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6046 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00006047 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006048
Richard Smithc49bd112011-10-28 17:51:58 +00006049 Result = ExprResult.Val.getInt();
6050 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006051}
6052
Jay Foad4ba2a172011-01-12 09:06:06 +00006053bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00006054 EvalInfo Info(Ctx, Result);
6055
John McCallefdb83e2010-05-07 21:00:08 +00006056 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006057 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6058 !CheckLValueConstantExpression(Info, getExprLoc(),
6059 Ctx.getLValueReferenceType(getType()), LV))
6060 return false;
6061
6062 CCValue Tmp;
6063 LV.moveInto(Tmp);
6064 Result.Val = Tmp.toAPValue();
6065 return true;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00006066}
6067
Richard Smith099e7f62011-12-19 06:19:21 +00006068bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6069 const VarDecl *VD,
6070 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00006071 // FIXME: Evaluating initializers for large array and record types can cause
6072 // performance problems. Only do so in C++11 for now.
6073 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
6074 !Ctx.getLangOptions().CPlusPlus0x)
6075 return false;
6076
Richard Smith099e7f62011-12-19 06:19:21 +00006077 Expr::EvalStatus EStatus;
6078 EStatus.Diag = &Notes;
6079
6080 EvalInfo InitInfo(Ctx, EStatus);
6081 InitInfo.setEvaluatingDecl(VD, Value);
6082
6083 LValue LVal;
6084 LVal.set(VD);
6085
Richard Smith51201882011-12-30 21:15:51 +00006086 // C++11 [basic.start.init]p2:
6087 // Variables with static storage duration or thread storage duration shall be
6088 // zero-initialized before any other initialization takes place.
6089 // This behavior is not present in C.
6090 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
6091 !VD->getType()->isReferenceType()) {
6092 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith83587db2012-02-15 02:18:13 +00006093 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6094 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00006095 return false;
6096 }
6097
Richard Smith83587db2012-02-15 02:18:13 +00006098 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6099 /*AllowNonLiteralTypes=*/true) ||
6100 EStatus.HasSideEffects)
6101 return false;
6102
6103 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6104 Value);
Richard Smith099e7f62011-12-19 06:19:21 +00006105}
6106
Richard Smith51f47082011-10-29 00:50:52 +00006107/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6108/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00006109bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00006110 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00006111 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00006112}
Anders Carlsson51fe9962008-11-22 21:04:56 +00006113
Jay Foad4ba2a172011-01-12 09:06:06 +00006114bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00006115 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00006116}
6117
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006118APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006119 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00006120 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00006121 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00006122 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006123 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00006124
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006125 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00006126}
John McCalld905f5a2010-05-07 05:32:02 +00006127
Abramo Bagnarae17a6432010-05-14 17:07:14 +00006128 bool Expr::EvalResult::isGlobalLValue() const {
6129 assert(Val.isLValue());
6130 return IsGlobalLValue(Val.getLValueBase());
6131 }
6132
6133
John McCalld905f5a2010-05-07 05:32:02 +00006134/// isIntegerConstantExpr - this recursive routine will test if an expression is
6135/// an integer constant expression.
6136
6137/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6138/// comma, etc
6139///
6140/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
6141/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
6142/// cast+dereference.
6143
6144// CheckICE - This function does the fundamental ICE checking: the returned
6145// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
6146// Note that to reduce code duplication, this helper does no evaluation
6147// itself; the caller checks whether the expression is evaluatable, and
6148// in the rare cases where CheckICE actually cares about the evaluated
6149// value, it calls into Evalute.
6150//
6151// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00006152// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00006153// 1: This expression is not an ICE, but if it isn't evaluated, it's
6154// a legal subexpression for an ICE. This return value is used to handle
6155// the comma operator in C99 mode.
6156// 2: This expression is not an ICE, and is not a legal subexpression for one.
6157
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006158namespace {
6159
John McCalld905f5a2010-05-07 05:32:02 +00006160struct ICEDiag {
6161 unsigned Val;
6162 SourceLocation Loc;
6163
6164 public:
6165 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6166 ICEDiag() : Val(0) {}
6167};
6168
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006169}
6170
6171static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00006172
6173static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6174 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006175 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00006176 !EVResult.Val.isInt()) {
6177 return ICEDiag(2, E->getLocStart());
6178 }
6179 return NoDiag();
6180}
6181
6182static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6183 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00006184 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00006185 return ICEDiag(2, E->getLocStart());
6186 }
6187
6188 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006189#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006190#define STMT(Node, Base) case Expr::Node##Class:
6191#define EXPR(Node, Base)
6192#include "clang/AST/StmtNodes.inc"
6193 case Expr::PredefinedExprClass:
6194 case Expr::FloatingLiteralClass:
6195 case Expr::ImaginaryLiteralClass:
6196 case Expr::StringLiteralClass:
6197 case Expr::ArraySubscriptExprClass:
6198 case Expr::MemberExprClass:
6199 case Expr::CompoundAssignOperatorClass:
6200 case Expr::CompoundLiteralExprClass:
6201 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006202 case Expr::DesignatedInitExprClass:
6203 case Expr::ImplicitValueInitExprClass:
6204 case Expr::ParenListExprClass:
6205 case Expr::VAArgExprClass:
6206 case Expr::AddrLabelExprClass:
6207 case Expr::StmtExprClass:
6208 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006209 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006210 case Expr::CXXDynamicCastExprClass:
6211 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006212 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006213 case Expr::CXXNullPtrLiteralExprClass:
6214 case Expr::CXXThisExprClass:
6215 case Expr::CXXThrowExprClass:
6216 case Expr::CXXNewExprClass:
6217 case Expr::CXXDeleteExprClass:
6218 case Expr::CXXPseudoDestructorExprClass:
6219 case Expr::UnresolvedLookupExprClass:
6220 case Expr::DependentScopeDeclRefExprClass:
6221 case Expr::CXXConstructExprClass:
6222 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006223 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006224 case Expr::CXXTemporaryObjectExprClass:
6225 case Expr::CXXUnresolvedConstructExprClass:
6226 case Expr::CXXDependentScopeMemberExprClass:
6227 case Expr::UnresolvedMemberExprClass:
6228 case Expr::ObjCStringLiteralClass:
6229 case Expr::ObjCEncodeExprClass:
6230 case Expr::ObjCMessageExprClass:
6231 case Expr::ObjCSelectorExprClass:
6232 case Expr::ObjCProtocolExprClass:
6233 case Expr::ObjCIvarRefExprClass:
6234 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006235 case Expr::ObjCIsaExprClass:
6236 case Expr::ShuffleVectorExprClass:
6237 case Expr::BlockExprClass:
6238 case Expr::BlockDeclRefExprClass:
6239 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006240 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006241 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006242 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006243 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006244 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006245 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006246 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006247 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006248 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00006249 case Expr::LambdaExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006250 return ICEDiag(2, E->getLocStart());
6251
Douglas Gregoree8aff02011-01-04 17:33:58 +00006252 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006253 case Expr::GNUNullExprClass:
6254 // GCC considers the GNU __null value to be an integral constant expression.
6255 return NoDiag();
6256
John McCall91a57552011-07-15 05:09:51 +00006257 case Expr::SubstNonTypeTemplateParmExprClass:
6258 return
6259 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6260
John McCalld905f5a2010-05-07 05:32:02 +00006261 case Expr::ParenExprClass:
6262 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006263 case Expr::GenericSelectionExprClass:
6264 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006265 case Expr::IntegerLiteralClass:
6266 case Expr::CharacterLiteralClass:
6267 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006268 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006269 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006270 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006271 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006272 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006273 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006274 return NoDiag();
6275 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006276 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006277 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6278 // constant expressions, but they can never be ICEs because an ICE cannot
6279 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006280 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006281 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006282 return CheckEvalInICE(E, Ctx);
6283 return ICEDiag(2, E->getLocStart());
6284 }
6285 case Expr::DeclRefExprClass:
6286 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6287 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00006288 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006289 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
6290
6291 // Parameter variables are never constants. Without this check,
6292 // getAnyInitializer() can find a default argument, which leads
6293 // to chaos.
6294 if (isa<ParmVarDecl>(D))
6295 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6296
6297 // C++ 7.1.5.1p2
6298 // A variable of non-volatile const-qualified integral or enumeration
6299 // type initialized by an ICE can be used in ICEs.
6300 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006301 if (!Dcl->getType()->isIntegralOrEnumerationType())
6302 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6303
Richard Smith099e7f62011-12-19 06:19:21 +00006304 const VarDecl *VD;
6305 // Look for a declaration of this variable that has an initializer, and
6306 // check whether it is an ICE.
6307 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6308 return NoDiag();
6309 else
6310 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006311 }
6312 }
6313 return ICEDiag(2, E->getLocStart());
6314 case Expr::UnaryOperatorClass: {
6315 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6316 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006317 case UO_PostInc:
6318 case UO_PostDec:
6319 case UO_PreInc:
6320 case UO_PreDec:
6321 case UO_AddrOf:
6322 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006323 // C99 6.6/3 allows increment and decrement within unevaluated
6324 // subexpressions of constant expressions, but they can never be ICEs
6325 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006326 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006327 case UO_Extension:
6328 case UO_LNot:
6329 case UO_Plus:
6330 case UO_Minus:
6331 case UO_Not:
6332 case UO_Real:
6333 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006334 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006335 }
6336
6337 // OffsetOf falls through here.
6338 }
6339 case Expr::OffsetOfExprClass: {
6340 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00006341 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00006342 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00006343 // compliance: we should warn earlier for offsetof expressions with
6344 // array subscripts that aren't ICEs, and if the array subscripts
6345 // are ICEs, the value of the offsetof must be an integer constant.
6346 return CheckEvalInICE(E, Ctx);
6347 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006348 case Expr::UnaryExprOrTypeTraitExprClass: {
6349 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6350 if ((Exp->getKind() == UETT_SizeOf) &&
6351 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00006352 return ICEDiag(2, E->getLocStart());
6353 return NoDiag();
6354 }
6355 case Expr::BinaryOperatorClass: {
6356 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6357 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006358 case BO_PtrMemD:
6359 case BO_PtrMemI:
6360 case BO_Assign:
6361 case BO_MulAssign:
6362 case BO_DivAssign:
6363 case BO_RemAssign:
6364 case BO_AddAssign:
6365 case BO_SubAssign:
6366 case BO_ShlAssign:
6367 case BO_ShrAssign:
6368 case BO_AndAssign:
6369 case BO_XorAssign:
6370 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006371 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6372 // constant expressions, but they can never be ICEs because an ICE cannot
6373 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006374 return ICEDiag(2, E->getLocStart());
6375
John McCall2de56d12010-08-25 11:45:40 +00006376 case BO_Mul:
6377 case BO_Div:
6378 case BO_Rem:
6379 case BO_Add:
6380 case BO_Sub:
6381 case BO_Shl:
6382 case BO_Shr:
6383 case BO_LT:
6384 case BO_GT:
6385 case BO_LE:
6386 case BO_GE:
6387 case BO_EQ:
6388 case BO_NE:
6389 case BO_And:
6390 case BO_Xor:
6391 case BO_Or:
6392 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006393 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6394 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006395 if (Exp->getOpcode() == BO_Div ||
6396 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006397 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006398 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006399 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006400 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006401 if (REval == 0)
6402 return ICEDiag(1, E->getLocStart());
6403 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006404 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006405 if (LEval.isMinSignedValue())
6406 return ICEDiag(1, E->getLocStart());
6407 }
6408 }
6409 }
John McCall2de56d12010-08-25 11:45:40 +00006410 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00006411 if (Ctx.getLangOptions().C99) {
6412 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6413 // if it isn't evaluated.
6414 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6415 return ICEDiag(1, E->getLocStart());
6416 } else {
6417 // In both C89 and C++, commas in ICEs are illegal.
6418 return ICEDiag(2, E->getLocStart());
6419 }
6420 }
6421 if (LHSResult.Val >= RHSResult.Val)
6422 return LHSResult;
6423 return RHSResult;
6424 }
John McCall2de56d12010-08-25 11:45:40 +00006425 case BO_LAnd:
6426 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006427 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6428 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6429 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6430 // Rare case where the RHS has a comma "side-effect"; we need
6431 // to actually check the condition to see whether the side
6432 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006433 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006434 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006435 return RHSResult;
6436 return NoDiag();
6437 }
6438
6439 if (LHSResult.Val >= RHSResult.Val)
6440 return LHSResult;
6441 return RHSResult;
6442 }
6443 }
6444 }
6445 case Expr::ImplicitCastExprClass:
6446 case Expr::CStyleCastExprClass:
6447 case Expr::CXXFunctionalCastExprClass:
6448 case Expr::CXXStaticCastExprClass:
6449 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006450 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006451 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006452 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006453 if (isa<ExplicitCastExpr>(E)) {
6454 if (const FloatingLiteral *FL
6455 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6456 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6457 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6458 APSInt IgnoredVal(DestWidth, !DestSigned);
6459 bool Ignored;
6460 // If the value does not fit in the destination type, the behavior is
6461 // undefined, so we are not required to treat it as a constant
6462 // expression.
6463 if (FL->getValue().convertToInteger(IgnoredVal,
6464 llvm::APFloat::rmTowardZero,
6465 &Ignored) & APFloat::opInvalidOp)
6466 return ICEDiag(2, E->getLocStart());
6467 return NoDiag();
6468 }
6469 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006470 switch (cast<CastExpr>(E)->getCastKind()) {
6471 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006472 case CK_AtomicToNonAtomic:
6473 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006474 case CK_NoOp:
6475 case CK_IntegralToBoolean:
6476 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006477 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006478 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006479 return ICEDiag(2, E->getLocStart());
6480 }
John McCalld905f5a2010-05-07 05:32:02 +00006481 }
John McCall56ca35d2011-02-17 10:25:35 +00006482 case Expr::BinaryConditionalOperatorClass: {
6483 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6484 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6485 if (CommonResult.Val == 2) return CommonResult;
6486 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6487 if (FalseResult.Val == 2) return FalseResult;
6488 if (CommonResult.Val == 1) return CommonResult;
6489 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006490 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006491 return FalseResult;
6492 }
John McCalld905f5a2010-05-07 05:32:02 +00006493 case Expr::ConditionalOperatorClass: {
6494 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6495 // If the condition (ignoring parens) is a __builtin_constant_p call,
6496 // then only the true side is actually considered in an integer constant
6497 // expression, and it is fully evaluated. This is an important GNU
6498 // extension. See GCC PR38377 for discussion.
6499 if (const CallExpr *CallCE
6500 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006501 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6502 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006503 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006504 if (CondResult.Val == 2)
6505 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006506
Richard Smithf48fdb02011-12-09 22:58:01 +00006507 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6508 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006509
John McCalld905f5a2010-05-07 05:32:02 +00006510 if (TrueResult.Val == 2)
6511 return TrueResult;
6512 if (FalseResult.Val == 2)
6513 return FalseResult;
6514 if (CondResult.Val == 1)
6515 return CondResult;
6516 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6517 return NoDiag();
6518 // Rare case where the diagnostics depend on which side is evaluated
6519 // Note that if we get here, CondResult is 0, and at least one of
6520 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006521 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006522 return FalseResult;
6523 }
6524 return TrueResult;
6525 }
6526 case Expr::CXXDefaultArgExprClass:
6527 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6528 case Expr::ChooseExprClass: {
6529 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6530 }
6531 }
6532
David Blaikie30263482012-01-20 21:50:17 +00006533 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006534}
6535
Richard Smithf48fdb02011-12-09 22:58:01 +00006536/// Evaluate an expression as a C++11 integral constant expression.
6537static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6538 const Expr *E,
6539 llvm::APSInt *Value,
6540 SourceLocation *Loc) {
6541 if (!E->getType()->isIntegralOrEnumerationType()) {
6542 if (Loc) *Loc = E->getExprLoc();
6543 return false;
6544 }
6545
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006546 APValue Result;
6547 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006548 return false;
6549
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006550 assert(Result.isInt() && "pointer cast to int is not an ICE");
6551 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006552 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006553}
6554
Richard Smithdd1f29b2011-12-12 09:28:41 +00006555bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00006556 if (Ctx.getLangOptions().CPlusPlus0x)
6557 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6558
John McCalld905f5a2010-05-07 05:32:02 +00006559 ICEDiag d = CheckICE(this, Ctx);
6560 if (d.Val != 0) {
6561 if (Loc) *Loc = d.Loc;
6562 return false;
6563 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006564 return true;
6565}
6566
6567bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6568 SourceLocation *Loc, bool isEvaluated) const {
6569 if (Ctx.getLangOptions().CPlusPlus0x)
6570 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6571
6572 if (!isIntegerConstantExpr(Ctx, Loc))
6573 return false;
6574 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006575 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006576 return true;
6577}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006578
Richard Smith70488e22012-02-14 21:38:30 +00006579bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
6580 return CheckICE(this, Ctx).Val == 0;
6581}
6582
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006583bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6584 SourceLocation *Loc) const {
6585 // We support this checking in C++98 mode in order to diagnose compatibility
6586 // issues.
6587 assert(Ctx.getLangOptions().CPlusPlus);
6588
Richard Smith70488e22012-02-14 21:38:30 +00006589 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006590 Expr::EvalStatus Status;
6591 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6592 Status.Diag = &Diags;
6593 EvalInfo Info(Ctx, Status);
6594
6595 APValue Scratch;
6596 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6597
6598 if (!Diags.empty()) {
6599 IsConstExpr = false;
6600 if (Loc) *Loc = Diags[0].first;
6601 } else if (!IsConstExpr) {
6602 // FIXME: This shouldn't happen.
6603 if (Loc) *Loc = getExprLoc();
6604 }
6605
6606 return IsConstExpr;
6607}
Richard Smith745f5142012-01-27 01:14:48 +00006608
6609bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6610 llvm::SmallVectorImpl<
6611 PartialDiagnosticAt> &Diags) {
6612 // FIXME: It would be useful to check constexpr function templates, but at the
6613 // moment the constant expression evaluator cannot cope with the non-rigorous
6614 // ASTs which we build for dependent expressions.
6615 if (FD->isDependentContext())
6616 return true;
6617
6618 Expr::EvalStatus Status;
6619 Status.Diag = &Diags;
6620
6621 EvalInfo Info(FD->getASTContext(), Status);
6622 Info.CheckingPotentialConstantExpression = true;
6623
6624 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6625 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6626
6627 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6628 // is a temporary being used as the 'this' pointer.
6629 LValue This;
6630 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smith83587db2012-02-15 02:18:13 +00006631 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith745f5142012-01-27 01:14:48 +00006632
Richard Smith745f5142012-01-27 01:14:48 +00006633 ArrayRef<const Expr*> Args;
6634
6635 SourceLocation Loc = FD->getLocation();
6636
6637 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Richard Smith83587db2012-02-15 02:18:13 +00006638 APValue Scratch;
Richard Smith745f5142012-01-27 01:14:48 +00006639 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith83587db2012-02-15 02:18:13 +00006640 } else {
6641 CCValue Scratch;
Richard Smith745f5142012-01-27 01:14:48 +00006642 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6643 Args, FD->getBody(), Info, Scratch);
Richard Smith83587db2012-02-15 02:18:13 +00006644 }
Richard Smith745f5142012-01-27 01:14:48 +00006645
6646 return Diags.empty();
6647}