blob: ccad97579651a513dfbf2e6fd42f5dc3f5273073 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-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 Smith253c2a32012-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 Carlsson7a241ba2008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000038#include "clang/AST/ASTDiagnostic.h"
Ken Dyck40775002010-01-11 17:06:35 +000039#include "clang/AST/CharUnits.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000040#include "clang/AST/Expr.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000041#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000042#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000043#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000044#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000045#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000046#include "llvm/ADT/SmallString.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000047#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000048#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000049#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000050
Anders Carlsson7a241ba2008-07-03 04:20:39 +000051using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000052using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000053using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000054
Richard Smithb228a862012-02-15 02:18:13 +000055static bool IsGlobalLValue(APValue::LValueBase B);
56
John McCall93d91dc2010-05-07 17:22:02 +000057namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000058 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000059 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000060 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000061
Richard Smithb228a862012-02-15 02:18:13 +000062 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000063 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65 return D->getType();
66 return B.get<const Expr*>()->getType();
67 }
68
Richard Smithd62306a2011-11-10 06:34:14 +000069 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000070 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000071 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000072 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000073 APValue::BaseOrMemberType Value;
74 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +000075 return Value;
76 }
77
78 /// Get an LValue path entry, which is known to not be an array index, as a
79 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +000080 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000081 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +000082 }
83 /// Get an LValue path entry, which is known to not be an array index, as a
84 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +000085 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000086 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +000087 }
88 /// Determine whether this LValue path entry for a base class names a virtual
89 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +000090 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000091 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +000092 }
93
Richard Smitha8105bc2012-01-06 16:39:00 +000094 /// Find the path length and type of the most-derived subobject in the given
95 /// path, and find the size of the containing array, if any.
96 static
97 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
98 ArrayRef<APValue::LValuePathEntry> Path,
99 uint64_t &ArraySize, QualType &Type) {
100 unsigned MostDerivedLength = 0;
101 Type = Base;
Richard Smith80815602011-11-07 05:07:52 +0000102 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000103 if (Type->isArrayType()) {
104 const ConstantArrayType *CAT =
105 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
106 Type = CAT->getElementType();
107 ArraySize = CAT->getSize().getZExtValue();
108 MostDerivedLength = I + 1;
Richard Smith66c96992012-02-18 22:04:06 +0000109 } else if (Type->isAnyComplexType()) {
110 const ComplexType *CT = Type->castAs<ComplexType>();
111 Type = CT->getElementType();
112 ArraySize = 2;
113 MostDerivedLength = I + 1;
Richard Smitha8105bc2012-01-06 16:39:00 +0000114 } else if (const FieldDecl *FD = getAsField(Path[I])) {
115 Type = FD->getType();
116 ArraySize = 0;
117 MostDerivedLength = I + 1;
118 } else {
Richard Smith80815602011-11-07 05:07:52 +0000119 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000120 ArraySize = 0;
121 }
Richard Smith80815602011-11-07 05:07:52 +0000122 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000123 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000124 }
125
Richard Smitha8105bc2012-01-06 16:39:00 +0000126 // The order of this enum is important for diagnostics.
127 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000128 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000129 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000130 };
131
Richard Smith96e0c102011-11-04 02:25:55 +0000132 /// A path from a glvalue to a subobject of that glvalue.
133 struct SubobjectDesignator {
134 /// True if the subobject was named in a manner not supported by C++11. Such
135 /// lvalues can still be folded, but they are not core constant expressions
136 /// and we cannot perform lvalue-to-rvalue conversions on them.
137 bool Invalid : 1;
138
Richard Smitha8105bc2012-01-06 16:39:00 +0000139 /// Is this a pointer one past the end of an object?
140 bool IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000141
Richard Smitha8105bc2012-01-06 16:39:00 +0000142 /// The length of the path to the most-derived object of which this is a
143 /// subobject.
144 unsigned MostDerivedPathLength : 30;
145
146 /// The size of the array of which the most-derived object is an element, or
147 /// 0 if the most-derived object is not an array element.
148 uint64_t MostDerivedArraySize;
149
150 /// The type of the most derived object referred to by this address.
151 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000152
Richard Smith80815602011-11-07 05:07:52 +0000153 typedef APValue::LValuePathEntry PathEntry;
154
Richard Smith96e0c102011-11-04 02:25:55 +0000155 /// The entries on the path from the glvalue to the designated subobject.
156 SmallVector<PathEntry, 8> Entries;
157
Richard Smitha8105bc2012-01-06 16:39:00 +0000158 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000159
Richard Smitha8105bc2012-01-06 16:39:00 +0000160 explicit SubobjectDesignator(QualType T)
161 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
162 MostDerivedArraySize(0), MostDerivedType(T) {}
163
164 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
165 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
166 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith80815602011-11-07 05:07:52 +0000167 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000168 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000169 ArrayRef<PathEntry> VEntries = V.getLValuePath();
170 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
171 if (V.getLValueBase())
Richard Smitha8105bc2012-01-06 16:39:00 +0000172 MostDerivedPathLength =
173 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
174 V.getLValuePath(), MostDerivedArraySize,
175 MostDerivedType);
Richard Smith80815602011-11-07 05:07:52 +0000176 }
177 }
178
Richard Smith96e0c102011-11-04 02:25:55 +0000179 void setInvalid() {
180 Invalid = true;
181 Entries.clear();
182 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000183
184 /// Determine whether this is a one-past-the-end pointer.
185 bool isOnePastTheEnd() const {
186 if (IsOnePastTheEnd)
187 return true;
188 if (MostDerivedArraySize &&
189 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
190 return true;
191 return false;
192 }
193
194 /// Check that this refers to a valid subobject.
195 bool isValidSubobject() const {
196 if (Invalid)
197 return false;
198 return !isOnePastTheEnd();
199 }
200 /// Check that this refers to a valid subobject, and if not, produce a
201 /// relevant diagnostic and set the designator as invalid.
202 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
203
204 /// Update this designator to refer to the first element within this array.
205 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000206 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000207 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000208 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000209
210 // This is a most-derived object.
211 MostDerivedType = CAT->getElementType();
212 MostDerivedArraySize = CAT->getSize().getZExtValue();
213 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000214 }
215 /// Update this designator to refer to the given base or member of this
216 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000217 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000218 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000219 APValue::BaseOrMemberType Value(D, Virtual);
220 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000221 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000222
223 // If this isn't a base class, it's a new most-derived object.
224 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
225 MostDerivedType = FD->getType();
226 MostDerivedArraySize = 0;
227 MostDerivedPathLength = Entries.size();
228 }
Richard Smith96e0c102011-11-04 02:25:55 +0000229 }
Richard Smith66c96992012-02-18 22:04:06 +0000230 /// Update this designator to refer to the given complex component.
231 void addComplexUnchecked(QualType EltTy, bool Imag) {
232 PathEntry Entry;
233 Entry.ArrayIndex = Imag;
234 Entries.push_back(Entry);
235
236 // This is technically a most-derived object, though in practice this
237 // is unlikely to matter.
238 MostDerivedType = EltTy;
239 MostDerivedArraySize = 2;
240 MostDerivedPathLength = Entries.size();
241 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000242 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith96e0c102011-11-04 02:25:55 +0000243 /// Add N to the address of this subobject.
Richard Smitha8105bc2012-01-06 16:39:00 +0000244 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith96e0c102011-11-04 02:25:55 +0000245 if (Invalid) return;
Richard Smitha8105bc2012-01-06 16:39:00 +0000246 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith80815602011-11-07 05:07:52 +0000247 Entries.back().ArrayIndex += N;
Richard Smitha8105bc2012-01-06 16:39:00 +0000248 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
249 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
250 setInvalid();
251 }
Richard Smith96e0c102011-11-04 02:25:55 +0000252 return;
253 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000254 // [expr.add]p4: For the purposes of these operators, a pointer to a
255 // nonarray object behaves the same as a pointer to the first element of
256 // an array of length one with the type of the object as its element type.
257 if (IsOnePastTheEnd && N == (uint64_t)-1)
258 IsOnePastTheEnd = false;
259 else if (!IsOnePastTheEnd && N == 1)
260 IsOnePastTheEnd = true;
261 else if (N != 0) {
262 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith96e0c102011-11-04 02:25:55 +0000263 setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000264 }
Richard Smith96e0c102011-11-04 02:25:55 +0000265 }
266 };
267
Richard Smith254a73d2011-10-28 22:34:42 +0000268 /// A stack frame in the constexpr call stack.
269 struct CallStackFrame {
270 EvalInfo &Info;
271
272 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000273 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000274
Richard Smithf6f003a2011-12-16 19:06:07 +0000275 /// CallLoc - The location of the call expression for this call.
276 SourceLocation CallLoc;
277
278 /// Callee - The function which was called.
279 const FunctionDecl *Callee;
280
Richard Smithb228a862012-02-15 02:18:13 +0000281 /// Index - The call index of this call.
282 unsigned Index;
283
Richard Smithd62306a2011-11-10 06:34:14 +0000284 /// This - The binding for the this pointer in this call, if any.
285 const LValue *This;
286
Richard Smith254a73d2011-10-28 22:34:42 +0000287 /// ParmBindings - Parameter bindings for this function call, indexed by
288 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000289 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000290
Eli Friedman4830ec82012-06-25 21:21:08 +0000291 // Note that we intentionally use std::map here so that references to
292 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000293 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000294 typedef MapTy::const_iterator temp_iterator;
295 /// Temporaries - Temporary lvalues materialized within this stack frame.
296 MapTy Temporaries;
297
Richard Smithf6f003a2011-12-16 19:06:07 +0000298 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
299 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000300 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000301 ~CallStackFrame();
Richard Smith254a73d2011-10-28 22:34:42 +0000302 };
303
Richard Smith852c9db2013-04-20 22:23:05 +0000304 /// Temporarily override 'this'.
305 class ThisOverrideRAII {
306 public:
307 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
308 : Frame(Frame), OldThis(Frame.This) {
309 if (Enable)
310 Frame.This = NewThis;
311 }
312 ~ThisOverrideRAII() {
313 Frame.This = OldThis;
314 }
315 private:
316 CallStackFrame &Frame;
317 const LValue *OldThis;
318 };
319
Richard Smith92b1ce02011-12-12 09:28:41 +0000320 /// A partial diagnostic which we might know in advance that we are not going
321 /// to emit.
322 class OptionalDiagnostic {
323 PartialDiagnostic *Diag;
324
325 public:
326 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
327
328 template<typename T>
329 OptionalDiagnostic &operator<<(const T &v) {
330 if (Diag)
331 *Diag << v;
332 return *this;
333 }
Richard Smithfe800032012-01-31 04:08:20 +0000334
335 OptionalDiagnostic &operator<<(const APSInt &I) {
336 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000337 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000338 I.toString(Buffer);
339 *Diag << StringRef(Buffer.data(), Buffer.size());
340 }
341 return *this;
342 }
343
344 OptionalDiagnostic &operator<<(const APFloat &F) {
345 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000346 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000347 F.toString(Buffer);
348 *Diag << StringRef(Buffer.data(), Buffer.size());
349 }
350 return *this;
351 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000352 };
353
Richard Smithb228a862012-02-15 02:18:13 +0000354 /// EvalInfo - This is a private struct used by the evaluator to capture
355 /// information about a subexpression as it is folded. It retains information
356 /// about the AST context, but also maintains information about the folded
357 /// expression.
358 ///
359 /// If an expression could be evaluated, it is still possible it is not a C
360 /// "integer constant expression" or constant expression. If not, this struct
361 /// captures information about how and why not.
362 ///
363 /// One bit of information passed *into* the request for constant folding
364 /// indicates whether the subexpression is "evaluated" or not according to C
365 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
366 /// evaluate the expression regardless of what the RHS is, but C only allows
367 /// certain things in certain situations.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000368 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000369 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000370
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000371 /// EvalStatus - Contains information about the evaluation.
372 Expr::EvalStatus &EvalStatus;
373
374 /// CurrentCall - The top of the constexpr call stack.
375 CallStackFrame *CurrentCall;
376
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000377 /// CallStackDepth - The number of calls in the call stack right now.
378 unsigned CallStackDepth;
379
Richard Smithb228a862012-02-15 02:18:13 +0000380 /// NextCallIndex - The next call index to assign.
381 unsigned NextCallIndex;
382
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000383 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000384 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000385 CallStackFrame BottomFrame;
386
Richard Smithd62306a2011-11-10 06:34:14 +0000387 /// EvaluatingDecl - This is the declaration whose initializer is being
388 /// evaluated, if any.
389 const VarDecl *EvaluatingDecl;
390
391 /// EvaluatingDeclValue - This is the value being constructed for the
392 /// declaration whose initializer is being evaluated, if any.
393 APValue *EvaluatingDeclValue;
394
Richard Smith357362d2011-12-13 06:39:58 +0000395 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
396 /// notes attached to it will also be stored, otherwise they will not be.
397 bool HasActiveDiagnostic;
398
Richard Smith253c2a32012-01-27 01:14:48 +0000399 /// CheckingPotentialConstantExpression - Are we checking whether the
400 /// expression is a potential constant expression? If so, some diagnostics
401 /// are suppressed.
402 bool CheckingPotentialConstantExpression;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000403
404 bool IntOverflowCheckMode;
Richard Smith253c2a32012-01-27 01:14:48 +0000405
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000406 EvalInfo(const ASTContext &C, Expr::EvalStatus &S,
407 bool OverflowCheckMode=false)
Richard Smith92b1ce02011-12-12 09:28:41 +0000408 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smithb228a862012-02-15 02:18:13 +0000409 CallStackDepth(0), NextCallIndex(1),
410 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith253c2a32012-01-27 01:14:48 +0000411 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000412 CheckingPotentialConstantExpression(false),
413 IntOverflowCheckMode(OverflowCheckMode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000414
Richard Smithd62306a2011-11-10 06:34:14 +0000415 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
416 EvaluatingDecl = VD;
417 EvaluatingDeclValue = &Value;
418 }
419
David Blaikiebbafb8a2012-03-11 07:00:24 +0000420 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000421
Richard Smith357362d2011-12-13 06:39:58 +0000422 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000423 // Don't perform any constexpr calls (other than the call we're checking)
424 // when checking a potential constant expression.
425 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
426 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000427 if (NextCallIndex == 0) {
428 // NextCallIndex has wrapped around.
429 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
430 return false;
431 }
Richard Smith357362d2011-12-13 06:39:58 +0000432 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
433 return true;
434 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
435 << getLangOpts().ConstexprCallDepth;
436 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000437 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000438
Richard Smithb228a862012-02-15 02:18:13 +0000439 CallStackFrame *getCallFrame(unsigned CallIndex) {
440 assert(CallIndex && "no call index in getCallFrame");
441 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
442 // be null in this loop.
443 CallStackFrame *Frame = CurrentCall;
444 while (Frame->Index > CallIndex)
445 Frame = Frame->Caller;
446 return (Frame->Index == CallIndex) ? Frame : 0;
447 }
448
Richard Smith357362d2011-12-13 06:39:58 +0000449 private:
450 /// Add a diagnostic to the diagnostics list.
451 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
452 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
453 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
454 return EvalStatus.Diag->back().second;
455 }
456
Richard Smithf6f003a2011-12-16 19:06:07 +0000457 /// Add notes containing a call stack to the current point of evaluation.
458 void addCallStack(unsigned Limit);
459
Richard Smith357362d2011-12-13 06:39:58 +0000460 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000461 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000462 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
463 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000464 unsigned ExtraNotes = 0) {
Richard Smithf57d8cb2011-12-09 22:58:01 +0000465 // If we have a prior diagnostic, it will be noting that the expression
466 // isn't a constant expression. This diagnostic is more important.
467 // FIXME: We might want to show both diagnostics to the user.
Richard Smith92b1ce02011-12-12 09:28:41 +0000468 if (EvalStatus.Diag) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000469 unsigned CallStackNotes = CallStackDepth - 1;
470 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
471 if (Limit)
472 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith253c2a32012-01-27 01:14:48 +0000473 if (CheckingPotentialConstantExpression)
474 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000475
Richard Smith357362d2011-12-13 06:39:58 +0000476 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000477 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000478 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
479 addDiag(Loc, DiagId);
Richard Smith253c2a32012-01-27 01:14:48 +0000480 if (!CheckingPotentialConstantExpression)
481 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000482 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000483 }
Richard Smith357362d2011-12-13 06:39:58 +0000484 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000485 return OptionalDiagnostic();
486 }
487
Richard Smithce1ec5e2012-03-15 04:53:45 +0000488 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
489 = diag::note_invalid_subexpr_in_const_expr,
490 unsigned ExtraNotes = 0) {
491 if (EvalStatus.Diag)
492 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
493 HasActiveDiagnostic = false;
494 return OptionalDiagnostic();
495 }
496
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000497 bool getIntOverflowCheckMode() { return IntOverflowCheckMode; }
498
Richard Smith92b1ce02011-12-12 09:28:41 +0000499 /// Diagnose that the evaluation does not produce a C++11 core constant
500 /// expression.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000501 template<typename LocArg>
502 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000503 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000504 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000505 // Don't override a previous diagnostic.
Eli Friedmanebea9af2012-02-21 22:41:33 +0000506 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
507 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000508 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000509 }
Richard Smith357362d2011-12-13 06:39:58 +0000510 return Diag(Loc, DiagId, ExtraNotes);
511 }
512
513 /// Add a note to a prior diagnostic.
514 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
515 if (!HasActiveDiagnostic)
516 return OptionalDiagnostic();
517 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000518 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000519
520 /// Add a stack of notes to a prior diagnostic.
521 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
522 if (HasActiveDiagnostic) {
523 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
524 Diags.begin(), Diags.end());
525 }
526 }
Richard Smith253c2a32012-01-27 01:14:48 +0000527
528 /// Should we continue evaluation as much as possible after encountering a
529 /// construct which can't be folded?
530 bool keepEvaluatingAfterFailure() {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000531 // Should return true in IntOverflowCheckMode, so that we check for
532 // overflow even if some subexpressions can't be evaluated as constants.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000533 return IntOverflowCheckMode ||
534 (CheckingPotentialConstantExpression &&
535 EvalStatus.Diag && EvalStatus.Diag->empty());
Richard Smith253c2a32012-01-27 01:14:48 +0000536 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000537 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000538
539 /// Object used to treat all foldable expressions as constant expressions.
540 struct FoldConstant {
541 bool Enabled;
542
543 explicit FoldConstant(EvalInfo &Info)
544 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
545 !Info.EvalStatus.HasSideEffects) {
546 }
547 // Treat the value we've computed since this object was created as constant.
548 void Fold(EvalInfo &Info) {
549 if (Enabled && !Info.EvalStatus.Diag->empty() &&
550 !Info.EvalStatus.HasSideEffects)
551 Info.EvalStatus.Diag->clear();
552 }
553 };
Richard Smith17100ba2012-02-16 02:46:34 +0000554
555 /// RAII object used to suppress diagnostics and side-effects from a
556 /// speculative evaluation.
557 class SpeculativeEvaluationRAII {
558 EvalInfo &Info;
559 Expr::EvalStatus Old;
560
561 public:
562 SpeculativeEvaluationRAII(EvalInfo &Info,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000563 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = 0)
Richard Smith17100ba2012-02-16 02:46:34 +0000564 : Info(Info), Old(Info.EvalStatus) {
565 Info.EvalStatus.Diag = NewDiag;
566 }
567 ~SpeculativeEvaluationRAII() {
568 Info.EvalStatus = Old;
569 }
570 };
Richard Smithf6f003a2011-12-16 19:06:07 +0000571}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000572
Richard Smitha8105bc2012-01-06 16:39:00 +0000573bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
574 CheckSubobjectKind CSK) {
575 if (Invalid)
576 return false;
577 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000578 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000579 << CSK;
580 setInvalid();
581 return false;
582 }
583 return true;
584}
585
586void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
587 const Expr *E, uint64_t N) {
588 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000589 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000590 << static_cast<int>(N) << /*array*/ 0
591 << static_cast<unsigned>(MostDerivedArraySize);
592 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000593 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000594 << static_cast<int>(N) << /*non-array*/ 1;
595 setInvalid();
596}
597
Richard Smithf6f003a2011-12-16 19:06:07 +0000598CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
599 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000600 APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000601 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000602 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000603 Info.CurrentCall = this;
604 ++Info.CallStackDepth;
605}
606
607CallStackFrame::~CallStackFrame() {
608 assert(Info.CurrentCall == this && "calls retired out of order");
609 --Info.CallStackDepth;
610 Info.CurrentCall = Caller;
611}
612
613/// Produce a string describing the given constexpr call.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000614static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000615 unsigned ArgIndex = 0;
616 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith74388b42012-02-04 00:33:54 +0000617 !isa<CXXConstructorDecl>(Frame->Callee) &&
618 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smithf6f003a2011-12-16 19:06:07 +0000619
620 if (!IsMemberCall)
621 Out << *Frame->Callee << '(';
622
623 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
624 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumib8efa1e2012-01-26 09:37:36 +0000625 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smithf6f003a2011-12-16 19:06:07 +0000626 Out << ", ";
627
628 const ParmVarDecl *Param = *I;
Richard Smith2e312c82012-03-03 22:46:17 +0000629 const APValue &Arg = Frame->Arguments[ArgIndex];
630 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
Richard Smithf6f003a2011-12-16 19:06:07 +0000631
632 if (ArgIndex == 0 && IsMemberCall)
633 Out << "->" << *Frame->Callee << '(';
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000634 }
635
Richard Smithf6f003a2011-12-16 19:06:07 +0000636 Out << ')';
637}
638
639void EvalInfo::addCallStack(unsigned Limit) {
640 // Determine which calls to skip, if any.
641 unsigned ActiveCalls = CallStackDepth - 1;
642 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
643 if (Limit && Limit < ActiveCalls) {
644 SkipStart = Limit / 2 + Limit % 2;
645 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000646 }
647
Richard Smithf6f003a2011-12-16 19:06:07 +0000648 // Walk the call stack and add the diagnostics.
649 unsigned CallIdx = 0;
650 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
651 Frame = Frame->Caller, ++CallIdx) {
652 // Skip this call?
653 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
654 if (CallIdx == SkipStart) {
655 // Note that we're skipping calls.
656 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
657 << unsigned(ActiveCalls - Limit);
658 }
659 continue;
660 }
661
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000662 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +0000663 llvm::raw_svector_ostream Out(Buffer);
664 describeCall(Frame, Out);
665 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
666 }
667}
668
669namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000670 struct ComplexValue {
671 private:
672 bool IsInt;
673
674 public:
675 APSInt IntReal, IntImag;
676 APFloat FloatReal, FloatImag;
677
678 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
679
680 void makeComplexFloat() { IsInt = false; }
681 bool isComplexFloat() const { return !IsInt; }
682 APFloat &getComplexFloatReal() { return FloatReal; }
683 APFloat &getComplexFloatImag() { return FloatImag; }
684
685 void makeComplexInt() { IsInt = true; }
686 bool isComplexInt() const { return IsInt; }
687 APSInt &getComplexIntReal() { return IntReal; }
688 APSInt &getComplexIntImag() { return IntImag; }
689
Richard Smith2e312c82012-03-03 22:46:17 +0000690 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000691 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +0000692 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000693 else
Richard Smith2e312c82012-03-03 22:46:17 +0000694 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000695 }
Richard Smith2e312c82012-03-03 22:46:17 +0000696 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000697 assert(v.isComplexFloat() || v.isComplexInt());
698 if (v.isComplexFloat()) {
699 makeComplexFloat();
700 FloatReal = v.getComplexFloatReal();
701 FloatImag = v.getComplexFloatImag();
702 } else {
703 makeComplexInt();
704 IntReal = v.getComplexIntReal();
705 IntImag = v.getComplexIntImag();
706 }
707 }
John McCall93d91dc2010-05-07 17:22:02 +0000708 };
John McCall45d55e42010-05-07 21:00:08 +0000709
710 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000711 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000712 CharUnits Offset;
Richard Smithb228a862012-02-15 02:18:13 +0000713 unsigned CallIndex;
Richard Smith96e0c102011-11-04 02:25:55 +0000714 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000715
Richard Smithce40ad62011-11-12 22:28:03 +0000716 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000717 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000718 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +0000719 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +0000720 SubobjectDesignator &getLValueDesignator() { return Designator; }
721 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000722
Richard Smith2e312c82012-03-03 22:46:17 +0000723 void moveInto(APValue &V) const {
724 if (Designator.Invalid)
725 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
726 else
727 V = APValue(Base, Offset, Designator.Entries,
728 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000729 }
Richard Smith2e312c82012-03-03 22:46:17 +0000730 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000731 assert(V.isLValue());
732 Base = V.getLValueBase();
733 Offset = V.getLValueOffset();
Richard Smithb228a862012-02-15 02:18:13 +0000734 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +0000735 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +0000736 }
737
Richard Smithb228a862012-02-15 02:18:13 +0000738 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smithce40ad62011-11-12 22:28:03 +0000739 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000740 Offset = CharUnits::Zero();
Richard Smithb228a862012-02-15 02:18:13 +0000741 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +0000742 Designator = SubobjectDesignator(getType(B));
743 }
744
745 // Check that this LValue is not based on a null pointer. If it is, produce
746 // a diagnostic and mark the designator as invalid.
747 bool checkNullPointer(EvalInfo &Info, const Expr *E,
748 CheckSubobjectKind CSK) {
749 if (Designator.Invalid)
750 return false;
751 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000752 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000753 << CSK;
754 Designator.setInvalid();
755 return false;
756 }
757 return true;
758 }
759
760 // Check this LValue refers to an object. If not, set the designator to be
761 // invalid and emit a diagnostic.
762 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000763 // Outside C++11, do not build a designator referring to a subobject of
764 // any object: we won't use such a designator for anything.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000765 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000766 Designator.setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000767 return checkNullPointer(Info, E, CSK) &&
768 Designator.checkSubobject(Info, E, CSK);
769 }
770
771 void addDecl(EvalInfo &Info, const Expr *E,
772 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000773 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
774 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +0000775 }
776 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000777 if (checkSubobject(Info, E, CSK_ArrayToPointer))
778 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +0000779 }
Richard Smith66c96992012-02-18 22:04:06 +0000780 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000781 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
782 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +0000783 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000784 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000785 if (checkNullPointer(Info, E, CSK_ArrayIndex))
786 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +0000787 }
John McCall45d55e42010-05-07 21:00:08 +0000788 };
Richard Smith027bf112011-11-17 22:56:20 +0000789
790 struct MemberPtr {
791 MemberPtr() {}
792 explicit MemberPtr(const ValueDecl *Decl) :
793 DeclAndIsDerivedMember(Decl, false), Path() {}
794
795 /// The member or (direct or indirect) field referred to by this member
796 /// pointer, or 0 if this is a null member pointer.
797 const ValueDecl *getDecl() const {
798 return DeclAndIsDerivedMember.getPointer();
799 }
800 /// Is this actually a member of some type derived from the relevant class?
801 bool isDerivedMember() const {
802 return DeclAndIsDerivedMember.getInt();
803 }
804 /// Get the class which the declaration actually lives in.
805 const CXXRecordDecl *getContainingRecord() const {
806 return cast<CXXRecordDecl>(
807 DeclAndIsDerivedMember.getPointer()->getDeclContext());
808 }
809
Richard Smith2e312c82012-03-03 22:46:17 +0000810 void moveInto(APValue &V) const {
811 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +0000812 }
Richard Smith2e312c82012-03-03 22:46:17 +0000813 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +0000814 assert(V.isMemberPointer());
815 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
816 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
817 Path.clear();
818 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
819 Path.insert(Path.end(), P.begin(), P.end());
820 }
821
822 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
823 /// whether the member is a member of some class derived from the class type
824 /// of the member pointer.
825 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
826 /// Path - The path of base/derived classes from the member declaration's
827 /// class (exclusive) to the class type of the member pointer (inclusive).
828 SmallVector<const CXXRecordDecl*, 4> Path;
829
830 /// Perform a cast towards the class of the Decl (either up or down the
831 /// hierarchy).
832 bool castBack(const CXXRecordDecl *Class) {
833 assert(!Path.empty());
834 const CXXRecordDecl *Expected;
835 if (Path.size() >= 2)
836 Expected = Path[Path.size() - 2];
837 else
838 Expected = getContainingRecord();
839 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
840 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
841 // if B does not contain the original member and is not a base or
842 // derived class of the class containing the original member, the result
843 // of the cast is undefined.
844 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
845 // (D::*). We consider that to be a language defect.
846 return false;
847 }
848 Path.pop_back();
849 return true;
850 }
851 /// Perform a base-to-derived member pointer cast.
852 bool castToDerived(const CXXRecordDecl *Derived) {
853 if (!getDecl())
854 return true;
855 if (!isDerivedMember()) {
856 Path.push_back(Derived);
857 return true;
858 }
859 if (!castBack(Derived))
860 return false;
861 if (Path.empty())
862 DeclAndIsDerivedMember.setInt(false);
863 return true;
864 }
865 /// Perform a derived-to-base member pointer cast.
866 bool castToBase(const CXXRecordDecl *Base) {
867 if (!getDecl())
868 return true;
869 if (Path.empty())
870 DeclAndIsDerivedMember.setInt(true);
871 if (isDerivedMember()) {
872 Path.push_back(Base);
873 return true;
874 }
875 return castBack(Base);
876 }
877 };
Richard Smith357362d2011-12-13 06:39:58 +0000878
Richard Smith7bb00672012-02-01 01:42:44 +0000879 /// Compare two member pointers, which are assumed to be of the same type.
880 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
881 if (!LHS.getDecl() || !RHS.getDecl())
882 return !LHS.getDecl() && !RHS.getDecl();
883 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
884 return false;
885 return LHS.Path == RHS.Path;
886 }
887
Richard Smith357362d2011-12-13 06:39:58 +0000888 /// Kinds of constant expression checking, for diagnostics.
889 enum CheckConstantExpressionKind {
890 CCEK_Constant, ///< A normal constant.
891 CCEK_ReturnValue, ///< A constexpr function return value.
892 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
893 };
John McCall93d91dc2010-05-07 17:22:02 +0000894}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000895
Richard Smith2e312c82012-03-03 22:46:17 +0000896static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +0000897static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
898 const LValue &This, const Expr *E,
899 CheckConstantExpressionKind CCEK = CCEK_Constant,
900 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +0000901static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
902static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +0000903static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
904 EvalInfo &Info);
905static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000906static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +0000907static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000908 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000909static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000910static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000911
912//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000913// Misc utilities
914//===----------------------------------------------------------------------===//
915
Richard Smithd9f663b2013-04-22 15:31:51 +0000916/// Evaluate an expression to see if it had side-effects, and discard its
917/// result.
918static void EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
919 APValue Scratch;
920 if (!Evaluate(Scratch, Info, E))
921 Info.EvalStatus.HasSideEffects = true;
922}
923
Richard Smithd62306a2011-11-10 06:34:14 +0000924/// Should this call expression be treated as a string literal?
925static bool IsStringLiteralCall(const CallExpr *E) {
926 unsigned Builtin = E->isBuiltinCall();
927 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
928 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
929}
930
Richard Smithce40ad62011-11-12 22:28:03 +0000931static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +0000932 // C++11 [expr.const]p3 An address constant expression is a prvalue core
933 // constant expression of pointer type that evaluates to...
934
935 // ... a null pointer value, or a prvalue core constant expression of type
936 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +0000937 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +0000938
Richard Smithce40ad62011-11-12 22:28:03 +0000939 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
940 // ... the address of an object with static storage duration,
941 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
942 return VD->hasGlobalStorage();
943 // ... the address of a function,
944 return isa<FunctionDecl>(D);
945 }
946
947 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +0000948 switch (E->getStmtClass()) {
949 default:
950 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +0000951 case Expr::CompoundLiteralExprClass: {
952 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
953 return CLE->isFileScope() && CLE->isLValue();
954 }
Richard Smithd62306a2011-11-10 06:34:14 +0000955 // A string literal has static storage duration.
956 case Expr::StringLiteralClass:
957 case Expr::PredefinedExprClass:
958 case Expr::ObjCStringLiteralClass:
959 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +0000960 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +0000961 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +0000962 return true;
963 case Expr::CallExprClass:
964 return IsStringLiteralCall(cast<CallExpr>(E));
965 // For GCC compatibility, &&label has static storage duration.
966 case Expr::AddrLabelExprClass:
967 return true;
968 // A Block literal expression may be used as the initialization value for
969 // Block variables at global or local static scope.
970 case Expr::BlockExprClass:
971 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +0000972 case Expr::ImplicitValueInitExprClass:
973 // FIXME:
974 // We can never form an lvalue with an implicit value initialization as its
975 // base through expression evaluation, so these only appear in one case: the
976 // implicit variable declaration we invent when checking whether a constexpr
977 // constructor can produce a constant expression. We must assume that such
978 // an expression might be a global lvalue.
979 return true;
Richard Smithd62306a2011-11-10 06:34:14 +0000980 }
John McCall95007602010-05-10 23:27:23 +0000981}
982
Richard Smithb228a862012-02-15 02:18:13 +0000983static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
984 assert(Base && "no location for a null lvalue");
985 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
986 if (VD)
987 Info.Note(VD->getLocation(), diag::note_declared_at);
988 else
Ted Kremenek28831752012-08-23 20:46:57 +0000989 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +0000990 diag::note_constexpr_temporary_here);
991}
992
Richard Smith80815602011-11-07 05:07:52 +0000993/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +0000994/// value for an address or reference constant expression. Return true if we
995/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +0000996static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
997 QualType Type, const LValue &LVal) {
998 bool IsReferenceType = Type->isReferenceType();
999
Richard Smith357362d2011-12-13 06:39:58 +00001000 APValue::LValueBase Base = LVal.getLValueBase();
1001 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1002
Richard Smith0dea49e2012-02-18 04:58:18 +00001003 // Check that the object is a global. Note that the fake 'this' object we
1004 // manufacture when checking potential constant expressions is conservatively
1005 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001006 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001007 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001008 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001009 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1010 << IsReferenceType << !Designator.Entries.empty()
1011 << !!VD << VD;
1012 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001013 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001014 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001015 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001016 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001017 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001018 }
Richard Smithb228a862012-02-15 02:18:13 +00001019 assert((Info.CheckingPotentialConstantExpression ||
1020 LVal.getLValueCallIndex() == 0) &&
1021 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001022
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001023 // Check if this is a thread-local variable.
1024 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1025 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
Richard Smithfd3834f2013-04-13 02:43:54 +00001026 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001027 return false;
1028 }
1029 }
1030
Richard Smitha8105bc2012-01-06 16:39:00 +00001031 // Allow address constant expressions to be past-the-end pointers. This is
1032 // an extension: the standard requires them to point to an object.
1033 if (!IsReferenceType)
1034 return true;
1035
1036 // A reference constant expression must refer to an object.
1037 if (!Base) {
1038 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001039 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001040 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001041 }
1042
Richard Smith357362d2011-12-13 06:39:58 +00001043 // Does this refer one past the end of some object?
Richard Smitha8105bc2012-01-06 16:39:00 +00001044 if (Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001045 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001046 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001047 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001048 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001049 }
1050
Richard Smith80815602011-11-07 05:07:52 +00001051 return true;
1052}
1053
Richard Smithfddd3842011-12-30 21:15:51 +00001054/// Check that this core constant expression is of literal type, and if not,
1055/// produce an appropriate diagnostic.
1056static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001057 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001058 return true;
1059
1060 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001061 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001062 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001063 << E->getType();
1064 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001065 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001066 return false;
1067}
1068
Richard Smith0b0a0b62011-10-29 20:57:55 +00001069/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001070/// constant expression. If not, report an appropriate diagnostic. Does not
1071/// check that the expression is of literal type.
1072static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1073 QualType Type, const APValue &Value) {
1074 // Core issue 1454: For a literal constant expression of array or class type,
1075 // each subobject of its value shall have been initialized by a constant
1076 // expression.
1077 if (Value.isArray()) {
1078 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1079 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1080 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1081 Value.getArrayInitializedElt(I)))
1082 return false;
1083 }
1084 if (!Value.hasArrayFiller())
1085 return true;
1086 return CheckConstantExpression(Info, DiagLoc, EltTy,
1087 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001088 }
Richard Smithb228a862012-02-15 02:18:13 +00001089 if (Value.isUnion() && Value.getUnionField()) {
1090 return CheckConstantExpression(Info, DiagLoc,
1091 Value.getUnionField()->getType(),
1092 Value.getUnionValue());
1093 }
1094 if (Value.isStruct()) {
1095 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1096 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1097 unsigned BaseIndex = 0;
1098 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1099 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1100 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1101 Value.getStructBase(BaseIndex)))
1102 return false;
1103 }
1104 }
1105 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1106 I != E; ++I) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001107 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1108 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001109 return false;
1110 }
1111 }
1112
1113 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001114 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001115 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001116 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1117 }
1118
1119 // Everything else is fine.
1120 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001121}
1122
Richard Smith83c68212011-10-31 05:11:32 +00001123const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001124 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001125}
1126
1127static bool IsLiteralLValue(const LValue &Value) {
Richard Smithb228a862012-02-15 02:18:13 +00001128 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith83c68212011-10-31 05:11:32 +00001129}
1130
Richard Smithcecf1842011-11-01 21:06:14 +00001131static bool IsWeakLValue(const LValue &Value) {
1132 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001133 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001134}
1135
Richard Smith2e312c82012-03-03 22:46:17 +00001136static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001137 // A null base expression indicates a null pointer. These are always
1138 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001139 if (!Value.getLValueBase()) {
1140 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001141 return true;
1142 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001143
Richard Smith027bf112011-11-17 22:56:20 +00001144 // We have a non-null base. These are generally known to be true, but if it's
1145 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001146 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001147 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001148 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001149}
1150
Richard Smith2e312c82012-03-03 22:46:17 +00001151static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001152 switch (Val.getKind()) {
1153 case APValue::Uninitialized:
1154 return false;
1155 case APValue::Int:
1156 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001157 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001158 case APValue::Float:
1159 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001160 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001161 case APValue::ComplexInt:
1162 Result = Val.getComplexIntReal().getBoolValue() ||
1163 Val.getComplexIntImag().getBoolValue();
1164 return true;
1165 case APValue::ComplexFloat:
1166 Result = !Val.getComplexFloatReal().isZero() ||
1167 !Val.getComplexFloatImag().isZero();
1168 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001169 case APValue::LValue:
1170 return EvalPointerValueAsBool(Val, Result);
1171 case APValue::MemberPointer:
1172 Result = Val.getMemberPointerDecl();
1173 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001174 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001175 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001176 case APValue::Struct:
1177 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001178 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001179 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001180 }
1181
Richard Smith11562c52011-10-28 17:51:58 +00001182 llvm_unreachable("unknown APValue kind");
1183}
1184
1185static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1186 EvalInfo &Info) {
1187 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001188 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001189 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001190 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001191 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001192}
1193
Richard Smith357362d2011-12-13 06:39:58 +00001194template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001195static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001196 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001197 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001198 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001199}
1200
1201static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1202 QualType SrcType, const APFloat &Value,
1203 QualType DestType, APSInt &Result) {
1204 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001205 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001206 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001207
Richard Smith357362d2011-12-13 06:39:58 +00001208 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001209 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001210 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1211 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001212 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001213 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001214}
1215
Richard Smith357362d2011-12-13 06:39:58 +00001216static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1217 QualType SrcType, QualType DestType,
1218 APFloat &Result) {
1219 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001220 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001221 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1222 APFloat::rmNearestTiesToEven, &ignored)
1223 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001224 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001225 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001226}
1227
Richard Smith911e1422012-01-30 22:27:01 +00001228static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1229 QualType DestType, QualType SrcType,
1230 APSInt &Value) {
1231 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001232 APSInt Result = Value;
1233 // Figure out if this is a truncate, extend or noop cast.
1234 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001235 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001236 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001237 return Result;
1238}
1239
Richard Smith357362d2011-12-13 06:39:58 +00001240static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1241 QualType SrcType, const APSInt &Value,
1242 QualType DestType, APFloat &Result) {
1243 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1244 if (Result.convertFromAPInt(Value, Value.isSigned(),
1245 APFloat::rmNearestTiesToEven)
1246 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001247 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001248 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001249}
1250
Eli Friedman803acb32011-12-22 03:51:45 +00001251static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1252 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001253 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001254 if (!Evaluate(SVal, Info, E))
1255 return false;
1256 if (SVal.isInt()) {
1257 Res = SVal.getInt();
1258 return true;
1259 }
1260 if (SVal.isFloat()) {
1261 Res = SVal.getFloat().bitcastToAPInt();
1262 return true;
1263 }
1264 if (SVal.isVector()) {
1265 QualType VecTy = E->getType();
1266 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1267 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1268 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1269 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1270 Res = llvm::APInt::getNullValue(VecSize);
1271 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1272 APValue &Elt = SVal.getVectorElt(i);
1273 llvm::APInt EltAsInt;
1274 if (Elt.isInt()) {
1275 EltAsInt = Elt.getInt();
1276 } else if (Elt.isFloat()) {
1277 EltAsInt = Elt.getFloat().bitcastToAPInt();
1278 } else {
1279 // Don't try to handle vectors of anything other than int or float
1280 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001281 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001282 return false;
1283 }
1284 unsigned BaseEltSize = EltAsInt.getBitWidth();
1285 if (BigEndian)
1286 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1287 else
1288 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1289 }
1290 return true;
1291 }
1292 // Give up if the input isn't an int, float, or vector. For example, we
1293 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001294 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001295 return false;
1296}
1297
Richard Smitha8105bc2012-01-06 16:39:00 +00001298/// Cast an lvalue referring to a base subobject to a derived class, by
1299/// truncating the lvalue's path to the given length.
1300static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1301 const RecordDecl *TruncatedType,
1302 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001303 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001304
1305 // Check we actually point to a derived class object.
1306 if (TruncatedElements == D.Entries.size())
1307 return true;
1308 assert(TruncatedElements >= D.MostDerivedPathLength &&
1309 "not casting to a derived class");
1310 if (!Result.checkSubobject(Info, E, CSK_Derived))
1311 return false;
1312
1313 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001314 const RecordDecl *RD = TruncatedType;
1315 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001316 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001317 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1318 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001319 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001320 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001321 else
Richard Smithd62306a2011-11-10 06:34:14 +00001322 Result.Offset -= Layout.getBaseClassOffset(Base);
1323 RD = Base;
1324 }
Richard Smith027bf112011-11-17 22:56:20 +00001325 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001326 return true;
1327}
1328
John McCalld7bca762012-05-01 00:38:49 +00001329static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001330 const CXXRecordDecl *Derived,
1331 const CXXRecordDecl *Base,
1332 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001333 if (!RL) {
1334 if (Derived->isInvalidDecl()) return false;
1335 RL = &Info.Ctx.getASTRecordLayout(Derived);
1336 }
1337
Richard Smithd62306a2011-11-10 06:34:14 +00001338 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001339 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001340 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001341}
1342
Richard Smitha8105bc2012-01-06 16:39:00 +00001343static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001344 const CXXRecordDecl *DerivedDecl,
1345 const CXXBaseSpecifier *Base) {
1346 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1347
John McCalld7bca762012-05-01 00:38:49 +00001348 if (!Base->isVirtual())
1349 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001350
Richard Smitha8105bc2012-01-06 16:39:00 +00001351 SubobjectDesignator &D = Obj.Designator;
1352 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001353 return false;
1354
Richard Smitha8105bc2012-01-06 16:39:00 +00001355 // Extract most-derived object and corresponding type.
1356 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1357 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1358 return false;
1359
1360 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001361 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001362 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1363 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001364 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001365 return true;
1366}
1367
1368/// Update LVal to refer to the given field, which must be a member of the type
1369/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001370static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001371 const FieldDecl *FD,
1372 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001373 if (!RL) {
1374 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001375 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001376 }
Richard Smithd62306a2011-11-10 06:34:14 +00001377
1378 unsigned I = FD->getFieldIndex();
1379 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001380 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001381 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001382}
1383
Richard Smith1b78b3d2012-01-25 22:15:11 +00001384/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001385static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001386 LValue &LVal,
1387 const IndirectFieldDecl *IFD) {
1388 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1389 CE = IFD->chain_end(); C != CE; ++C)
John McCalld7bca762012-05-01 00:38:49 +00001390 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1391 return false;
1392 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001393}
1394
Richard Smithd62306a2011-11-10 06:34:14 +00001395/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001396static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1397 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001398 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1399 // extension.
1400 if (Type->isVoidType() || Type->isFunctionType()) {
1401 Size = CharUnits::One();
1402 return true;
1403 }
1404
1405 if (!Type->isConstantSizeType()) {
1406 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001407 // FIXME: Better diagnostic.
1408 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001409 return false;
1410 }
1411
1412 Size = Info.Ctx.getTypeSizeInChars(Type);
1413 return true;
1414}
1415
1416/// Update a pointer value to model pointer arithmetic.
1417/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001418/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001419/// \param LVal - The pointer value to be updated.
1420/// \param EltTy - The pointee type represented by LVal.
1421/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001422static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1423 LValue &LVal, QualType EltTy,
1424 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001425 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001426 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001427 return false;
1428
1429 // Compute the new offset in the appropriate width.
1430 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001431 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001432 return true;
1433}
1434
Richard Smith66c96992012-02-18 22:04:06 +00001435/// Update an lvalue to refer to a component of a complex number.
1436/// \param Info - Information about the ongoing evaluation.
1437/// \param LVal - The lvalue to be updated.
1438/// \param EltTy - The complex number's component type.
1439/// \param Imag - False for the real component, true for the imaginary.
1440static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1441 LValue &LVal, QualType EltTy,
1442 bool Imag) {
1443 if (Imag) {
1444 CharUnits SizeOfComponent;
1445 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1446 return false;
1447 LVal.Offset += SizeOfComponent;
1448 }
1449 LVal.addComplex(Info, E, EltTy, Imag);
1450 return true;
1451}
1452
Richard Smith27908702011-10-24 17:54:18 +00001453/// Try to evaluate the initializer for a variable declaration.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001454static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1455 const VarDecl *VD,
Richard Smith2e312c82012-03-03 22:46:17 +00001456 CallStackFrame *Frame, APValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001457 // If this is a parameter to an active constexpr function call, perform
1458 // argument substitution.
1459 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001460 // Assume arguments of a potential constant expression are unknown
1461 // constant expressions.
1462 if (Info.CheckingPotentialConstantExpression)
1463 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001464 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001465 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001466 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001467 }
Richard Smithfec09922011-11-01 16:57:24 +00001468 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1469 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001470 }
Richard Smith27908702011-10-24 17:54:18 +00001471
Richard Smithd9f663b2013-04-22 15:31:51 +00001472 // If this is a local variable, dig out its value.
1473 if (VD->hasLocalStorage() && Frame && Frame->Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001474 // In C++1y, we can't safely read anything which might have been mutated
1475 // when checking a potential constant expression.
1476 if (Info.getLangOpts().CPlusPlus1y &&
1477 Info.CheckingPotentialConstantExpression)
1478 return false;
1479
Richard Smithd9f663b2013-04-22 15:31:51 +00001480 Result = Frame->Temporaries[VD];
1481 // If we've carried on past an unevaluatable local variable initializer,
1482 // we can't go any further. This can happen during potential constant
1483 // expression checking.
1484 return !Result.isUninit();
1485 }
1486
Richard Smithd0b4dd62011-12-19 06:19:21 +00001487 // Dig out the initializer, and use the declaration which it's attached to.
1488 const Expr *Init = VD->getAnyInitializer(VD);
1489 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001490 // If we're checking a potential constant expression, the variable could be
1491 // initialized later.
1492 if (!Info.CheckingPotentialConstantExpression)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001493 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001494 return false;
1495 }
1496
Richard Smithd62306a2011-11-10 06:34:14 +00001497 // If we're currently evaluating the initializer of this declaration, use that
1498 // in-flight value.
1499 if (Info.EvaluatingDecl == VD) {
Richard Smith2e312c82012-03-03 22:46:17 +00001500 Result = *Info.EvaluatingDeclValue;
Richard Smithd62306a2011-11-10 06:34:14 +00001501 return !Result.isUninit();
1502 }
1503
Richard Smithcecf1842011-11-01 21:06:14 +00001504 // Never evaluate the initializer of a weak variable. We can't be sure that
1505 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001506 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001507 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001508 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001509 }
Richard Smithcecf1842011-11-01 21:06:14 +00001510
Richard Smithd0b4dd62011-12-19 06:19:21 +00001511 // Check that we can fold the initializer. In C++, we will have already done
1512 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001513 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001514 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001515 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001516 Notes.size() + 1) << VD;
1517 Info.Note(VD->getLocation(), diag::note_declared_at);
1518 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001519 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001520 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001521 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001522 Notes.size() + 1) << VD;
1523 Info.Note(VD->getLocation(), diag::note_declared_at);
1524 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001525 }
Richard Smith27908702011-10-24 17:54:18 +00001526
Richard Smith2e312c82012-03-03 22:46:17 +00001527 Result = *VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001528 return true;
Richard Smith27908702011-10-24 17:54:18 +00001529}
1530
Richard Smith11562c52011-10-28 17:51:58 +00001531static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001532 Qualifiers Quals = T.getQualifiers();
1533 return Quals.hasConst() && !Quals.hasVolatile();
1534}
1535
Richard Smithe97cbd72011-11-11 04:05:33 +00001536/// Get the base index of the given base class within an APValue representing
1537/// the given derived class.
1538static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1539 const CXXRecordDecl *Base) {
1540 Base = Base->getCanonicalDecl();
1541 unsigned Index = 0;
1542 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1543 E = Derived->bases_end(); I != E; ++I, ++Index) {
1544 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1545 return Index;
1546 }
1547
1548 llvm_unreachable("base class missing from derived class's bases list");
1549}
1550
Richard Smith3da88fa2013-04-26 14:36:30 +00001551/// Extract the value of a character from a string literal.
1552static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1553 uint64_t Index) {
Richard Smith14a94132012-02-17 03:35:37 +00001554 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith3da88fa2013-04-26 14:36:30 +00001555 const StringLiteral *S = cast<StringLiteral>(Lit);
1556 const ConstantArrayType *CAT =
1557 Info.Ctx.getAsConstantArrayType(S->getType());
1558 assert(CAT && "string literal isn't an array");
1559 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00001560 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00001561
1562 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00001563 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00001564 if (Index < S->getLength())
1565 Value = S->getCodeUnit(Index);
1566 return Value;
1567}
1568
Richard Smith3da88fa2013-04-26 14:36:30 +00001569// Expand a string literal into an array of characters.
1570static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
1571 APValue &Result) {
1572 const StringLiteral *S = cast<StringLiteral>(Lit);
1573 const ConstantArrayType *CAT =
1574 Info.Ctx.getAsConstantArrayType(S->getType());
1575 assert(CAT && "string literal isn't an array");
1576 QualType CharType = CAT->getElementType();
1577 assert(CharType->isIntegerType() && "unexpected character type");
1578
1579 unsigned Elts = CAT->getSize().getZExtValue();
1580 Result = APValue(APValue::UninitArray(),
1581 std::min(S->getLength(), Elts), Elts);
1582 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1583 CharType->isUnsignedIntegerType());
1584 if (Result.hasArrayFiller())
1585 Result.getArrayFiller() = APValue(Value);
1586 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
1587 Value = S->getCodeUnit(I);
1588 Result.getArrayInitializedElt(I) = APValue(Value);
1589 }
1590}
1591
1592// Expand an array so that it has more than Index filled elements.
1593static void expandArray(APValue &Array, unsigned Index) {
1594 unsigned Size = Array.getArraySize();
1595 assert(Index < Size);
1596
1597 // Always at least double the number of elements for which we store a value.
1598 unsigned OldElts = Array.getArrayInitializedElts();
1599 unsigned NewElts = std::max(Index+1, OldElts * 2);
1600 NewElts = std::min(Size, std::max(NewElts, 8u));
1601
1602 // Copy the data across.
1603 APValue NewValue(APValue::UninitArray(), NewElts, Size);
1604 for (unsigned I = 0; I != OldElts; ++I)
1605 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
1606 for (unsigned I = OldElts; I != NewElts; ++I)
1607 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
1608 if (NewValue.hasArrayFiller())
1609 NewValue.getArrayFiller() = Array.getArrayFiller();
1610 Array.swap(NewValue);
1611}
1612
1613/// Kinds of access we can perform on an object.
1614enum AccessKinds {
1615 AK_Read,
1616 AK_Assign
1617};
1618
1619/// Find the designated sub-object of an rvalue.
1620template<typename SubobjectHandler>
1621typename SubobjectHandler::result_type
1622findSubobject(EvalInfo &Info, const Expr *E, APValue &Obj, QualType ObjType,
1623 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001624 if (Sub.Invalid)
1625 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00001626 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00001627 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001628 if (Info.getLangOpts().CPlusPlus11)
1629 Info.Diag(E, diag::note_constexpr_access_past_end)
1630 << handler.AccessKind;
1631 else
1632 Info.Diag(E);
1633 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001634 }
Richard Smith6804be52011-11-11 08:28:03 +00001635 if (Sub.Entries.empty())
Richard Smith3da88fa2013-04-26 14:36:30 +00001636 return handler.found(Obj, ObjType);
Richard Smith253c2a32012-01-27 01:14:48 +00001637 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1638 // This object might be initialized later.
Richard Smith3da88fa2013-04-26 14:36:30 +00001639 return handler.failed();
Richard Smithf3e9e432011-11-07 09:22:26 +00001640
Richard Smith4e9e5232012-03-10 00:28:11 +00001641 APValue *O = &Obj;
Richard Smithd62306a2011-11-10 06:34:14 +00001642 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001643 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001644 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001645 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001646 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001647 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001648 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001649 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001650 // Note, it should not be possible to form a pointer with a valid
1651 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00001652 if (Info.getLangOpts().CPlusPlus11)
1653 Info.Diag(E, diag::note_constexpr_access_past_end)
1654 << handler.AccessKind;
1655 else
1656 Info.Diag(E);
1657 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001658 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001659
1660 ObjType = CAT->getElementType();
1661
Richard Smith14a94132012-02-17 03:35:37 +00001662 // An array object is represented as either an Array APValue or as an
1663 // LValue which refers to a string literal.
1664 if (O->isLValue()) {
1665 assert(I == N - 1 && "extracting subobject of character?");
1666 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00001667 if (handler.AccessKind != AK_Read)
1668 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
1669 *O);
1670 else
1671 return handler.foundString(*O, ObjType, Index);
1672 }
1673
1674 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00001675 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00001676 else if (handler.AccessKind != AK_Read) {
1677 expandArray(*O, Index);
1678 O = &O->getArrayInitializedElt(Index);
1679 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00001680 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00001681 } else if (ObjType->isAnyComplexType()) {
1682 // Next subobject is a complex number.
1683 uint64_t Index = Sub.Entries[I].ArrayIndex;
1684 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001685 if (Info.getLangOpts().CPlusPlus11)
1686 Info.Diag(E, diag::note_constexpr_access_past_end)
1687 << handler.AccessKind;
1688 else
1689 Info.Diag(E);
1690 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00001691 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001692
1693 bool WasConstQualified = ObjType.isConstQualified();
1694 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1695 if (WasConstQualified)
1696 ObjType.addConst();
1697
Richard Smith66c96992012-02-18 22:04:06 +00001698 assert(I == N - 1 && "extracting subobject of scalar?");
1699 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001700 return handler.found(Index ? O->getComplexIntImag()
1701 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001702 } else {
1703 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00001704 return handler.found(Index ? O->getComplexFloatImag()
1705 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001706 }
Richard Smithd62306a2011-11-10 06:34:14 +00001707 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001708 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001709 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00001710 << Field;
1711 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00001712 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00001713 }
1714
Richard Smithd62306a2011-11-10 06:34:14 +00001715 // Next subobject is a class, struct or union field.
1716 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1717 if (RD->isUnion()) {
1718 const FieldDecl *UnionField = O->getUnionField();
1719 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001720 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001721 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
1722 << handler.AccessKind << Field << !UnionField << UnionField;
1723 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001724 }
Richard Smithd62306a2011-11-10 06:34:14 +00001725 O = &O->getUnionValue();
1726 } else
1727 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00001728
1729 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00001730 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00001731 if (WasConstQualified && !Field->isMutable())
1732 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00001733
1734 if (ObjType.isVolatileQualified()) {
1735 if (Info.getLangOpts().CPlusPlus) {
1736 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00001737 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
1738 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00001739 Info.Note(Field->getLocation(), diag::note_declared_at);
1740 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001741 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001742 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001743 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001744 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001745 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001746 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001747 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1748 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1749 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00001750
1751 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00001752 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00001753 if (WasConstQualified)
1754 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00001755 }
Richard Smithd62306a2011-11-10 06:34:14 +00001756
Richard Smithf57d8cb2011-12-09 22:58:01 +00001757 if (O->isUninit()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001758 if (!Info.CheckingPotentialConstantExpression)
Richard Smith3da88fa2013-04-26 14:36:30 +00001759 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
1760 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001761 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001762 }
1763
Richard Smith3da88fa2013-04-26 14:36:30 +00001764 return handler.found(*O, ObjType);
1765}
1766
1767struct ExtractSubobjectHandler {
1768 EvalInfo &Info;
1769 APValue &Obj;
1770
1771 static const AccessKinds AccessKind = AK_Read;
1772
1773 typedef bool result_type;
1774 bool failed() { return false; }
1775 bool found(APValue &Subobj, QualType SubobjType) {
1776 if (&Subobj != &Obj) {
1777 // We can't just swap Obj and Subobj here, because we'd create an object
1778 // that has itself as a subobject. To avoid the leak, we ensure that Tmp
1779 // ends up owning the original complete object, which is destroyed by
1780 // Tmp's destructor.
1781 APValue Tmp;
1782 Subobj.swap(Tmp);
1783 Obj.swap(Tmp);
1784 }
1785 return true;
1786 }
1787 bool found(APSInt &Value, QualType SubobjType) {
1788 Obj = APValue(Value);
1789 return true;
1790 }
1791 bool found(APFloat &Value, QualType SubobjType) {
1792 Obj = APValue(Value);
1793 return true;
1794 }
1795 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
1796 Obj = APValue(extractStringLiteralCharacter(
1797 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
1798 return true;
1799 }
1800};
1801const AccessKinds ExtractSubobjectHandler::AccessKind;
1802
1803/// Extract the designated sub-object of an rvalue.
1804static bool extractSubobject(EvalInfo &Info, const Expr *E,
1805 APValue &Obj, QualType ObjType,
1806 const SubobjectDesignator &Sub) {
1807 ExtractSubobjectHandler Handler = { Info, Obj };
1808 return findSubobject(Info, E, Obj, ObjType, Sub, Handler);
1809}
1810
1811struct ModifySubobjectHandler {
1812 EvalInfo &Info;
1813 APValue &NewVal;
1814 const Expr *E;
1815
1816 typedef bool result_type;
1817 static const AccessKinds AccessKind = AK_Assign;
1818
1819 bool checkConst(QualType QT) {
1820 // Assigning to a const object has undefined behavior.
1821 if (QT.isConstQualified()) {
1822 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
1823 return false;
1824 }
1825 return true;
1826 }
1827
1828 bool failed() { return false; }
1829 bool found(APValue &Subobj, QualType SubobjType) {
1830 if (!checkConst(SubobjType))
1831 return false;
1832 // We've been given ownership of NewVal, so just swap it in.
1833 Subobj.swap(NewVal);
1834 return true;
1835 }
1836 bool found(APSInt &Value, QualType SubobjType) {
1837 if (!checkConst(SubobjType))
1838 return false;
1839 if (!NewVal.isInt()) {
1840 // Maybe trying to write a cast pointer value into a complex?
1841 Info.Diag(E);
1842 return false;
1843 }
1844 Value = NewVal.getInt();
1845 return true;
1846 }
1847 bool found(APFloat &Value, QualType SubobjType) {
1848 if (!checkConst(SubobjType))
1849 return false;
1850 Value = NewVal.getFloat();
1851 return true;
1852 }
1853 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
1854 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
1855 }
1856};
1857const AccessKinds ModifySubobjectHandler::AccessKind;
1858
1859/// Update the designated sub-object of an rvalue to the given value.
1860static bool modifySubobject(EvalInfo &Info, const Expr *E,
1861 APValue &Obj, QualType ObjType,
1862 const SubobjectDesignator &Sub,
1863 APValue &NewVal) {
1864 ModifySubobjectHandler Handler = { Info, NewVal, E };
1865 return findSubobject(Info, E, Obj, ObjType, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00001866}
1867
Richard Smith84f6dcf2012-02-02 01:16:57 +00001868/// Find the position where two subobject designators diverge, or equivalently
1869/// the length of the common initial subsequence.
1870static unsigned FindDesignatorMismatch(QualType ObjType,
1871 const SubobjectDesignator &A,
1872 const SubobjectDesignator &B,
1873 bool &WasArrayIndex) {
1874 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1875 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00001876 if (!ObjType.isNull() &&
1877 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00001878 // Next subobject is an array element.
1879 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1880 WasArrayIndex = true;
1881 return I;
1882 }
Richard Smith66c96992012-02-18 22:04:06 +00001883 if (ObjType->isAnyComplexType())
1884 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1885 else
1886 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00001887 } else {
1888 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1889 WasArrayIndex = false;
1890 return I;
1891 }
1892 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1893 // Next subobject is a field.
1894 ObjType = FD->getType();
1895 else
1896 // Next subobject is a base class.
1897 ObjType = QualType();
1898 }
1899 }
1900 WasArrayIndex = false;
1901 return I;
1902}
1903
1904/// Determine whether the given subobject designators refer to elements of the
1905/// same array object.
1906static bool AreElementsOfSameArray(QualType ObjType,
1907 const SubobjectDesignator &A,
1908 const SubobjectDesignator &B) {
1909 if (A.Entries.size() != B.Entries.size())
1910 return false;
1911
1912 bool IsArray = A.MostDerivedArraySize != 0;
1913 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1914 // A is a subobject of the array element.
1915 return false;
1916
1917 // If A (and B) designates an array element, the last entry will be the array
1918 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1919 // of length 1' case, and the entire path must match.
1920 bool WasArrayIndex;
1921 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1922 return CommonLength >= A.Entries.size() - IsArray;
1923}
1924
Richard Smithd62306a2011-11-10 06:34:14 +00001925/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
Richard Smith3da88fa2013-04-26 14:36:30 +00001926/// the given glvalue. This can also be used for 'lvalue-to-lvalue' conversions
Richard Smithd62306a2011-11-10 06:34:14 +00001927/// for looking up the glvalue referred to by an entity of reference type.
1928///
1929/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001930/// \param Conv - The expression for which we are performing the conversion.
1931/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00001932/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
1933/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00001934/// \param LVal - The glvalue on which we are attempting to perform this action.
1935/// \param RVal - The produced value will be placed here.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001936static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1937 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00001938 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001939 if (LVal.Designator.Invalid)
1940 // A diagnostic will have already been produced.
1941 return false;
1942
Richard Smithce40ad62011-11-12 22:28:03 +00001943 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith11562c52011-10-28 17:51:58 +00001944
Richard Smithf57d8cb2011-12-09 22:58:01 +00001945 if (!LVal.Base) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001946 Info.Diag(Conv, diag::note_constexpr_access_null) << AK_Read;
Richard Smithf2b681b2011-12-21 05:04:46 +00001947 return false;
1948 }
1949
Richard Smithb228a862012-02-15 02:18:13 +00001950 CallStackFrame *Frame = 0;
1951 if (LVal.CallIndex) {
1952 Frame = Info.getCallFrame(LVal.CallIndex);
1953 if (!Frame) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001954 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1)
1955 << AK_Read << !Base;
Richard Smithb228a862012-02-15 02:18:13 +00001956 NoteLValueLocation(Info, LVal.Base);
1957 return false;
1958 }
1959 }
1960
Richard Smithf2b681b2011-12-21 05:04:46 +00001961 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1962 // is not a constant expression (even if the object is non-volatile). We also
1963 // apply this rule to C++98, in order to conform to the expected 'volatile'
1964 // semantics.
1965 if (Type.isVolatileQualified()) {
1966 if (Info.getLangOpts().CPlusPlus)
Richard Smith3da88fa2013-04-26 14:36:30 +00001967 Info.Diag(Conv, diag::note_constexpr_access_volatile_type)
1968 << AK_Read << Type;
Richard Smithf2b681b2011-12-21 05:04:46 +00001969 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001970 Info.Diag(Conv);
Richard Smith11562c52011-10-28 17:51:58 +00001971 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001972 }
Richard Smith11562c52011-10-28 17:51:58 +00001973
Richard Smithce40ad62011-11-12 22:28:03 +00001974 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smith11562c52011-10-28 17:51:58 +00001975 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1976 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +00001977 // expressions are constant expressions too. Inside constexpr functions,
1978 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +00001979 // In C, such things can also be folded, although they are not ICEs.
Richard Smith11562c52011-10-28 17:51:58 +00001980 const VarDecl *VD = dyn_cast<VarDecl>(D);
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001981 if (VD) {
1982 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
1983 VD = VDef;
1984 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00001985 if (!VD || VD->isInvalidDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001986 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00001987 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001988 }
1989
Richard Smithf2b681b2011-12-21 05:04:46 +00001990 // DR1313: If the object is volatile-qualified but the glvalue was not,
1991 // behavior is undefined so the result is not a constant expression.
Richard Smithce40ad62011-11-12 22:28:03 +00001992 QualType VT = VD->getType();
Richard Smithf2b681b2011-12-21 05:04:46 +00001993 if (VT.isVolatileQualified()) {
1994 if (Info.getLangOpts().CPlusPlus) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001995 Info.Diag(Conv, diag::note_constexpr_access_volatile_obj, 1)
1996 << AK_Read << 1 << VD;
Richard Smithf2b681b2011-12-21 05:04:46 +00001997 Info.Note(VD->getLocation(), diag::note_declared_at);
1998 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001999 Info.Diag(Conv);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002000 }
Richard Smithf2b681b2011-12-21 05:04:46 +00002001 return false;
2002 }
2003
Richard Smithd9f663b2013-04-22 15:31:51 +00002004 // Unless we're looking at a local variable or argument in a constexpr call,
2005 // the variable we're reading must be const.
2006 if (LVal.CallIndex <= 1 || !VD->hasLocalStorage()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002007 if (VD->isConstexpr()) {
2008 // OK, we can read this variable.
2009 } else if (VT->isIntegralOrEnumerationType()) {
2010 if (!VT.isConstQualified()) {
2011 if (Info.getLangOpts().CPlusPlus) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002012 Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smithf2b681b2011-12-21 05:04:46 +00002013 Info.Note(VD->getLocation(), diag::note_declared_at);
2014 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002015 Info.Diag(Conv);
Richard Smithf2b681b2011-12-21 05:04:46 +00002016 }
2017 return false;
2018 }
2019 } else if (VT->isFloatingType() && VT.isConstQualified()) {
2020 // We support folding of const floating-point types, in order to make
2021 // static const data members of such types (supported as an extension)
2022 // more useful.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002023 if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002024 Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smithf2b681b2011-12-21 05:04:46 +00002025 Info.Note(VD->getLocation(), diag::note_declared_at);
2026 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002027 Info.CCEDiag(Conv);
Richard Smithf2b681b2011-12-21 05:04:46 +00002028 }
2029 } else {
2030 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002031 if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002032 Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smithf2b681b2011-12-21 05:04:46 +00002033 Info.Note(VD->getLocation(), diag::note_declared_at);
2034 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002035 Info.Diag(Conv);
Richard Smithf2b681b2011-12-21 05:04:46 +00002036 }
Richard Smith96e0c102011-11-04 02:25:55 +00002037 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002038 }
Richard Smith96e0c102011-11-04 02:25:55 +00002039 }
Richard Smithf2b681b2011-12-21 05:04:46 +00002040
Richard Smith3da88fa2013-04-26 14:36:30 +00002041 return EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal) &&
2042 extractSubobject(Info, Conv, RVal, VT, LVal.Designator);
Richard Smith11562c52011-10-28 17:51:58 +00002043 }
2044
Richard Smithf2b681b2011-12-21 05:04:46 +00002045 // Volatile temporary objects cannot be read in constant expressions.
2046 if (Base->getType().isVolatileQualified()) {
2047 if (Info.getLangOpts().CPlusPlus) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002048 Info.Diag(Conv, diag::note_constexpr_access_volatile_obj, 1)
2049 << AK_Read << 0;
Richard Smithf2b681b2011-12-21 05:04:46 +00002050 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2051 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002052 Info.Diag(Conv);
Richard Smithf2b681b2011-12-21 05:04:46 +00002053 }
2054 return false;
2055 }
2056
Richard Smithf3e9e432011-11-07 09:22:26 +00002057 if (Frame) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002058 // In C++1y, we can't safely read anything which might have been mutated
2059 // when checking a potential constant expression.
2060 if (Info.getLangOpts().CPlusPlus1y &&
2061 Info.CheckingPotentialConstantExpression)
2062 return false;
2063
Richard Smithf3e9e432011-11-07 09:22:26 +00002064 // If this is a temporary expression with a nontrivial initializer, grab the
2065 // value from the relevant stack frame.
2066 RVal = Frame->Temporaries[Base];
2067 } else if (const CompoundLiteralExpr *CLE
2068 = dyn_cast<CompoundLiteralExpr>(Base)) {
2069 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2070 // initializer until now for such expressions. Such an expression can't be
2071 // an ICE in C, so this only matters for fold.
2072 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2073 if (!Evaluate(RVal, Info, CLE->getInitializer()))
2074 return false;
Richard Smith14a94132012-02-17 03:35:37 +00002075 } else if (isa<StringLiteral>(Base)) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002076 if (Info.getLangOpts().CPlusPlus1y &&
2077 Info.CheckingPotentialConstantExpression &&
2078 !Base->getType().isConstQualified())
2079 return false;
2080
Richard Smith14a94132012-02-17 03:35:37 +00002081 // We represent a string literal array as an lvalue pointing at the
2082 // corresponding expression, rather than building an array of chars.
2083 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith2e312c82012-03-03 22:46:17 +00002084 RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002085 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002086 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00002087 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002088 }
Richard Smith96e0c102011-11-04 02:25:55 +00002089
Richard Smith3da88fa2013-04-26 14:36:30 +00002090 return extractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator);
2091}
2092
2093/// Perform an assignment of Val to LVal. Takes ownership of Val.
2094// FIXME: Factor out duplication with HandleLValueToRValueConversion.
2095static bool HandleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
2096 QualType LValType, APValue &Val) {
2097 if (!Info.getLangOpts().CPlusPlus1y) {
2098 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
2099 return false;
2100 }
2101
2102 if (LVal.Designator.Invalid)
2103 // A diagnostic will have already been produced.
2104 return false;
2105
2106 if (Info.CheckingPotentialConstantExpression)
2107 return false;
2108
2109 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2110
2111 if (!LVal.Base) {
2112 Info.Diag(E, diag::note_constexpr_access_null) << AK_Assign;
2113 return false;
2114 }
2115
2116 if (!LVal.CallIndex) {
2117 Info.Diag(E, diag::note_constexpr_modify_global);
2118 return false;
2119 }
2120
2121 CallStackFrame *Frame = Info.getCallFrame(LVal.CallIndex);
2122 if (!Frame) {
2123 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2124 << AK_Assign << !Base;
2125 NoteLValueLocation(Info, LVal.Base);
2126 return false;
2127 }
2128
2129 if (LValType.isVolatileQualified()) {
2130 if (Info.getLangOpts().CPlusPlus)
2131 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2132 << AK_Assign << LValType;
2133 else
2134 Info.Diag(E);
2135 return false;
2136 }
2137
2138 // Compute value storage location and type of base object.
2139 APValue *BaseVal = 0;
2140 QualType BaseType;
2141
2142 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2143 const VarDecl *VD = dyn_cast<VarDecl>(D);
2144 if (VD) {
2145 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2146 VD = VDef;
2147 }
2148 if (!VD || VD->isInvalidDecl()) {
2149 Info.Diag(E);
2150 return false;
2151 }
2152
2153 // Modifications to volatile-qualified objects are not allowed.
2154 BaseType = VD->getType();
2155 if (BaseType.isVolatileQualified()) {
2156 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2157 << AK_Assign << 1 << VD;
2158 Info.Note(VD->getLocation(), diag::note_declared_at);
2159 return false;
2160 }
2161
2162 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2163 if (!Frame || !Frame->Arguments) {
2164 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
2165 return false;
2166 }
2167 BaseVal = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2168 } else if (VD->hasLocalStorage() && Frame && Frame->Index > 1) {
2169 BaseVal = &Frame->Temporaries[VD];
2170 } else {
2171 // FIXME: Can this happen?
2172 Info.Diag(E);
2173 return false;
2174 }
2175 } else {
2176 BaseType = Base->getType();
2177 BaseVal = &Frame->Temporaries[Base];
2178
2179 // Volatile temporary objects cannot be modified in constant expressions.
2180 if (BaseType.isVolatileQualified()) {
2181 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2182 << AK_Assign << 0;
2183 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2184 return false;
2185 }
2186 }
2187
2188 return modifySubobject(Info, E, *BaseVal, BaseType, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002189}
2190
Richard Smithe97cbd72011-11-11 04:05:33 +00002191/// Build an lvalue for the object argument of a member function call.
2192static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2193 LValue &This) {
2194 if (Object->getType()->isPointerType())
2195 return EvaluatePointer(Object, This, Info);
2196
2197 if (Object->isGLValue())
2198 return EvaluateLValue(Object, This, Info);
2199
Richard Smithd9f663b2013-04-22 15:31:51 +00002200 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00002201 return EvaluateTemporary(Object, This, Info);
2202
2203 return false;
2204}
2205
2206/// HandleMemberPointerAccess - Evaluate a member access operation and build an
2207/// lvalue referring to the result.
2208///
2209/// \param Info - Information about the ongoing evaluation.
2210/// \param BO - The member pointer access operation.
2211/// \param LV - Filled in with a reference to the resulting object.
2212/// \param IncludeMember - Specifies whether the member itself is included in
2213/// the resulting LValue subobject designator. This is not possible when
2214/// creating a bound member function.
2215/// \return The field or method declaration to which the member pointer refers,
2216/// or 0 if evaluation fails.
2217static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
2218 const BinaryOperator *BO,
2219 LValue &LV,
2220 bool IncludeMember = true) {
2221 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
2222
Richard Smith253c2a32012-01-27 01:14:48 +00002223 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
2224 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smith027bf112011-11-17 22:56:20 +00002225 return 0;
2226
2227 MemberPtr MemPtr;
2228 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
2229 return 0;
2230
2231 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2232 // member value, the behavior is undefined.
2233 if (!MemPtr.getDecl())
2234 return 0;
2235
Richard Smith253c2a32012-01-27 01:14:48 +00002236 if (!EvalObjOK)
2237 return 0;
2238
Richard Smith027bf112011-11-17 22:56:20 +00002239 if (MemPtr.isDerivedMember()) {
2240 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00002241 // The end of the derived-to-base path for the base object must match the
2242 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00002243 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith027bf112011-11-17 22:56:20 +00002244 LV.Designator.Entries.size())
2245 return 0;
2246 unsigned PathLengthToMember =
2247 LV.Designator.Entries.size() - MemPtr.Path.size();
2248 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
2249 const CXXRecordDecl *LVDecl = getAsBaseClass(
2250 LV.Designator.Entries[PathLengthToMember + I]);
2251 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
2252 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
2253 return 0;
2254 }
2255
2256 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002257 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
2258 PathLengthToMember))
2259 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002260 } else if (!MemPtr.Path.empty()) {
2261 // Extend the LValue path with the member pointer's path.
2262 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
2263 MemPtr.Path.size() + IncludeMember);
2264
2265 // Walk down to the appropriate base class.
2266 QualType LVType = BO->getLHS()->getType();
2267 if (const PointerType *PT = LVType->getAs<PointerType>())
2268 LVType = PT->getPointeeType();
2269 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
2270 assert(RD && "member pointer access on non-class-type expression");
2271 // The first class in the path is that of the lvalue.
2272 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
2273 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
John McCalld7bca762012-05-01 00:38:49 +00002274 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
2275 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002276 RD = Base;
2277 }
2278 // Finally cast to the class containing the member.
John McCalld7bca762012-05-01 00:38:49 +00002279 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
2280 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002281 }
2282
2283 // Add the member. Note that we cannot build bound member functions here.
2284 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00002285 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
2286 if (!HandleLValueMember(Info, BO, LV, FD))
2287 return 0;
2288 } else if (const IndirectFieldDecl *IFD =
2289 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
2290 if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
2291 return 0;
2292 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002293 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00002294 }
Richard Smith027bf112011-11-17 22:56:20 +00002295 }
2296
2297 return MemPtr.getDecl();
2298}
2299
2300/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
2301/// the provided lvalue, which currently refers to the base object.
2302static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
2303 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00002304 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002305 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00002306 return false;
2307
Richard Smitha8105bc2012-01-06 16:39:00 +00002308 QualType TargetQT = E->getType();
2309 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2310 TargetQT = PT->getPointeeType();
2311
2312 // Check this cast lands within the final derived-to-base subobject path.
2313 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002314 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002315 << D.MostDerivedType << TargetQT;
2316 return false;
2317 }
2318
Richard Smith027bf112011-11-17 22:56:20 +00002319 // Check the type of the final cast. We don't need to check the path,
2320 // since a cast can only be formed if the path is unique.
2321 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00002322 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2323 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00002324 if (NewEntriesSize == D.MostDerivedPathLength)
2325 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2326 else
Richard Smith027bf112011-11-17 22:56:20 +00002327 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00002328 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002329 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002330 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00002331 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00002332 }
Richard Smith027bf112011-11-17 22:56:20 +00002333
2334 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002335 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00002336}
2337
Mike Stump876387b2009-10-27 22:09:17 +00002338namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00002339enum EvalStmtResult {
2340 /// Evaluation failed.
2341 ESR_Failed,
2342 /// Hit a 'return' statement.
2343 ESR_Returned,
2344 /// Evaluation succeeded.
2345 ESR_Succeeded
2346};
2347}
2348
Richard Smithd9f663b2013-04-22 15:31:51 +00002349static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
2350 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2351 // We don't need to evaluate the initializer for a static local.
2352 if (!VD->hasLocalStorage())
2353 return true;
2354
2355 LValue Result;
2356 Result.set(VD, Info.CurrentCall->Index);
2357 APValue &Val = Info.CurrentCall->Temporaries[VD];
2358
2359 if (!EvaluateInPlace(Val, Info, Result, VD->getInit())) {
2360 // Wipe out any partially-computed value, to allow tracking that this
2361 // evaluation failed.
2362 Val = APValue();
2363 return false;
2364 }
2365 }
2366
2367 return true;
2368}
2369
Richard Smith254a73d2011-10-28 22:34:42 +00002370// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00002371static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +00002372 const Stmt *S) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002373 // FIXME: Mark all temporaries in the current frame as destroyed at
2374 // the end of each full-expression.
Richard Smith254a73d2011-10-28 22:34:42 +00002375 switch (S->getStmtClass()) {
2376 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00002377 if (const Expr *E = dyn_cast<Expr>(S)) {
2378 EvaluateIgnoredValue(Info, E);
2379 // Don't bother evaluating beyond an expression-statement which couldn't
2380 // be evaluated.
2381 if (Info.EvalStatus.HasSideEffects && !Info.keepEvaluatingAfterFailure())
2382 return ESR_Failed;
2383 return ESR_Succeeded;
2384 }
2385
2386 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00002387 return ESR_Failed;
2388
2389 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00002390 return ESR_Succeeded;
2391
Richard Smithd9f663b2013-04-22 15:31:51 +00002392 case Stmt::DeclStmtClass: {
2393 const DeclStmt *DS = cast<DeclStmt>(S);
2394 for (DeclStmt::const_decl_iterator DclIt = DS->decl_begin(),
2395 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt)
2396 if (!EvaluateDecl(Info, *DclIt) && !Info.keepEvaluatingAfterFailure())
2397 return ESR_Failed;
2398 return ESR_Succeeded;
2399 }
2400
Richard Smith357362d2011-12-13 06:39:58 +00002401 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00002402 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smithd9f663b2013-04-22 15:31:51 +00002403 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00002404 return ESR_Failed;
2405 return ESR_Returned;
2406 }
Richard Smith254a73d2011-10-28 22:34:42 +00002407
2408 case Stmt::CompoundStmtClass: {
2409 const CompoundStmt *CS = cast<CompoundStmt>(S);
2410 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2411 BE = CS->body_end(); BI != BE; ++BI) {
2412 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2413 if (ESR != ESR_Succeeded)
2414 return ESR;
2415 }
2416 return ESR_Succeeded;
2417 }
Richard Smithd9f663b2013-04-22 15:31:51 +00002418
2419 case Stmt::IfStmtClass: {
2420 const IfStmt *IS = cast<IfStmt>(S);
2421
2422 // Evaluate the condition, as either a var decl or as an expression.
2423 bool Cond;
2424 if (VarDecl *CondDecl = IS->getConditionVariable()) {
2425 if (!EvaluateDecl(Info, CondDecl))
2426 return ESR_Failed;
2427 if (!HandleConversionToBool(Info.CurrentCall->Temporaries[CondDecl],
2428 Cond))
2429 return ESR_Failed;
2430 } else if (!EvaluateAsBooleanCondition(IS->getCond(), Cond, Info))
2431 return ESR_Failed;
2432
2433 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
2434 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
2435 if (ESR != ESR_Succeeded)
2436 return ESR;
2437 }
2438 return ESR_Succeeded;
2439 }
Richard Smith254a73d2011-10-28 22:34:42 +00002440 }
2441}
2442
Richard Smithcc36f692011-12-22 02:22:31 +00002443/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2444/// default constructor. If so, we'll fold it whether or not it's marked as
2445/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2446/// so we need special handling.
2447static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00002448 const CXXConstructorDecl *CD,
2449 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00002450 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2451 return false;
2452
Richard Smith66e05fe2012-01-18 05:21:49 +00002453 // Value-initialization does not call a trivial default constructor, so such a
2454 // call is a core constant expression whether or not the constructor is
2455 // constexpr.
2456 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002457 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00002458 // FIXME: If DiagDecl is an implicitly-declared special member function,
2459 // we should be much more explicit about why it's not constexpr.
2460 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2461 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2462 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00002463 } else {
2464 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2465 }
2466 }
2467 return true;
2468}
2469
Richard Smith357362d2011-12-13 06:39:58 +00002470/// CheckConstexprFunction - Check that a function can be called in a constant
2471/// expression.
2472static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2473 const FunctionDecl *Declaration,
2474 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00002475 // Potential constant expressions can contain calls to declared, but not yet
2476 // defined, constexpr functions.
2477 if (Info.CheckingPotentialConstantExpression && !Definition &&
2478 Declaration->isConstexpr())
2479 return false;
2480
Richard Smith357362d2011-12-13 06:39:58 +00002481 // Can we evaluate this function call?
2482 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2483 return true;
2484
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002485 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00002486 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002487 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2488 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00002489 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2490 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2491 << DiagDecl;
2492 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2493 } else {
2494 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2495 }
2496 return false;
2497}
2498
Richard Smithd62306a2011-11-10 06:34:14 +00002499namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00002500typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00002501}
2502
2503/// EvaluateArgs - Evaluate the arguments to a function call.
2504static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2505 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00002506 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00002507 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00002508 I != E; ++I) {
2509 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2510 // If we're checking for a potential constant expression, evaluate all
2511 // initializers even if some of them fail.
2512 if (!Info.keepEvaluatingAfterFailure())
2513 return false;
2514 Success = false;
2515 }
2516 }
2517 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00002518}
2519
Richard Smith254a73d2011-10-28 22:34:42 +00002520/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00002521static bool HandleFunctionCall(SourceLocation CallLoc,
2522 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002523 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00002524 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00002525 ArgVector ArgValues(Args.size());
2526 if (!EvaluateArgs(Args, ArgValues, Info))
2527 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00002528
Richard Smith253c2a32012-01-27 01:14:48 +00002529 if (!Info.CheckCallLimit(CallLoc))
2530 return false;
2531
2532 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd9f663b2013-04-22 15:31:51 +00002533 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00002534 if (ESR == ESR_Succeeded) {
2535 if (Callee->getResultType()->isVoidType())
2536 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002537 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00002538 }
Richard Smithd9f663b2013-04-22 15:31:51 +00002539 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00002540}
2541
Richard Smithd62306a2011-11-10 06:34:14 +00002542/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00002543static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00002544 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00002545 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00002546 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00002547 ArgVector ArgValues(Args.size());
2548 if (!EvaluateArgs(Args, ArgValues, Info))
2549 return false;
2550
Richard Smith253c2a32012-01-27 01:14:48 +00002551 if (!Info.CheckCallLimit(CallLoc))
2552 return false;
2553
Richard Smith3607ffe2012-02-13 03:54:03 +00002554 const CXXRecordDecl *RD = Definition->getParent();
2555 if (RD->getNumVBases()) {
2556 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2557 return false;
2558 }
2559
Richard Smith253c2a32012-01-27 01:14:48 +00002560 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00002561
2562 // If it's a delegating constructor, just delegate.
2563 if (Definition->isDelegatingConstructor()) {
2564 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smithd9f663b2013-04-22 15:31:51 +00002565 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
2566 return false;
2567 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00002568 }
2569
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002570 // For a trivial copy or move constructor, perform an APValue copy. This is
2571 // essential for unions, where the operations performed by the constructor
2572 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002573 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00002574 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2575 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002576 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00002577 RHS.setFrom(Info.Ctx, ArgValues[0]);
2578 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2579 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002580 }
2581
2582 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00002583 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00002584 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2585 std::distance(RD->field_begin(), RD->field_end()));
2586
John McCalld7bca762012-05-01 00:38:49 +00002587 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002588 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2589
Richard Smith253c2a32012-01-27 01:14:48 +00002590 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00002591 unsigned BasesSeen = 0;
2592#ifndef NDEBUG
2593 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2594#endif
2595 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2596 E = Definition->init_end(); I != E; ++I) {
Richard Smith253c2a32012-01-27 01:14:48 +00002597 LValue Subobject = This;
2598 APValue *Value = &Result;
2599
2600 // Determine the subobject to initialize.
Richard Smithd62306a2011-11-10 06:34:14 +00002601 if ((*I)->isBaseInitializer()) {
2602 QualType BaseType((*I)->getBaseClass(), 0);
2603#ifndef NDEBUG
2604 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00002605 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00002606 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2607 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2608 "base class initializers not in expected order");
2609 ++BaseIt;
2610#endif
John McCalld7bca762012-05-01 00:38:49 +00002611 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
2612 BaseType->getAsCXXRecordDecl(), &Layout))
2613 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00002614 Value = &Result.getStructBase(BasesSeen++);
Richard Smithd62306a2011-11-10 06:34:14 +00002615 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCalld7bca762012-05-01 00:38:49 +00002616 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
2617 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002618 if (RD->isUnion()) {
2619 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00002620 Value = &Result.getUnionValue();
2621 } else {
2622 Value = &Result.getStructField(FD->getFieldIndex());
2623 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00002624 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002625 // Walk the indirect field decl's chain to find the object to initialize,
2626 // and make sure we've initialized every step along it.
2627 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2628 CE = IFD->chain_end();
2629 C != CE; ++C) {
2630 FieldDecl *FD = cast<FieldDecl>(*C);
2631 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2632 // Switch the union field if it differs. This happens if we had
2633 // preceding zero-initialization, and we're now initializing a union
2634 // subobject other than the first.
2635 // FIXME: In this case, the values of the other subobjects are
2636 // specified, since zero-initialization sets all padding bits to zero.
2637 if (Value->isUninit() ||
2638 (Value->isUnion() && Value->getUnionField() != FD)) {
2639 if (CD->isUnion())
2640 *Value = APValue(FD);
2641 else
2642 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2643 std::distance(CD->field_begin(), CD->field_end()));
2644 }
John McCalld7bca762012-05-01 00:38:49 +00002645 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
2646 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002647 if (CD->isUnion())
2648 Value = &Value->getUnionValue();
2649 else
2650 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00002651 }
Richard Smithd62306a2011-11-10 06:34:14 +00002652 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002653 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00002654 }
Richard Smith253c2a32012-01-27 01:14:48 +00002655
Richard Smithb228a862012-02-15 02:18:13 +00002656 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2657 (*I)->isBaseInitializer()
Richard Smith253c2a32012-01-27 01:14:48 +00002658 ? CCEK_Constant : CCEK_MemberInit)) {
2659 // If we're checking for a potential constant expression, evaluate all
2660 // initializers even if some of them fail.
2661 if (!Info.keepEvaluatingAfterFailure())
2662 return false;
2663 Success = false;
2664 }
Richard Smithd62306a2011-11-10 06:34:14 +00002665 }
2666
Richard Smithd9f663b2013-04-22 15:31:51 +00002667 return Success &&
2668 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00002669}
2670
Eli Friedman9a156e52008-11-12 09:44:48 +00002671//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00002672// Generic Evaluation
2673//===----------------------------------------------------------------------===//
2674namespace {
2675
Richard Smithf57d8cb2011-12-09 22:58:01 +00002676// FIXME: RetTy is always bool. Remove it.
2677template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00002678class ExprEvaluatorBase
2679 : public ConstStmtVisitor<Derived, RetTy> {
2680private:
Richard Smith2e312c82012-03-03 22:46:17 +00002681 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002682 return static_cast<Derived*>(this)->Success(V, E);
2683 }
Richard Smithfddd3842011-12-30 21:15:51 +00002684 RetTy DerivedZeroInitialization(const Expr *E) {
2685 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002686 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002687
Richard Smith17100ba2012-02-16 02:46:34 +00002688 // Check whether a conditional operator with a non-constant condition is a
2689 // potential constant expression. If neither arm is a potential constant
2690 // expression, then the conditional operator is not either.
2691 template<typename ConditionalOperator>
2692 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2693 assert(Info.CheckingPotentialConstantExpression);
2694
2695 // Speculatively evaluate both arms.
2696 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002697 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00002698 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2699
2700 StmtVisitorTy::Visit(E->getFalseExpr());
2701 if (Diag.empty())
2702 return;
2703
2704 Diag.clear();
2705 StmtVisitorTy::Visit(E->getTrueExpr());
2706 if (Diag.empty())
2707 return;
2708 }
2709
2710 Error(E, diag::note_constexpr_conditional_never_const);
2711 }
2712
2713
2714 template<typename ConditionalOperator>
2715 bool HandleConditionalOperator(const ConditionalOperator *E) {
2716 bool BoolResult;
2717 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2718 if (Info.CheckingPotentialConstantExpression)
2719 CheckPotentialConstantConditional(E);
2720 return false;
2721 }
2722
2723 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2724 return StmtVisitorTy::Visit(EvalExpr);
2725 }
2726
Peter Collingbournee9200682011-05-13 03:29:01 +00002727protected:
2728 EvalInfo &Info;
2729 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2730 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2731
Richard Smith92b1ce02011-12-12 09:28:41 +00002732 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002733 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002734 }
2735
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00002736 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2737
2738public:
2739 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2740
2741 EvalInfo &getEvalInfo() { return Info; }
2742
Richard Smithf57d8cb2011-12-09 22:58:01 +00002743 /// Report an evaluation error. This should only be called when an error is
2744 /// first discovered. When propagating an error, just return false.
2745 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002746 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002747 return false;
2748 }
2749 bool Error(const Expr *E) {
2750 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2751 }
2752
Peter Collingbournee9200682011-05-13 03:29:01 +00002753 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00002754 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00002755 }
2756 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002757 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002758 }
2759
2760 RetTy VisitParenExpr(const ParenExpr *E)
2761 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2762 RetTy VisitUnaryExtension(const UnaryOperator *E)
2763 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2764 RetTy VisitUnaryPlus(const UnaryOperator *E)
2765 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2766 RetTy VisitChooseExpr(const ChooseExpr *E)
2767 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2768 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2769 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00002770 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2771 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00002772 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2773 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith852c9db2013-04-20 22:23:05 +00002774 RetTy VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
2775 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00002776 // We cannot create any objects for which cleanups are required, so there is
2777 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2778 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2779 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002780
Richard Smith6d6ecc32011-12-12 12:46:16 +00002781 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2782 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2783 return static_cast<Derived*>(this)->VisitCastExpr(E);
2784 }
2785 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2786 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2787 return static_cast<Derived*>(this)->VisitCastExpr(E);
2788 }
2789
Richard Smith027bf112011-11-17 22:56:20 +00002790 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2791 switch (E->getOpcode()) {
2792 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00002793 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002794
2795 case BO_Comma:
2796 VisitIgnoredValue(E->getLHS());
2797 return StmtVisitorTy::Visit(E->getRHS());
2798
2799 case BO_PtrMemD:
2800 case BO_PtrMemI: {
2801 LValue Obj;
2802 if (!HandleMemberPointerAccess(Info, E, Obj))
2803 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00002804 APValue Result;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002805 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00002806 return false;
2807 return DerivedSuccess(Result, E);
2808 }
2809 }
2810 }
2811
Peter Collingbournee9200682011-05-13 03:29:01 +00002812 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00002813 // Evaluate and cache the common expression. We treat it as a temporary,
2814 // even though it's not quite the same thing.
2815 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
2816 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002817 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002818
Richard Smith17100ba2012-02-16 02:46:34 +00002819 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002820 }
2821
2822 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002823 bool IsBcpCall = false;
2824 // If the condition (ignoring parens) is a __builtin_constant_p call,
2825 // the result is a constant expression if it can be folded without
2826 // side-effects. This is an important GNU extension. See GCC PR38377
2827 // for discussion.
2828 if (const CallExpr *CallCE =
2829 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2830 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2831 IsBcpCall = true;
2832
2833 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2834 // constant expression; we can't check whether it's potentially foldable.
2835 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2836 return false;
2837
2838 FoldConstant Fold(Info);
2839
Richard Smith17100ba2012-02-16 02:46:34 +00002840 if (!HandleConditionalOperator(E))
Richard Smith84f6dcf2012-02-02 01:16:57 +00002841 return false;
2842
2843 if (IsBcpCall)
2844 Fold.Fold(Info);
2845
2846 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00002847 }
2848
2849 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00002850 APValue &Value = Info.CurrentCall->Temporaries[E];
2851 if (Value.isUninit()) {
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002852 const Expr *Source = E->getSourceExpr();
2853 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002854 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002855 if (Source == E) { // sanity checking.
2856 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00002857 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002858 }
2859 return StmtVisitorTy::Visit(Source);
2860 }
Richard Smith26d4cc12012-06-26 08:12:11 +00002861 return DerivedSuccess(Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002862 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002863
Richard Smith254a73d2011-10-28 22:34:42 +00002864 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002865 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00002866 QualType CalleeType = Callee->getType();
2867
Richard Smith254a73d2011-10-28 22:34:42 +00002868 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00002869 LValue *This = 0, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002870 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00002871 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00002872
Richard Smithe97cbd72011-11-11 04:05:33 +00002873 // Extract function decl and 'this' pointer from the callee.
2874 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002875 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00002876 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2877 // Explicit bound member calls, such as x.f() or p->g();
2878 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002879 return false;
2880 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00002881 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00002882 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00002883 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2884 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00002885 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2886 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00002887 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00002888 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002889 return Error(Callee);
2890
2891 FD = dyn_cast<FunctionDecl>(Member);
2892 if (!FD)
2893 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002894 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002895 LValue Call;
2896 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002897 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00002898
Richard Smitha8105bc2012-01-06 16:39:00 +00002899 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002900 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00002901 FD = dyn_cast_or_null<FunctionDecl>(
2902 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00002903 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002904 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002905
2906 // Overloaded operator calls to member functions are represented as normal
2907 // calls with '*this' as the first argument.
2908 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2909 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002910 // FIXME: When selecting an implicit conversion for an overloaded
2911 // operator delete, we sometimes try to evaluate calls to conversion
2912 // operators without a 'this' parameter!
2913 if (Args.empty())
2914 return Error(E);
2915
Richard Smithe97cbd72011-11-11 04:05:33 +00002916 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2917 return false;
2918 This = &ThisVal;
2919 Args = Args.slice(1);
2920 }
2921
2922 // Don't call function pointers which have been cast to some other type.
2923 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002924 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00002925 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002926 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00002927
Richard Smith47b34932012-02-01 02:39:43 +00002928 if (This && !This->checkSubobject(Info, E, CSK_This))
2929 return false;
2930
Richard Smith3607ffe2012-02-13 03:54:03 +00002931 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2932 // calls to such functions in constant expressions.
2933 if (This && !HasQualifier &&
2934 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2935 return Error(E, diag::note_constexpr_virtual_call);
2936
Richard Smith357362d2011-12-13 06:39:58 +00002937 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00002938 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00002939 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00002940
Richard Smith357362d2011-12-13 06:39:58 +00002941 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00002942 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2943 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002944 return false;
2945
Richard Smithb228a862012-02-15 02:18:13 +00002946 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00002947 }
2948
Richard Smith11562c52011-10-28 17:51:58 +00002949 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2950 return StmtVisitorTy::Visit(E->getInitializer());
2951 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002952 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00002953 if (E->getNumInits() == 0)
2954 return DerivedZeroInitialization(E);
2955 if (E->getNumInits() == 1)
2956 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00002957 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002958 }
2959 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002960 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002961 }
2962 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002963 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002964 }
Richard Smith027bf112011-11-17 22:56:20 +00002965 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002966 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00002967 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002968
Richard Smithd62306a2011-11-10 06:34:14 +00002969 /// A member expression where the object is a prvalue is itself a prvalue.
2970 RetTy VisitMemberExpr(const MemberExpr *E) {
2971 assert(!E->isArrow() && "missing call to bound member function?");
2972
Richard Smith2e312c82012-03-03 22:46:17 +00002973 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00002974 if (!Evaluate(Val, Info, E->getBase()))
2975 return false;
2976
2977 QualType BaseTy = E->getBase()->getType();
2978
2979 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00002980 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002981 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00002982 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00002983 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2984
Richard Smitha8105bc2012-01-06 16:39:00 +00002985 SubobjectDesignator Designator(BaseTy);
2986 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00002987
Richard Smith3da88fa2013-04-26 14:36:30 +00002988 return extractSubobject(Info, E, Val, BaseTy, Designator) &&
Richard Smithd62306a2011-11-10 06:34:14 +00002989 DerivedSuccess(Val, E);
2990 }
2991
Richard Smith11562c52011-10-28 17:51:58 +00002992 RetTy VisitCastExpr(const CastExpr *E) {
2993 switch (E->getCastKind()) {
2994 default:
2995 break;
2996
David Chisnallfa35df62012-01-16 17:27:18 +00002997 case CK_AtomicToNonAtomic:
2998 case CK_NonAtomicToAtomic:
Richard Smith11562c52011-10-28 17:51:58 +00002999 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00003000 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00003001 return StmtVisitorTy::Visit(E->getSubExpr());
3002
3003 case CK_LValueToRValue: {
3004 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003005 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
3006 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003007 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00003008 // Note, we use the subexpression's type in order to retain cv-qualifiers.
3009 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
3010 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003011 return false;
3012 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00003013 }
3014 }
3015
Richard Smithf57d8cb2011-12-09 22:58:01 +00003016 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003017 }
3018
Richard Smith4a678122011-10-24 18:44:57 +00003019 /// Visit a value which is evaluated, but whose value is ignored.
3020 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003021 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00003022 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003023};
3024
3025}
3026
3027//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003028// Common base class for lvalue and temporary evaluation.
3029//===----------------------------------------------------------------------===//
3030namespace {
3031template<class Derived>
3032class LValueExprEvaluatorBase
3033 : public ExprEvaluatorBase<Derived, bool> {
3034protected:
3035 LValue &Result;
3036 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
3037 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
3038
3039 bool Success(APValue::LValueBase B) {
3040 Result.set(B);
3041 return true;
3042 }
3043
3044public:
3045 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
3046 ExprEvaluatorBaseTy(Info), Result(Result) {}
3047
Richard Smith2e312c82012-03-03 22:46:17 +00003048 bool Success(const APValue &V, const Expr *E) {
3049 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00003050 return true;
3051 }
Richard Smith027bf112011-11-17 22:56:20 +00003052
Richard Smith027bf112011-11-17 22:56:20 +00003053 bool VisitMemberExpr(const MemberExpr *E) {
3054 // Handle non-static data members.
3055 QualType BaseTy;
3056 if (E->isArrow()) {
3057 if (!EvaluatePointer(E->getBase(), Result, this->Info))
3058 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00003059 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00003060 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00003061 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00003062 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
3063 return false;
3064 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003065 } else {
3066 if (!this->Visit(E->getBase()))
3067 return false;
3068 BaseTy = E->getBase()->getType();
3069 }
Richard Smith027bf112011-11-17 22:56:20 +00003070
Richard Smith1b78b3d2012-01-25 22:15:11 +00003071 const ValueDecl *MD = E->getMemberDecl();
3072 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
3073 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
3074 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3075 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00003076 if (!HandleLValueMember(this->Info, E, Result, FD))
3077 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003078 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00003079 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
3080 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003081 } else
3082 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003083
Richard Smith1b78b3d2012-01-25 22:15:11 +00003084 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00003085 APValue RefValue;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003086 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00003087 RefValue))
3088 return false;
3089 return Success(RefValue, E);
3090 }
3091 return true;
3092 }
3093
3094 bool VisitBinaryOperator(const BinaryOperator *E) {
3095 switch (E->getOpcode()) {
3096 default:
3097 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
3098
3099 case BO_PtrMemD:
3100 case BO_PtrMemI:
3101 return HandleMemberPointerAccess(this->Info, E, Result);
Richard Smith3da88fa2013-04-26 14:36:30 +00003102
3103 case BO_Assign: {
3104 if (!this->Visit(E->getLHS()))
3105 return false;
3106 APValue NewVal;
3107 if (!Evaluate(NewVal, this->Info, E->getRHS()))
3108 return false;
3109 return HandleAssignment(this->Info, E, Result, E->getLHS()->getType(),
3110 NewVal);
3111 }
Richard Smith027bf112011-11-17 22:56:20 +00003112 }
3113 }
3114
3115 bool VisitCastExpr(const CastExpr *E) {
3116 switch (E->getCastKind()) {
3117 default:
3118 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3119
3120 case CK_DerivedToBase:
3121 case CK_UncheckedDerivedToBase: {
3122 if (!this->Visit(E->getSubExpr()))
3123 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003124
3125 // Now figure out the necessary offset to add to the base LV to get from
3126 // the derived class to the base class.
3127 QualType Type = E->getSubExpr()->getType();
3128
3129 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3130 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003131 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smith027bf112011-11-17 22:56:20 +00003132 *PathI))
3133 return false;
3134 Type = (*PathI)->getType();
3135 }
3136
3137 return true;
3138 }
3139 }
3140 }
3141};
3142}
3143
3144//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00003145// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003146//
3147// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
3148// function designators (in C), decl references to void objects (in C), and
3149// temporaries (if building with -Wno-address-of-temporary).
3150//
3151// LValue evaluation produces values comprising a base expression of one of the
3152// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00003153// - Declarations
3154// * VarDecl
3155// * FunctionDecl
3156// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00003157// * CompoundLiteralExpr in C
3158// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00003159// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00003160// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00003161// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00003162// * ObjCEncodeExpr
3163// * AddrLabelExpr
3164// * BlockExpr
3165// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00003166// - Locals and temporaries
Richard Smithb228a862012-02-15 02:18:13 +00003167// * Any Expr, with a CallIndex indicating the function in which the temporary
3168// was evaluated.
Richard Smithce40ad62011-11-12 22:28:03 +00003169// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00003170//===----------------------------------------------------------------------===//
3171namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003172class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00003173 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00003174public:
Richard Smith027bf112011-11-17 22:56:20 +00003175 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
3176 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00003177
Richard Smith11562c52011-10-28 17:51:58 +00003178 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
3179
Peter Collingbournee9200682011-05-13 03:29:01 +00003180 bool VisitDeclRefExpr(const DeclRefExpr *E);
3181 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003182 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003183 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
3184 bool VisitMemberExpr(const MemberExpr *E);
3185 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
3186 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00003187 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00003188 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003189 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
3190 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00003191 bool VisitUnaryReal(const UnaryOperator *E);
3192 bool VisitUnaryImag(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +00003193
Peter Collingbournee9200682011-05-13 03:29:01 +00003194 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00003195 switch (E->getCastKind()) {
3196 default:
Richard Smith027bf112011-11-17 22:56:20 +00003197 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00003198
Eli Friedmance3e02a2011-10-11 00:13:24 +00003199 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00003200 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00003201 if (!Visit(E->getSubExpr()))
3202 return false;
3203 Result.Designator.setInvalid();
3204 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00003205
Richard Smith027bf112011-11-17 22:56:20 +00003206 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00003207 if (!Visit(E->getSubExpr()))
3208 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003209 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00003210 }
3211 }
Eli Friedman9a156e52008-11-12 09:44:48 +00003212};
3213} // end anonymous namespace
3214
Richard Smith11562c52011-10-28 17:51:58 +00003215/// Evaluate an expression as an lvalue. This can be legitimately called on
3216/// expressions which are not glvalues, in a few cases:
3217/// * function designators in C,
3218/// * "extern void" objects,
3219/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +00003220static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003221 assert((E->isGLValue() || E->getType()->isFunctionType() ||
3222 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
3223 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +00003224 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003225}
3226
Peter Collingbournee9200682011-05-13 03:29:01 +00003227bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00003228 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
3229 return Success(FD);
3230 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00003231 return VisitVarDecl(E, VD);
3232 return Error(E);
3233}
Richard Smith733237d2011-10-24 23:14:33 +00003234
Richard Smith11562c52011-10-28 17:51:58 +00003235bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +00003236 if (!VD->getType()->isReferenceType()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003237 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
Richard Smithb228a862012-02-15 02:18:13 +00003238 Result.set(VD, Info.CurrentCall->Index);
Richard Smithfec09922011-11-01 16:57:24 +00003239 return true;
3240 }
Richard Smithce40ad62011-11-12 22:28:03 +00003241 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00003242 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00003243
Richard Smith2e312c82012-03-03 22:46:17 +00003244 APValue V;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003245 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
3246 return false;
3247 return Success(V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00003248}
3249
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003250bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
3251 const MaterializeTemporaryExpr *E) {
Jordan Roseb1312a52013-04-11 00:58:58 +00003252 if (E->getType()->isRecordType())
3253 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
Richard Smith027bf112011-11-17 22:56:20 +00003254
Richard Smithb228a862012-02-15 02:18:13 +00003255 Result.set(E, Info.CurrentCall->Index);
Jordan Roseb1312a52013-04-11 00:58:58 +00003256 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
3257 Result, E->GetTemporaryExpr());
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003258}
3259
Peter Collingbournee9200682011-05-13 03:29:01 +00003260bool
3261LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003262 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
3263 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
3264 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00003265 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003266}
3267
Richard Smith6e525142011-12-27 12:18:28 +00003268bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00003269 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00003270 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00003271
3272 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
3273 << E->getExprOperand()->getType()
3274 << E->getExprOperand()->getSourceRange();
3275 return false;
Richard Smith6e525142011-12-27 12:18:28 +00003276}
3277
Francois Pichet0066db92012-04-16 04:08:35 +00003278bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
3279 return Success(E);
3280}
3281
Peter Collingbournee9200682011-05-13 03:29:01 +00003282bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003283 // Handle static data members.
3284 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
3285 VisitIgnoredValue(E->getBase());
3286 return VisitVarDecl(E, VD);
3287 }
3288
Richard Smith254a73d2011-10-28 22:34:42 +00003289 // Handle static member functions.
3290 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
3291 if (MD->isStatic()) {
3292 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00003293 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00003294 }
3295 }
3296
Richard Smithd62306a2011-11-10 06:34:14 +00003297 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00003298 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003299}
3300
Peter Collingbournee9200682011-05-13 03:29:01 +00003301bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003302 // FIXME: Deal with vectors as array subscript bases.
3303 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003304 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003305
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003306 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00003307 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003308
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003309 APSInt Index;
3310 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00003311 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003312 int64_t IndexValue
3313 = Index.isSigned() ? Index.getSExtValue()
3314 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003315
Richard Smitha8105bc2012-01-06 16:39:00 +00003316 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003317}
Eli Friedman9a156e52008-11-12 09:44:48 +00003318
Peter Collingbournee9200682011-05-13 03:29:01 +00003319bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00003320 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00003321}
3322
Richard Smith66c96992012-02-18 22:04:06 +00003323bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3324 if (!Visit(E->getSubExpr()))
3325 return false;
3326 // __real is a no-op on scalar lvalues.
3327 if (E->getSubExpr()->getType()->isAnyComplexType())
3328 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
3329 return true;
3330}
3331
3332bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3333 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
3334 "lvalue __imag__ on scalar?");
3335 if (!Visit(E->getSubExpr()))
3336 return false;
3337 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
3338 return true;
3339}
3340
Eli Friedman9a156e52008-11-12 09:44:48 +00003341//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003342// Pointer Evaluation
3343//===----------------------------------------------------------------------===//
3344
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003345namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003346class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003347 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00003348 LValue &Result;
3349
Peter Collingbournee9200682011-05-13 03:29:01 +00003350 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00003351 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00003352 return true;
3353 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00003354public:
Mike Stump11289f42009-09-09 15:08:12 +00003355
John McCall45d55e42010-05-07 21:00:08 +00003356 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003357 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00003358
Richard Smith2e312c82012-03-03 22:46:17 +00003359 bool Success(const APValue &V, const Expr *E) {
3360 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00003361 return true;
3362 }
Richard Smithfddd3842011-12-30 21:15:51 +00003363 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00003364 return Success((Expr*)0);
3365 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00003366
John McCall45d55e42010-05-07 21:00:08 +00003367 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003368 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00003369 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003370 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00003371 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00003372 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00003373 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003374 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00003375 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003376 bool VisitCallExpr(const CallExpr *E);
3377 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00003378 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00003379 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003380 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00003381 }
Richard Smithd62306a2011-11-10 06:34:14 +00003382 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3383 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003384 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003385 Result = *Info.CurrentCall->This;
3386 return true;
3387 }
John McCallc07a0c72011-02-17 10:25:35 +00003388
Eli Friedman449fe542009-03-23 04:56:01 +00003389 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003390};
Chris Lattner05706e882008-07-11 18:11:29 +00003391} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003392
John McCall45d55e42010-05-07 21:00:08 +00003393static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003394 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00003395 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00003396}
3397
John McCall45d55e42010-05-07 21:00:08 +00003398bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00003399 if (E->getOpcode() != BO_Add &&
3400 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00003401 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00003402
Chris Lattner05706e882008-07-11 18:11:29 +00003403 const Expr *PExp = E->getLHS();
3404 const Expr *IExp = E->getRHS();
3405 if (IExp->getType()->isPointerType())
3406 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00003407
Richard Smith253c2a32012-01-27 01:14:48 +00003408 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3409 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00003410 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003411
John McCall45d55e42010-05-07 21:00:08 +00003412 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00003413 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00003414 return false;
3415 int64_t AdditionalOffset
3416 = Offset.isSigned() ? Offset.getSExtValue()
3417 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00003418 if (E->getOpcode() == BO_Sub)
3419 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00003420
Ted Kremenek28831752012-08-23 20:46:57 +00003421 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00003422 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3423 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00003424}
Eli Friedman9a156e52008-11-12 09:44:48 +00003425
John McCall45d55e42010-05-07 21:00:08 +00003426bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3427 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00003428}
Mike Stump11289f42009-09-09 15:08:12 +00003429
Peter Collingbournee9200682011-05-13 03:29:01 +00003430bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3431 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00003432
Eli Friedman847a2bc2009-12-27 05:43:15 +00003433 switch (E->getCastKind()) {
3434 default:
3435 break;
3436
John McCalle3027922010-08-25 11:45:40 +00003437 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00003438 case CK_CPointerToObjCPointerCast:
3439 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00003440 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00003441 if (!Visit(SubExpr))
3442 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00003443 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3444 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3445 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00003446 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00003447 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00003448 if (SubExpr->getType()->isVoidPointerType())
3449 CCEDiag(E, diag::note_constexpr_invalid_cast)
3450 << 3 << SubExpr->getType();
3451 else
3452 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3453 }
Richard Smith96e0c102011-11-04 02:25:55 +00003454 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00003455
Anders Carlsson18275092010-10-31 20:41:46 +00003456 case CK_DerivedToBase:
3457 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003458 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00003459 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003460 if (!Result.Base && Result.Offset.isZero())
3461 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00003462
Richard Smithd62306a2011-11-10 06:34:14 +00003463 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00003464 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00003465 QualType Type =
3466 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00003467
Richard Smithd62306a2011-11-10 06:34:14 +00003468 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00003469 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003470 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3471 *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00003472 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003473 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00003474 }
3475
Anders Carlsson18275092010-10-31 20:41:46 +00003476 return true;
3477 }
3478
Richard Smith027bf112011-11-17 22:56:20 +00003479 case CK_BaseToDerived:
3480 if (!Visit(E->getSubExpr()))
3481 return false;
3482 if (!Result.Base && Result.Offset.isZero())
3483 return true;
3484 return HandleBaseToDerivedCast(Info, E, Result);
3485
Richard Smith0b0a0b62011-10-29 20:57:55 +00003486 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00003487 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00003488 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00003489
John McCalle3027922010-08-25 11:45:40 +00003490 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00003491 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3492
Richard Smith2e312c82012-03-03 22:46:17 +00003493 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00003494 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00003495 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00003496
John McCall45d55e42010-05-07 21:00:08 +00003497 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003498 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3499 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00003500 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003501 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00003502 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00003503 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00003504 return true;
3505 } else {
3506 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00003507 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00003508 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00003509 }
3510 }
John McCalle3027922010-08-25 11:45:40 +00003511 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00003512 if (SubExpr->isGLValue()) {
3513 if (!EvaluateLValue(SubExpr, Result, Info))
3514 return false;
3515 } else {
Richard Smithb228a862012-02-15 02:18:13 +00003516 Result.set(SubExpr, Info.CurrentCall->Index);
3517 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3518 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00003519 return false;
3520 }
Richard Smith96e0c102011-11-04 02:25:55 +00003521 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00003522 if (const ConstantArrayType *CAT
3523 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3524 Result.addArray(Info, E, CAT);
3525 else
3526 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00003527 return true;
Richard Smithdd785442011-10-31 20:57:44 +00003528
John McCalle3027922010-08-25 11:45:40 +00003529 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00003530 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00003531 }
3532
Richard Smith11562c52011-10-28 17:51:58 +00003533 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00003534}
Chris Lattner05706e882008-07-11 18:11:29 +00003535
Peter Collingbournee9200682011-05-13 03:29:01 +00003536bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003537 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00003538 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00003539
Peter Collingbournee9200682011-05-13 03:29:01 +00003540 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003541}
Chris Lattner05706e882008-07-11 18:11:29 +00003542
3543//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003544// Member Pointer Evaluation
3545//===----------------------------------------------------------------------===//
3546
3547namespace {
3548class MemberPointerExprEvaluator
3549 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3550 MemberPtr &Result;
3551
3552 bool Success(const ValueDecl *D) {
3553 Result = MemberPtr(D);
3554 return true;
3555 }
3556public:
3557
3558 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3559 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3560
Richard Smith2e312c82012-03-03 22:46:17 +00003561 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003562 Result.setFrom(V);
3563 return true;
3564 }
Richard Smithfddd3842011-12-30 21:15:51 +00003565 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003566 return Success((const ValueDecl*)0);
3567 }
3568
3569 bool VisitCastExpr(const CastExpr *E);
3570 bool VisitUnaryAddrOf(const UnaryOperator *E);
3571};
3572} // end anonymous namespace
3573
3574static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3575 EvalInfo &Info) {
3576 assert(E->isRValue() && E->getType()->isMemberPointerType());
3577 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3578}
3579
3580bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3581 switch (E->getCastKind()) {
3582 default:
3583 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3584
3585 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00003586 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00003587 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00003588
3589 case CK_BaseToDerivedMemberPointer: {
3590 if (!Visit(E->getSubExpr()))
3591 return false;
3592 if (E->path_empty())
3593 return true;
3594 // Base-to-derived member pointer casts store the path in derived-to-base
3595 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3596 // the wrong end of the derived->base arc, so stagger the path by one class.
3597 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3598 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3599 PathI != PathE; ++PathI) {
3600 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3601 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3602 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003603 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003604 }
3605 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3606 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003607 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003608 return true;
3609 }
3610
3611 case CK_DerivedToBaseMemberPointer:
3612 if (!Visit(E->getSubExpr()))
3613 return false;
3614 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3615 PathE = E->path_end(); PathI != PathE; ++PathI) {
3616 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3617 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3618 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003619 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003620 }
3621 return true;
3622 }
3623}
3624
3625bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3626 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3627 // member can be formed.
3628 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3629}
3630
3631//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00003632// Record Evaluation
3633//===----------------------------------------------------------------------===//
3634
3635namespace {
3636 class RecordExprEvaluator
3637 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3638 const LValue &This;
3639 APValue &Result;
3640 public:
3641
3642 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3643 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3644
Richard Smith2e312c82012-03-03 22:46:17 +00003645 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00003646 Result = V;
3647 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00003648 }
Richard Smithfddd3842011-12-30 21:15:51 +00003649 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00003650
Richard Smithe97cbd72011-11-11 04:05:33 +00003651 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00003652 bool VisitInitListExpr(const InitListExpr *E);
3653 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3654 };
3655}
3656
Richard Smithfddd3842011-12-30 21:15:51 +00003657/// Perform zero-initialization on an object of non-union class type.
3658/// C++11 [dcl.init]p5:
3659/// To zero-initialize an object or reference of type T means:
3660/// [...]
3661/// -- if T is a (possibly cv-qualified) non-union class type,
3662/// each non-static data member and each base-class subobject is
3663/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00003664static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3665 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00003666 const LValue &This, APValue &Result) {
3667 assert(!RD->isUnion() && "Expected non-union class type");
3668 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3669 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3670 std::distance(RD->field_begin(), RD->field_end()));
3671
John McCalld7bca762012-05-01 00:38:49 +00003672 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00003673 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3674
3675 if (CD) {
3676 unsigned Index = 0;
3677 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003678 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00003679 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3680 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00003681 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
3682 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003683 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00003684 Result.getStructBase(Index)))
3685 return false;
3686 }
3687 }
3688
Richard Smitha8105bc2012-01-06 16:39:00 +00003689 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3690 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00003691 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00003692 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00003693 continue;
3694
3695 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00003696 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00003697 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00003698
David Blaikie2d7c57e2012-04-30 02:36:29 +00003699 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00003700 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00003701 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00003702 return false;
3703 }
3704
3705 return true;
3706}
3707
3708bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3709 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00003710 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00003711 if (RD->isUnion()) {
3712 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3713 // object's first non-static named data member is zero-initialized
3714 RecordDecl::field_iterator I = RD->field_begin();
3715 if (I == RD->field_end()) {
3716 Result = APValue((const FieldDecl*)0);
3717 return true;
3718 }
3719
3720 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00003721 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00003722 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00003723 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00003724 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00003725 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00003726 }
3727
Richard Smith5d108602012-02-17 00:44:16 +00003728 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003729 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00003730 return false;
3731 }
3732
Richard Smitha8105bc2012-01-06 16:39:00 +00003733 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00003734}
3735
Richard Smithe97cbd72011-11-11 04:05:33 +00003736bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3737 switch (E->getCastKind()) {
3738 default:
3739 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3740
3741 case CK_ConstructorConversion:
3742 return Visit(E->getSubExpr());
3743
3744 case CK_DerivedToBase:
3745 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00003746 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003747 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00003748 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003749 if (!DerivedObject.isStruct())
3750 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00003751
3752 // Derived-to-base rvalue conversion: just slice off the derived part.
3753 APValue *Value = &DerivedObject;
3754 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3755 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3756 PathE = E->path_end(); PathI != PathE; ++PathI) {
3757 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3758 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3759 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3760 RD = Base;
3761 }
3762 Result = *Value;
3763 return true;
3764 }
3765 }
3766}
3767
Richard Smithd62306a2011-11-10 06:34:14 +00003768bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redle6c32e62012-02-19 14:53:49 +00003769 // Cannot constant-evaluate std::initializer_list inits.
3770 if (E->initializesStdInitializerList())
3771 return false;
3772
Richard Smithd62306a2011-11-10 06:34:14 +00003773 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00003774 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003775 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3776
3777 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00003778 const FieldDecl *Field = E->getInitializedFieldInUnion();
3779 Result = APValue(Field);
3780 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00003781 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00003782
3783 // If the initializer list for a union does not contain any elements, the
3784 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00003785 // FIXME: The element should be initialized from an initializer list.
3786 // Is this difference ever observable for initializer lists which
3787 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00003788 ImplicitValueInitExpr VIE(Field->getType());
3789 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3790
Richard Smithd62306a2011-11-10 06:34:14 +00003791 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00003792 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
3793 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00003794
3795 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
3796 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
3797 isa<CXXDefaultInitExpr>(InitExpr));
3798
Richard Smithb228a862012-02-15 02:18:13 +00003799 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00003800 }
3801
3802 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3803 "initializer list for class with base classes");
3804 Result = APValue(APValue::UninitStruct(), 0,
3805 std::distance(RD->field_begin(), RD->field_end()));
3806 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00003807 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003808 for (RecordDecl::field_iterator Field = RD->field_begin(),
3809 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3810 // Anonymous bit-fields are not considered members of the class for
3811 // purposes of aggregate initialization.
3812 if (Field->isUnnamedBitfield())
3813 continue;
3814
3815 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00003816
Richard Smith253c2a32012-01-27 01:14:48 +00003817 bool HaveInit = ElementNo < E->getNumInits();
3818
3819 // FIXME: Diagnostics here should point to the end of the initializer
3820 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00003821 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie40ed2972012-06-06 20:45:41 +00003822 Subobject, *Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00003823 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003824
3825 // Perform an implicit value-initialization for members beyond the end of
3826 // the initializer list.
3827 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00003828 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00003829
Richard Smith852c9db2013-04-20 22:23:05 +00003830 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
3831 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
3832 isa<CXXDefaultInitExpr>(Init));
3833
3834 if (!EvaluateInPlace(Result.getStructField(Field->getFieldIndex()), Info,
3835 Subobject, Init)) {
Richard Smith253c2a32012-01-27 01:14:48 +00003836 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00003837 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003838 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00003839 }
3840 }
3841
Richard Smith253c2a32012-01-27 01:14:48 +00003842 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003843}
3844
3845bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3846 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00003847 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
3848
Richard Smithfddd3842011-12-30 21:15:51 +00003849 bool ZeroInit = E->requiresZeroInitialization();
3850 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00003851 // If we've already performed zero-initialization, we're already done.
3852 if (!Result.isUninit())
3853 return true;
3854
Richard Smithfddd3842011-12-30 21:15:51 +00003855 if (ZeroInit)
3856 return ZeroInitialization(E);
3857
Richard Smithcc36f692011-12-22 02:22:31 +00003858 const CXXRecordDecl *RD = FD->getParent();
3859 if (RD->isUnion())
3860 Result = APValue((FieldDecl*)0);
3861 else
3862 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3863 std::distance(RD->field_begin(), RD->field_end()));
3864 return true;
3865 }
3866
Richard Smithd62306a2011-11-10 06:34:14 +00003867 const FunctionDecl *Definition = 0;
3868 FD->getBody(Definition);
3869
Richard Smith357362d2011-12-13 06:39:58 +00003870 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3871 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003872
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003873 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00003874 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00003875 if (const MaterializeTemporaryExpr *ME
3876 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3877 return Visit(ME->GetTemporaryExpr());
3878
Richard Smithfddd3842011-12-30 21:15:51 +00003879 if (ZeroInit && !ZeroInitialization(E))
3880 return false;
3881
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003882 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00003883 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003884 cast<CXXConstructorDecl>(Definition), Info,
3885 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00003886}
3887
3888static bool EvaluateRecord(const Expr *E, const LValue &This,
3889 APValue &Result, EvalInfo &Info) {
3890 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00003891 "can't evaluate expression as a record rvalue");
3892 return RecordExprEvaluator(Info, This, Result).Visit(E);
3893}
3894
3895//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003896// Temporary Evaluation
3897//
3898// Temporaries are represented in the AST as rvalues, but generally behave like
3899// lvalues. The full-object of which the temporary is a subobject is implicitly
3900// materialized so that a reference can bind to it.
3901//===----------------------------------------------------------------------===//
3902namespace {
3903class TemporaryExprEvaluator
3904 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3905public:
3906 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3907 LValueExprEvaluatorBaseTy(Info, Result) {}
3908
3909 /// Visit an expression which constructs the value of this temporary.
3910 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00003911 Result.set(E, Info.CurrentCall->Index);
3912 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00003913 }
3914
3915 bool VisitCastExpr(const CastExpr *E) {
3916 switch (E->getCastKind()) {
3917 default:
3918 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3919
3920 case CK_ConstructorConversion:
3921 return VisitConstructExpr(E->getSubExpr());
3922 }
3923 }
3924 bool VisitInitListExpr(const InitListExpr *E) {
3925 return VisitConstructExpr(E);
3926 }
3927 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3928 return VisitConstructExpr(E);
3929 }
3930 bool VisitCallExpr(const CallExpr *E) {
3931 return VisitConstructExpr(E);
3932 }
3933};
3934} // end anonymous namespace
3935
3936/// Evaluate an expression of record type as a temporary.
3937static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00003938 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00003939 return TemporaryExprEvaluator(Info, Result).Visit(E);
3940}
3941
3942//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003943// Vector Evaluation
3944//===----------------------------------------------------------------------===//
3945
3946namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003947 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00003948 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3949 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003950 public:
Mike Stump11289f42009-09-09 15:08:12 +00003951
Richard Smith2d406342011-10-22 21:10:00 +00003952 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3953 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00003954
Richard Smith2d406342011-10-22 21:10:00 +00003955 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3956 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3957 // FIXME: remove this APValue copy.
3958 Result = APValue(V.data(), V.size());
3959 return true;
3960 }
Richard Smith2e312c82012-03-03 22:46:17 +00003961 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00003962 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00003963 Result = V;
3964 return true;
3965 }
Richard Smithfddd3842011-12-30 21:15:51 +00003966 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00003967
Richard Smith2d406342011-10-22 21:10:00 +00003968 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00003969 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00003970 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00003971 bool VisitInitListExpr(const InitListExpr *E);
3972 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003973 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00003974 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00003975 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003976 };
3977} // end anonymous namespace
3978
3979static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003980 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00003981 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003982}
3983
Richard Smith2d406342011-10-22 21:10:00 +00003984bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3985 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00003986 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00003987
Richard Smith161f09a2011-12-06 22:44:34 +00003988 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00003989 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003990
Eli Friedmanc757de22011-03-25 00:43:55 +00003991 switch (E->getCastKind()) {
3992 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00003993 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00003994 if (SETy->isIntegerType()) {
3995 APSInt IntResult;
3996 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003997 return false;
Richard Smith2d406342011-10-22 21:10:00 +00003998 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00003999 } else if (SETy->isRealFloatingType()) {
4000 APFloat F(0.0);
4001 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004002 return false;
Richard Smith2d406342011-10-22 21:10:00 +00004003 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00004004 } else {
Richard Smith2d406342011-10-22 21:10:00 +00004005 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004006 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00004007
4008 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00004009 SmallVector<APValue, 4> Elts(NElts, Val);
4010 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00004011 }
Eli Friedman803acb32011-12-22 03:51:45 +00004012 case CK_BitCast: {
4013 // Evaluate the operand into an APInt we can extract from.
4014 llvm::APInt SValInt;
4015 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
4016 return false;
4017 // Extract the elements
4018 QualType EltTy = VTy->getElementType();
4019 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
4020 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
4021 SmallVector<APValue, 4> Elts;
4022 if (EltTy->isRealFloatingType()) {
4023 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00004024 unsigned FloatEltSize = EltSize;
4025 if (&Sem == &APFloat::x87DoubleExtended)
4026 FloatEltSize = 80;
4027 for (unsigned i = 0; i < NElts; i++) {
4028 llvm::APInt Elt;
4029 if (BigEndian)
4030 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
4031 else
4032 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00004033 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00004034 }
4035 } else if (EltTy->isIntegerType()) {
4036 for (unsigned i = 0; i < NElts; i++) {
4037 llvm::APInt Elt;
4038 if (BigEndian)
4039 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
4040 else
4041 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
4042 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
4043 }
4044 } else {
4045 return Error(E);
4046 }
4047 return Success(Elts, E);
4048 }
Eli Friedmanc757de22011-03-25 00:43:55 +00004049 default:
Richard Smith11562c52011-10-28 17:51:58 +00004050 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004051 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004052}
4053
Richard Smith2d406342011-10-22 21:10:00 +00004054bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004055VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00004056 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004057 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00004058 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00004059
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004060 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004061 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004062
Eli Friedmanb9c71292012-01-03 23:24:20 +00004063 // The number of initializers can be less than the number of
4064 // vector elements. For OpenCL, this can be due to nested vector
4065 // initialization. For GCC compatibility, missing trailing elements
4066 // should be initialized with zeroes.
4067 unsigned CountInits = 0, CountElts = 0;
4068 while (CountElts < NumElements) {
4069 // Handle nested vector initialization.
4070 if (CountInits < NumInits
4071 && E->getInit(CountInits)->getType()->isExtVectorType()) {
4072 APValue v;
4073 if (!EvaluateVector(E->getInit(CountInits), v, Info))
4074 return Error(E);
4075 unsigned vlen = v.getVectorLength();
4076 for (unsigned j = 0; j < vlen; j++)
4077 Elements.push_back(v.getVectorElt(j));
4078 CountElts += vlen;
4079 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004080 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00004081 if (CountInits < NumInits) {
4082 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00004083 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00004084 } else // trailing integer zero.
4085 sInt = Info.Ctx.MakeIntValue(0, EltTy);
4086 Elements.push_back(APValue(sInt));
4087 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004088 } else {
4089 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00004090 if (CountInits < NumInits) {
4091 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00004092 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00004093 } else // trailing float zero.
4094 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
4095 Elements.push_back(APValue(f));
4096 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00004097 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00004098 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004099 }
Richard Smith2d406342011-10-22 21:10:00 +00004100 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004101}
4102
Richard Smith2d406342011-10-22 21:10:00 +00004103bool
Richard Smithfddd3842011-12-30 21:15:51 +00004104VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00004105 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00004106 QualType EltTy = VT->getElementType();
4107 APValue ZeroElement;
4108 if (EltTy->isIntegerType())
4109 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
4110 else
4111 ZeroElement =
4112 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
4113
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004114 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00004115 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004116}
4117
Richard Smith2d406342011-10-22 21:10:00 +00004118bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00004119 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004120 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004121}
4122
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004123//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00004124// Array Evaluation
4125//===----------------------------------------------------------------------===//
4126
4127namespace {
4128 class ArrayExprEvaluator
4129 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00004130 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00004131 APValue &Result;
4132 public:
4133
Richard Smithd62306a2011-11-10 06:34:14 +00004134 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
4135 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00004136
4137 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00004138 assert((V.isArray() || V.isLValue()) &&
4139 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00004140 Result = V;
4141 return true;
4142 }
Richard Smithf3e9e432011-11-07 09:22:26 +00004143
Richard Smithfddd3842011-12-30 21:15:51 +00004144 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004145 const ConstantArrayType *CAT =
4146 Info.Ctx.getAsConstantArrayType(E->getType());
4147 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004148 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004149
4150 Result = APValue(APValue::UninitArray(), 0,
4151 CAT->getSize().getZExtValue());
4152 if (!Result.hasArrayFiller()) return true;
4153
Richard Smithfddd3842011-12-30 21:15:51 +00004154 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00004155 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00004156 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00004157 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00004158 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00004159 }
4160
Richard Smithf3e9e432011-11-07 09:22:26 +00004161 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00004162 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00004163 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
4164 const LValue &Subobject,
4165 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00004166 };
4167} // end anonymous namespace
4168
Richard Smithd62306a2011-11-10 06:34:14 +00004169static bool EvaluateArray(const Expr *E, const LValue &This,
4170 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00004171 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00004172 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00004173}
4174
4175bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
4176 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
4177 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004178 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00004179
Richard Smithca2cfbf2011-12-22 01:07:19 +00004180 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
4181 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00004182 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00004183 LValue LV;
4184 if (!EvaluateLValue(E->getInit(0), LV, Info))
4185 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004186 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00004187 LV.moveInto(Val);
4188 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00004189 }
4190
Richard Smith253c2a32012-01-27 01:14:48 +00004191 bool Success = true;
4192
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004193 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
4194 "zero-initialized array shouldn't have any initialized elts");
4195 APValue Filler;
4196 if (Result.isArray() && Result.hasArrayFiller())
4197 Filler = Result.getArrayFiller();
4198
Richard Smith9543c5e2013-04-22 14:44:29 +00004199 unsigned NumEltsToInit = E->getNumInits();
4200 unsigned NumElts = CAT->getSize().getZExtValue();
4201 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
4202
4203 // If the initializer might depend on the array index, run it for each
4204 // array element. For now, just whitelist non-class value-initialization.
4205 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
4206 NumEltsToInit = NumElts;
4207
4208 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004209
4210 // If the array was previously zero-initialized, preserve the
4211 // zero-initialized values.
4212 if (!Filler.isUninit()) {
4213 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
4214 Result.getArrayInitializedElt(I) = Filler;
4215 if (Result.hasArrayFiller())
4216 Result.getArrayFiller() = Filler;
4217 }
4218
Richard Smithd62306a2011-11-10 06:34:14 +00004219 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00004220 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00004221 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
4222 const Expr *Init =
4223 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00004224 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00004225 Info, Subobject, Init) ||
4226 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00004227 CAT->getElementType(), 1)) {
4228 if (!Info.keepEvaluatingAfterFailure())
4229 return false;
4230 Success = false;
4231 }
Richard Smithd62306a2011-11-10 06:34:14 +00004232 }
Richard Smithf3e9e432011-11-07 09:22:26 +00004233
Richard Smith9543c5e2013-04-22 14:44:29 +00004234 if (!Result.hasArrayFiller())
4235 return Success;
4236
4237 // If we get here, we have a trivial filler, which we can just evaluate
4238 // once and splat over the rest of the array elements.
4239 assert(FillerExpr && "no array filler for incomplete init list");
4240 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
4241 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00004242}
4243
Richard Smith027bf112011-11-17 22:56:20 +00004244bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00004245 return VisitCXXConstructExpr(E, This, &Result, E->getType());
4246}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004247
Richard Smith9543c5e2013-04-22 14:44:29 +00004248bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
4249 const LValue &Subobject,
4250 APValue *Value,
4251 QualType Type) {
4252 bool HadZeroInit = !Value->isUninit();
4253
4254 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
4255 unsigned N = CAT->getSize().getZExtValue();
4256
4257 // Preserve the array filler if we had prior zero-initialization.
4258 APValue Filler =
4259 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
4260 : APValue();
4261
4262 *Value = APValue(APValue::UninitArray(), N, N);
4263
4264 if (HadZeroInit)
4265 for (unsigned I = 0; I != N; ++I)
4266 Value->getArrayInitializedElt(I) = Filler;
4267
4268 // Initialize the elements.
4269 LValue ArrayElt = Subobject;
4270 ArrayElt.addArray(Info, E, CAT);
4271 for (unsigned I = 0; I != N; ++I)
4272 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
4273 CAT->getElementType()) ||
4274 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
4275 CAT->getElementType(), 1))
4276 return false;
4277
4278 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004279 }
Richard Smith027bf112011-11-17 22:56:20 +00004280
Richard Smith9543c5e2013-04-22 14:44:29 +00004281 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00004282 return Error(E);
4283
Richard Smith027bf112011-11-17 22:56:20 +00004284 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00004285
Richard Smithfddd3842011-12-30 21:15:51 +00004286 bool ZeroInit = E->requiresZeroInitialization();
4287 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00004288 if (HadZeroInit)
4289 return true;
4290
Richard Smithfddd3842011-12-30 21:15:51 +00004291 if (ZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00004292 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004293 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004294 }
4295
Richard Smithcc36f692011-12-22 02:22:31 +00004296 const CXXRecordDecl *RD = FD->getParent();
4297 if (RD->isUnion())
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004298 *Value = APValue((FieldDecl*)0);
Richard Smithcc36f692011-12-22 02:22:31 +00004299 else
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004300 *Value =
Richard Smithcc36f692011-12-22 02:22:31 +00004301 APValue(APValue::UninitStruct(), RD->getNumBases(),
4302 std::distance(RD->field_begin(), RD->field_end()));
4303 return true;
4304 }
4305
Richard Smith027bf112011-11-17 22:56:20 +00004306 const FunctionDecl *Definition = 0;
4307 FD->getBody(Definition);
4308
Richard Smith357362d2011-12-13 06:39:58 +00004309 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
4310 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004311
Richard Smith9eae7232012-01-12 18:54:33 +00004312 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00004313 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004314 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004315 return false;
4316 }
4317
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004318 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00004319 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00004320 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004321 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00004322}
4323
Richard Smithf3e9e432011-11-07 09:22:26 +00004324//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004325// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004326//
4327// As a GNU extension, we support casting pointers to sufficiently-wide integer
4328// types and back in constant folding. Integer values are thus represented
4329// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00004330//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004331
4332namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004333class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004334 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith2e312c82012-03-03 22:46:17 +00004335 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004336public:
Richard Smith2e312c82012-03-03 22:46:17 +00004337 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004338 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004339
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004340 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004341 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00004342 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004343 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004344 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004345 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004346 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00004347 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004348 return true;
4349 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004350 bool Success(const llvm::APSInt &SI, const Expr *E) {
4351 return Success(SI, E, Result);
4352 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004353
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004354 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00004355 assert(E->getType()->isIntegralOrEnumerationType() &&
4356 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004357 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004358 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00004359 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00004360 Result.getInt().setIsUnsigned(
4361 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004362 return true;
4363 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004364 bool Success(const llvm::APInt &I, const Expr *E) {
4365 return Success(I, E, Result);
4366 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004367
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004368 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00004369 assert(E->getType()->isIntegralOrEnumerationType() &&
4370 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00004371 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004372 return true;
4373 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004374 bool Success(uint64_t Value, const Expr *E) {
4375 return Success(Value, E, Result);
4376 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004377
Ken Dyckdbc01912011-03-11 02:13:43 +00004378 bool Success(CharUnits Size, const Expr *E) {
4379 return Success(Size.getQuantity(), E);
4380 }
4381
Richard Smith2e312c82012-03-03 22:46:17 +00004382 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00004383 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00004384 Result = V;
4385 return true;
4386 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004387 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00004388 }
Mike Stump11289f42009-09-09 15:08:12 +00004389
Richard Smithfddd3842011-12-30 21:15:51 +00004390 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00004391
Peter Collingbournee9200682011-05-13 03:29:01 +00004392 //===--------------------------------------------------------------------===//
4393 // Visitor Methods
4394 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004395
Chris Lattner7174bf32008-07-12 00:38:25 +00004396 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004397 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00004398 }
4399 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004400 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00004401 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004402
4403 bool CheckReferencedDecl(const Expr *E, const Decl *D);
4404 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004405 if (CheckReferencedDecl(E, E->getDecl()))
4406 return true;
4407
4408 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004409 }
4410 bool VisitMemberExpr(const MemberExpr *E) {
4411 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00004412 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004413 return true;
4414 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004415
4416 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004417 }
4418
Peter Collingbournee9200682011-05-13 03:29:01 +00004419 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00004420 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00004421 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00004422 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00004423
Peter Collingbournee9200682011-05-13 03:29:01 +00004424 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00004425 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00004426
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004427 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004428 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004429 }
Mike Stump11289f42009-09-09 15:08:12 +00004430
Ted Kremeneke65b0862012-03-06 20:05:56 +00004431 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4432 return Success(E->getValue(), E);
4433 }
4434
Richard Smith4ce706a2011-10-11 21:43:33 +00004435 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00004436 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004437 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00004438 }
4439
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004440 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004441 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004442 }
4443
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004444 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4445 return Success(E->getValue(), E);
4446 }
4447
Douglas Gregor29c42f22012-02-24 07:38:34 +00004448 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4449 return Success(E->getValue(), E);
4450 }
4451
John Wiegley6242b6a2011-04-28 00:16:57 +00004452 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4453 return Success(E->getValue(), E);
4454 }
4455
John Wiegleyf9f65842011-04-25 06:54:41 +00004456 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4457 return Success(E->getValue(), E);
4458 }
4459
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004460 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00004461 bool VisitUnaryImag(const UnaryOperator *E);
4462
Sebastian Redl5f0180d2010-09-10 20:55:47 +00004463 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00004464 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00004465
Chris Lattnerf8d7f722008-07-11 21:24:13 +00004466private:
Ken Dyck160146e2010-01-27 17:10:57 +00004467 CharUnits GetAlignOfExpr(const Expr *E);
4468 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00004469 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00004470 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00004471 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00004472};
Chris Lattner05706e882008-07-11 18:11:29 +00004473} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004474
Richard Smith11562c52011-10-28 17:51:58 +00004475/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4476/// produce either the integer value or a pointer.
4477///
4478/// GCC has a heinous extension which folds casts between pointer types and
4479/// pointer-sized integral types. We support this by allowing the evaluation of
4480/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4481/// Some simple arithmetic on such values is supported (they are treated much
4482/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00004483static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00004484 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004485 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004486 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00004487}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004488
Richard Smithf57d8cb2011-12-09 22:58:01 +00004489static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00004490 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004491 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00004492 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004493 if (!Val.isInt()) {
4494 // FIXME: It would be better to produce the diagnostic for casting
4495 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00004496 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004497 return false;
4498 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004499 Result = Val.getInt();
4500 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004501}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004502
Richard Smithf57d8cb2011-12-09 22:58:01 +00004503/// Check whether the given declaration can be directly converted to an integral
4504/// rvalue. If not, no diagnostic is produced; there are other things we can
4505/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004506bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00004507 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00004508 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004509 // Check for signedness/width mismatches between E type and ECD value.
4510 bool SameSign = (ECD->getInitVal().isSigned()
4511 == E->getType()->isSignedIntegerOrEnumerationType());
4512 bool SameWidth = (ECD->getInitVal().getBitWidth()
4513 == Info.Ctx.getIntWidth(E->getType()));
4514 if (SameSign && SameWidth)
4515 return Success(ECD->getInitVal(), E);
4516 else {
4517 // Get rid of mismatch (otherwise Success assertions will fail)
4518 // by computing a new value matching the type of E.
4519 llvm::APSInt Val = ECD->getInitVal();
4520 if (!SameSign)
4521 Val.setIsSigned(!ECD->getInitVal().isSigned());
4522 if (!SameWidth)
4523 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4524 return Success(Val, E);
4525 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00004526 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004527 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00004528}
4529
Chris Lattner86ee2862008-10-06 06:40:35 +00004530/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4531/// as GCC.
4532static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4533 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004534 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00004535 enum gcc_type_class {
4536 no_type_class = -1,
4537 void_type_class, integer_type_class, char_type_class,
4538 enumeral_type_class, boolean_type_class,
4539 pointer_type_class, reference_type_class, offset_type_class,
4540 real_type_class, complex_type_class,
4541 function_type_class, method_type_class,
4542 record_type_class, union_type_class,
4543 array_type_class, string_type_class,
4544 lang_type_class
4545 };
Mike Stump11289f42009-09-09 15:08:12 +00004546
4547 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00004548 // ideal, however it is what gcc does.
4549 if (E->getNumArgs() == 0)
4550 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00004551
Chris Lattner86ee2862008-10-06 06:40:35 +00004552 QualType ArgTy = E->getArg(0)->getType();
4553 if (ArgTy->isVoidType())
4554 return void_type_class;
4555 else if (ArgTy->isEnumeralType())
4556 return enumeral_type_class;
4557 else if (ArgTy->isBooleanType())
4558 return boolean_type_class;
4559 else if (ArgTy->isCharType())
4560 return string_type_class; // gcc doesn't appear to use char_type_class
4561 else if (ArgTy->isIntegerType())
4562 return integer_type_class;
4563 else if (ArgTy->isPointerType())
4564 return pointer_type_class;
4565 else if (ArgTy->isReferenceType())
4566 return reference_type_class;
4567 else if (ArgTy->isRealType())
4568 return real_type_class;
4569 else if (ArgTy->isComplexType())
4570 return complex_type_class;
4571 else if (ArgTy->isFunctionType())
4572 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00004573 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00004574 return record_type_class;
4575 else if (ArgTy->isUnionType())
4576 return union_type_class;
4577 else if (ArgTy->isArrayType())
4578 return array_type_class;
4579 else if (ArgTy->isUnionType())
4580 return union_type_class;
4581 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00004582 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00004583}
4584
Richard Smith5fab0c92011-12-28 19:48:30 +00004585/// EvaluateBuiltinConstantPForLValue - Determine the result of
4586/// __builtin_constant_p when applied to the given lvalue.
4587///
4588/// An lvalue is only "constant" if it is a pointer or reference to the first
4589/// character of a string literal.
4590template<typename LValue>
4591static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00004592 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00004593 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4594}
4595
4596/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4597/// GCC as we can manage.
4598static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4599 QualType ArgType = Arg->getType();
4600
4601 // __builtin_constant_p always has one operand. The rules which gcc follows
4602 // are not precisely documented, but are as follows:
4603 //
4604 // - If the operand is of integral, floating, complex or enumeration type,
4605 // and can be folded to a known value of that type, it returns 1.
4606 // - If the operand and can be folded to a pointer to the first character
4607 // of a string literal (or such a pointer cast to an integral type), it
4608 // returns 1.
4609 //
4610 // Otherwise, it returns 0.
4611 //
4612 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4613 // its support for this does not currently work.
4614 if (ArgType->isIntegralOrEnumerationType()) {
4615 Expr::EvalResult Result;
4616 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4617 return false;
4618
4619 APValue &V = Result.Val;
4620 if (V.getKind() == APValue::Int)
4621 return true;
4622
4623 return EvaluateBuiltinConstantPForLValue(V);
4624 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4625 return Arg->isEvaluatable(Ctx);
4626 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4627 LValue LV;
4628 Expr::EvalStatus Status;
4629 EvalInfo Info(Ctx, Status);
4630 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4631 : EvaluatePointer(Arg, LV, Info)) &&
4632 !Status.HasSideEffects)
4633 return EvaluateBuiltinConstantPForLValue(LV);
4634 }
4635
4636 // Anything else isn't considered to be sufficiently constant.
4637 return false;
4638}
4639
John McCall95007602010-05-10 23:27:23 +00004640/// Retrieves the "underlying object type" of the given expression,
4641/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00004642QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4643 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4644 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00004645 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00004646 } else if (const Expr *E = B.get<const Expr*>()) {
4647 if (isa<CompoundLiteralExpr>(E))
4648 return E->getType();
John McCall95007602010-05-10 23:27:23 +00004649 }
4650
4651 return QualType();
4652}
4653
Peter Collingbournee9200682011-05-13 03:29:01 +00004654bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00004655 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00004656
4657 {
4658 // The operand of __builtin_object_size is never evaluated for side-effects.
4659 // If there are any, but we can determine the pointed-to object anyway, then
4660 // ignore the side-effects.
4661 SpeculativeEvaluationRAII SpeculativeEval(Info);
4662 if (!EvaluatePointer(E->getArg(0), Base, Info))
4663 return false;
4664 }
John McCall95007602010-05-10 23:27:23 +00004665
4666 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00004667 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00004668
Richard Smithce40ad62011-11-12 22:28:03 +00004669 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00004670 if (T.isNull() ||
4671 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00004672 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00004673 T->isVariablyModifiedType() ||
4674 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004675 return Error(E);
John McCall95007602010-05-10 23:27:23 +00004676
4677 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4678 CharUnits Offset = Base.getLValueOffset();
4679
4680 if (!Offset.isNegative() && Offset <= Size)
4681 Size -= Offset;
4682 else
4683 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00004684 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00004685}
4686
Peter Collingbournee9200682011-05-13 03:29:01 +00004687bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith01ba47d2012-04-13 00:45:38 +00004688 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004689 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00004690 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00004691
4692 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00004693 if (TryEvaluateBuiltinObjectSize(E))
4694 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00004695
Richard Smith0421ce72012-08-07 04:16:51 +00004696 // If evaluating the argument has side-effects, we can't determine the size
4697 // of the object, and so we lower it to unknown now. CodeGen relies on us to
4698 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00004699 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00004700 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00004701 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00004702 return Success(0, E);
4703 }
Mike Stump876387b2009-10-27 22:09:17 +00004704
Richard Smith01ade172012-05-23 04:13:20 +00004705 // Expression had no side effects, but we couldn't statically determine the
4706 // size of the referenced object.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004707 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00004708 }
4709
Benjamin Kramera801f4a2012-10-06 14:42:22 +00004710 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00004711 case Builtin::BI__builtin_bswap32:
4712 case Builtin::BI__builtin_bswap64: {
4713 APSInt Val;
4714 if (!EvaluateInteger(E->getArg(0), Val, Info))
4715 return false;
4716
4717 return Success(Val.byteSwap(), E);
4718 }
4719
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004720 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004721 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00004722
Richard Smith5fab0c92011-12-28 19:48:30 +00004723 case Builtin::BI__builtin_constant_p:
4724 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smith10c7c902011-12-09 02:04:48 +00004725
Chris Lattnerd545ad12009-09-23 06:06:36 +00004726 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00004727 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00004728 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00004729 return Success(Operand, E);
4730 }
Eli Friedmand5c93992010-02-13 00:10:10 +00004731
4732 case Builtin::BI__builtin_expect:
4733 return Visit(E->getArg(0));
Richard Smith9cf080f2012-01-18 03:06:12 +00004734
Douglas Gregor6a6dac22010-09-10 06:27:15 +00004735 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00004736 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004737 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00004738 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00004739 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4740 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00004741 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00004742 // Fall through.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00004743 case Builtin::BI__builtin_strlen:
4744 // As an extension, we support strlen() and __builtin_strlen() as constant
4745 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00004746 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00004747 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4748 // The string literal may have embedded null characters. Find the first
4749 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004750 StringRef Str = S->getString();
4751 StringRef::size_type Pos = Str.find(0);
4752 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00004753 Str = Str.substr(0, Pos);
4754
4755 return Success(Str.size(), E);
4756 }
4757
Richard Smithf57d8cb2011-12-09 22:58:01 +00004758 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00004759
Richard Smith01ba47d2012-04-13 00:45:38 +00004760 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00004761 case Builtin::BI__atomic_is_lock_free:
4762 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00004763 APSInt SizeVal;
4764 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4765 return false;
4766
4767 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4768 // of two less than the maximum inline atomic width, we know it is
4769 // lock-free. If the size isn't a power of two, or greater than the
4770 // maximum alignment where we promote atomics, we know it is not lock-free
4771 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4772 // the answer can only be determined at runtime; for example, 16-byte
4773 // atomics have lock-free implementations on some, but not all,
4774 // x86-64 processors.
4775
4776 // Check power-of-two.
4777 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00004778 if (Size.isPowerOfTwo()) {
4779 // Check against inlining width.
4780 unsigned InlineWidthBits =
4781 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4782 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
4783 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
4784 Size == CharUnits::One() ||
4785 E->getArg(1)->isNullPointerConstant(Info.Ctx,
4786 Expr::NPC_NeverValueDependent))
4787 // OK, we will inline appropriately-aligned operations of this size,
4788 // and _Atomic(T) is appropriately-aligned.
4789 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00004790
Richard Smith01ba47d2012-04-13 00:45:38 +00004791 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
4792 castAs<PointerType>()->getPointeeType();
4793 if (!PointeeType->isIncompleteType() &&
4794 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
4795 // OK, we will inline operations on this object.
4796 return Success(1, E);
4797 }
4798 }
4799 }
Eli Friedmana4c26022011-10-17 21:44:23 +00004800
Richard Smith01ba47d2012-04-13 00:45:38 +00004801 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
4802 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00004803 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004804 }
Chris Lattner7174bf32008-07-12 00:38:25 +00004805}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004806
Richard Smith8b3497e2011-10-31 01:37:14 +00004807static bool HasSameBase(const LValue &A, const LValue &B) {
4808 if (!A.getLValueBase())
4809 return !B.getLValueBase();
4810 if (!B.getLValueBase())
4811 return false;
4812
Richard Smithce40ad62011-11-12 22:28:03 +00004813 if (A.getLValueBase().getOpaqueValue() !=
4814 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00004815 const Decl *ADecl = GetLValueBaseDecl(A);
4816 if (!ADecl)
4817 return false;
4818 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00004819 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00004820 return false;
4821 }
4822
4823 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00004824 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00004825}
4826
Richard Smithc8042322012-02-01 05:53:12 +00004827/// Perform the given integer operation, which is known to need at most BitWidth
4828/// bits, and check for overflow in the original type (if that type was not an
4829/// unsigned type).
4830template<typename Operation>
4831static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4832 const APSInt &LHS, const APSInt &RHS,
4833 unsigned BitWidth, Operation Op) {
4834 if (LHS.isUnsigned())
4835 return Op(LHS, RHS);
4836
4837 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4838 APSInt Result = Value.trunc(LHS.getBitWidth());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00004839 if (Result.extend(BitWidth) != Value) {
4840 if (Info.getIntOverflowCheckMode())
4841 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
4842 diag::warn_integer_constant_overflow)
4843 << Result.toString(10) << E->getType();
4844 else
4845 HandleOverflow(Info, E, Value, E->getType());
4846 }
Richard Smithc8042322012-02-01 05:53:12 +00004847 return Result;
4848}
4849
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004850namespace {
Richard Smith11562c52011-10-28 17:51:58 +00004851
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004852/// \brief Data recursive integer evaluator of certain binary operators.
4853///
4854/// We use a data recursive algorithm for binary operators so that we are able
4855/// to handle extreme cases of chained binary operators without causing stack
4856/// overflow.
4857class DataRecursiveIntBinOpEvaluator {
4858 struct EvalResult {
4859 APValue Val;
4860 bool Failed;
4861
4862 EvalResult() : Failed(false) { }
4863
4864 void swap(EvalResult &RHS) {
4865 Val.swap(RHS.Val);
4866 Failed = RHS.Failed;
4867 RHS.Failed = false;
4868 }
4869 };
4870
4871 struct Job {
4872 const Expr *E;
4873 EvalResult LHSResult; // meaningful only for binary operator expression.
4874 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
4875
4876 Job() : StoredInfo(0) { }
4877 void startSpeculativeEval(EvalInfo &Info) {
4878 OldEvalStatus = Info.EvalStatus;
4879 Info.EvalStatus.Diag = 0;
4880 StoredInfo = &Info;
4881 }
4882 ~Job() {
4883 if (StoredInfo) {
4884 StoredInfo->EvalStatus = OldEvalStatus;
4885 }
4886 }
4887 private:
4888 EvalInfo *StoredInfo; // non-null if status changed.
4889 Expr::EvalStatus OldEvalStatus;
4890 };
4891
4892 SmallVector<Job, 16> Queue;
4893
4894 IntExprEvaluator &IntEval;
4895 EvalInfo &Info;
4896 APValue &FinalResult;
4897
4898public:
4899 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
4900 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
4901
4902 /// \brief True if \param E is a binary operator that we are going to handle
4903 /// data recursively.
4904 /// We handle binary operators that are comma, logical, or that have operands
4905 /// with integral or enumeration type.
4906 static bool shouldEnqueue(const BinaryOperator *E) {
4907 return E->getOpcode() == BO_Comma ||
4908 E->isLogicalOp() ||
4909 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4910 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00004911 }
4912
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004913 bool Traverse(const BinaryOperator *E) {
4914 enqueue(E);
4915 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00004916 while (!Queue.empty())
4917 process(PrevResult);
4918
4919 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004920
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004921 FinalResult.swap(PrevResult.Val);
4922 return true;
4923 }
4924
4925private:
4926 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
4927 return IntEval.Success(Value, E, Result);
4928 }
4929 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
4930 return IntEval.Success(Value, E, Result);
4931 }
4932 bool Error(const Expr *E) {
4933 return IntEval.Error(E);
4934 }
4935 bool Error(const Expr *E, diag::kind D) {
4936 return IntEval.Error(E, D);
4937 }
4938
4939 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4940 return Info.CCEDiag(E, D);
4941 }
4942
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00004943 // \brief Returns true if visiting the RHS is necessary, false otherwise.
4944 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004945 bool &SuppressRHSDiags);
4946
4947 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4948 const BinaryOperator *E, APValue &Result);
4949
4950 void EvaluateExpr(const Expr *E, EvalResult &Result) {
4951 Result.Failed = !Evaluate(Result.Val, Info, E);
4952 if (Result.Failed)
4953 Result.Val = APValue();
4954 }
4955
Richard Trieuba4d0872012-03-21 23:30:30 +00004956 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004957
4958 void enqueue(const Expr *E) {
4959 E = E->IgnoreParens();
4960 Queue.resize(Queue.size()+1);
4961 Queue.back().E = E;
4962 Queue.back().Kind = Job::AnyExprKind;
4963 }
4964};
4965
4966}
4967
4968bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00004969 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004970 bool &SuppressRHSDiags) {
4971 if (E->getOpcode() == BO_Comma) {
4972 // Ignore LHS but note if we could not evaluate it.
4973 if (LHSResult.Failed)
4974 Info.EvalStatus.HasSideEffects = true;
4975 return true;
4976 }
4977
4978 if (E->isLogicalOp()) {
4979 bool lhsResult;
4980 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004981 // We were able to evaluate the LHS, see if we can get away with not
4982 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004983 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00004984 Success(lhsResult, E, LHSResult.Val);
4985 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004986 }
4987 } else {
4988 // Since we weren't able to evaluate the left hand side, it
4989 // must have had side effects.
4990 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004991
4992 // We can't evaluate the LHS; however, sometimes the result
4993 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4994 // Don't ignore RHS and suppress diagnostics from this arm.
4995 SuppressRHSDiags = true;
4996 }
4997
4998 return true;
4999 }
5000
5001 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5002 E->getRHS()->getType()->isIntegralOrEnumerationType());
5003
5004 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005005 return false; // Ignore RHS;
5006
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005007 return true;
5008}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005009
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005010bool DataRecursiveIntBinOpEvaluator::
5011 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
5012 const BinaryOperator *E, APValue &Result) {
5013 if (E->getOpcode() == BO_Comma) {
5014 if (RHSResult.Failed)
5015 return false;
5016 Result = RHSResult.Val;
5017 return true;
5018 }
5019
5020 if (E->isLogicalOp()) {
5021 bool lhsResult, rhsResult;
5022 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
5023 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
5024
5025 if (LHSIsOK) {
5026 if (RHSIsOK) {
5027 if (E->getOpcode() == BO_LOr)
5028 return Success(lhsResult || rhsResult, E, Result);
5029 else
5030 return Success(lhsResult && rhsResult, E, Result);
5031 }
5032 } else {
5033 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005034 // We can't evaluate the LHS; however, sometimes the result
5035 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
5036 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005037 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005038 }
5039 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005040
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005041 return false;
5042 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005043
5044 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5045 E->getRHS()->getType()->isIntegralOrEnumerationType());
5046
5047 if (LHSResult.Failed || RHSResult.Failed)
5048 return false;
5049
5050 const APValue &LHSVal = LHSResult.Val;
5051 const APValue &RHSVal = RHSResult.Val;
5052
5053 // Handle cases like (unsigned long)&a + 4.
5054 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
5055 Result = LHSVal;
5056 CharUnits AdditionalOffset = CharUnits::fromQuantity(
5057 RHSVal.getInt().getZExtValue());
5058 if (E->getOpcode() == BO_Add)
5059 Result.getLValueOffset() += AdditionalOffset;
5060 else
5061 Result.getLValueOffset() -= AdditionalOffset;
5062 return true;
5063 }
5064
5065 // Handle cases like 4 + (unsigned long)&a
5066 if (E->getOpcode() == BO_Add &&
5067 RHSVal.isLValue() && LHSVal.isInt()) {
5068 Result = RHSVal;
5069 Result.getLValueOffset() += CharUnits::fromQuantity(
5070 LHSVal.getInt().getZExtValue());
5071 return true;
5072 }
5073
5074 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
5075 // Handle (intptr_t)&&A - (intptr_t)&&B.
5076 if (!LHSVal.getLValueOffset().isZero() ||
5077 !RHSVal.getLValueOffset().isZero())
5078 return false;
5079 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
5080 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
5081 if (!LHSExpr || !RHSExpr)
5082 return false;
5083 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
5084 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
5085 if (!LHSAddrExpr || !RHSAddrExpr)
5086 return false;
5087 // Make sure both labels come from the same function.
5088 if (LHSAddrExpr->getLabel()->getDeclContext() !=
5089 RHSAddrExpr->getLabel()->getDeclContext())
5090 return false;
5091 Result = APValue(LHSAddrExpr, RHSAddrExpr);
5092 return true;
5093 }
5094
5095 // All the following cases expect both operands to be an integer
5096 if (!LHSVal.isInt() || !RHSVal.isInt())
5097 return Error(E);
5098
5099 const APSInt &LHS = LHSVal.getInt();
5100 APSInt RHS = RHSVal.getInt();
5101
5102 switch (E->getOpcode()) {
5103 default:
5104 return Error(E);
5105 case BO_Mul:
5106 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
5107 LHS.getBitWidth() * 2,
5108 std::multiplies<APSInt>()), E,
5109 Result);
5110 case BO_Add:
5111 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
5112 LHS.getBitWidth() + 1,
5113 std::plus<APSInt>()), E, Result);
5114 case BO_Sub:
5115 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
5116 LHS.getBitWidth() + 1,
5117 std::minus<APSInt>()), E, Result);
5118 case BO_And: return Success(LHS & RHS, E, Result);
5119 case BO_Xor: return Success(LHS ^ RHS, E, Result);
5120 case BO_Or: return Success(LHS | RHS, E, Result);
5121 case BO_Div:
5122 case BO_Rem:
5123 if (RHS == 0)
5124 return Error(E, diag::note_expr_divide_by_zero);
5125 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
5126 // not actually undefined behavior in C++11 due to a language defect.
5127 if (RHS.isNegative() && RHS.isAllOnesValue() &&
5128 LHS.isSigned() && LHS.isMinSignedValue())
5129 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
5130 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
5131 Result);
5132 case BO_Shl: {
David Tweed042e0882013-01-07 16:43:27 +00005133 if (Info.getLangOpts().OpenCL)
5134 // OpenCL 6.3j: shift values are effectively % word size of LHS.
Joey Gouly0942e0b2013-01-29 15:09:40 +00005135 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
David Tweed042e0882013-01-07 16:43:27 +00005136 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
5137 RHS.isUnsigned());
5138 else if (RHS.isSigned() && RHS.isNegative()) {
5139 // During constant-folding, a negative shift is an opposite shift. Such
5140 // a shift is not a constant expression.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005141 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
5142 RHS = -RHS;
5143 goto shift_right;
5144 }
5145
5146 shift_left:
5147 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
5148 // the shifted type.
5149 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
5150 if (SA != RHS) {
5151 CCEDiag(E, diag::note_constexpr_large_shift)
5152 << RHS << E->getType() << LHS.getBitWidth();
5153 } else if (LHS.isSigned()) {
5154 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
5155 // operand, and must not overflow the corresponding unsigned type.
5156 if (LHS.isNegative())
5157 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
5158 else if (LHS.countLeadingZeros() < SA)
5159 CCEDiag(E, diag::note_constexpr_lshift_discards);
5160 }
5161
5162 return Success(LHS << SA, E, Result);
5163 }
5164 case BO_Shr: {
David Tweed042e0882013-01-07 16:43:27 +00005165 if (Info.getLangOpts().OpenCL)
5166 // OpenCL 6.3j: shift values are effectively % word size of LHS.
Joey Gouly0942e0b2013-01-29 15:09:40 +00005167 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
David Tweed042e0882013-01-07 16:43:27 +00005168 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
5169 RHS.isUnsigned());
5170 else if (RHS.isSigned() && RHS.isNegative()) {
5171 // During constant-folding, a negative shift is an opposite shift. Such a
5172 // shift is not a constant expression.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005173 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
5174 RHS = -RHS;
5175 goto shift_left;
5176 }
5177
5178 shift_right:
5179 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
5180 // shifted type.
5181 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
5182 if (SA != RHS)
5183 CCEDiag(E, diag::note_constexpr_large_shift)
5184 << RHS << E->getType() << LHS.getBitWidth();
5185
5186 return Success(LHS >> SA, E, Result);
5187 }
5188
5189 case BO_LT: return Success(LHS < RHS, E, Result);
5190 case BO_GT: return Success(LHS > RHS, E, Result);
5191 case BO_LE: return Success(LHS <= RHS, E, Result);
5192 case BO_GE: return Success(LHS >= RHS, E, Result);
5193 case BO_EQ: return Success(LHS == RHS, E, Result);
5194 case BO_NE: return Success(LHS != RHS, E, Result);
5195 }
5196}
5197
Richard Trieuba4d0872012-03-21 23:30:30 +00005198void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005199 Job &job = Queue.back();
5200
5201 switch (job.Kind) {
5202 case Job::AnyExprKind: {
5203 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
5204 if (shouldEnqueue(Bop)) {
5205 job.Kind = Job::BinOpKind;
5206 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00005207 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005208 }
5209 }
5210
5211 EvaluateExpr(job.E, Result);
5212 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005213 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005214 }
5215
5216 case Job::BinOpKind: {
5217 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005218 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005219 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005220 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005221 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005222 }
5223 if (SuppressRHSDiags)
5224 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005225 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005226 job.Kind = Job::BinOpVisitedLHSKind;
5227 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00005228 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005229 }
5230
5231 case Job::BinOpVisitedLHSKind: {
5232 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
5233 EvalResult RHS;
5234 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00005235 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005236 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005237 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005238 }
5239 }
5240
5241 llvm_unreachable("Invalid Job::Kind!");
5242}
5243
5244bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5245 if (E->isAssignmentOp())
5246 return Error(E);
5247
5248 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
5249 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00005250
Anders Carlssonacc79812008-11-16 07:17:21 +00005251 QualType LHSTy = E->getLHS()->getType();
5252 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005253
5254 if (LHSTy->isAnyComplexType()) {
5255 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00005256 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005257
Richard Smith253c2a32012-01-27 01:14:48 +00005258 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
5259 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005260 return false;
5261
Richard Smith253c2a32012-01-27 01:14:48 +00005262 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005263 return false;
5264
5265 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00005266 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005267 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00005268 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005269 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
5270
John McCalle3027922010-08-25 11:45:40 +00005271 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005272 return Success((CR_r == APFloat::cmpEqual &&
5273 CR_i == APFloat::cmpEqual), E);
5274 else {
John McCalle3027922010-08-25 11:45:40 +00005275 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005276 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00005277 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00005278 CR_r == APFloat::cmpLessThan ||
5279 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00005280 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00005281 CR_i == APFloat::cmpLessThan ||
5282 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005283 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005284 } else {
John McCalle3027922010-08-25 11:45:40 +00005285 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005286 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
5287 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
5288 else {
John McCalle3027922010-08-25 11:45:40 +00005289 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005290 "Invalid compex comparison.");
5291 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
5292 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
5293 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005294 }
5295 }
Mike Stump11289f42009-09-09 15:08:12 +00005296
Anders Carlssonacc79812008-11-16 07:17:21 +00005297 if (LHSTy->isRealFloatingType() &&
5298 RHSTy->isRealFloatingType()) {
5299 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00005300
Richard Smith253c2a32012-01-27 01:14:48 +00005301 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
5302 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00005303 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005304
Richard Smith253c2a32012-01-27 01:14:48 +00005305 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00005306 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005307
Anders Carlssonacc79812008-11-16 07:17:21 +00005308 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00005309
Anders Carlssonacc79812008-11-16 07:17:21 +00005310 switch (E->getOpcode()) {
5311 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005312 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00005313 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005314 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00005315 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005316 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00005317 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005318 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00005319 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00005320 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005321 E);
John McCalle3027922010-08-25 11:45:40 +00005322 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005323 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00005324 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00005325 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00005326 || CR == APFloat::cmpLessThan
5327 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00005328 }
Anders Carlssonacc79812008-11-16 07:17:21 +00005329 }
Mike Stump11289f42009-09-09 15:08:12 +00005330
Eli Friedmana38da572009-04-28 19:17:36 +00005331 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00005332 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00005333 LValue LHSValue, RHSValue;
5334
5335 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
5336 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005337 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005338
Richard Smith253c2a32012-01-27 01:14:48 +00005339 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005340 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005341
Richard Smith8b3497e2011-10-31 01:37:14 +00005342 // Reject differing bases from the normal codepath; we special-case
5343 // comparisons to null.
5344 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005345 if (E->getOpcode() == BO_Sub) {
5346 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005347 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
5348 return false;
5349 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00005350 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005351 if (!LHSExpr || !RHSExpr)
5352 return false;
5353 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
5354 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
5355 if (!LHSAddrExpr || !RHSAddrExpr)
5356 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005357 // Make sure both labels come from the same function.
5358 if (LHSAddrExpr->getLabel()->getDeclContext() !=
5359 RHSAddrExpr->getLabel()->getDeclContext())
5360 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005361 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005362 return true;
5363 }
Richard Smith83c68212011-10-31 05:11:32 +00005364 // Inequalities and subtractions between unrelated pointers have
5365 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00005366 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005367 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00005368 // A constant address may compare equal to the address of a symbol.
5369 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00005370 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00005371 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
5372 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005373 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005374 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00005375 // distinct addresses. In clang, the result of such a comparison is
5376 // unspecified, so it is not a constant expression. However, we do know
5377 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00005378 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
5379 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005380 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005381 // We can't tell whether weak symbols will end up pointing to the same
5382 // object.
5383 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005384 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005385 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00005386 // (Note that clang defaults to -fmerge-all-constants, which can
5387 // lead to inconsistent results for comparisons involving the address
5388 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00005389 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00005390 }
Eli Friedman64004332009-03-23 04:38:34 +00005391
Richard Smith1b470412012-02-01 08:10:20 +00005392 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
5393 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
5394
Richard Smith84f6dcf2012-02-02 01:16:57 +00005395 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
5396 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
5397
John McCalle3027922010-08-25 11:45:40 +00005398 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00005399 // C++11 [expr.add]p6:
5400 // Unless both pointers point to elements of the same array object, or
5401 // one past the last element of the array object, the behavior is
5402 // undefined.
5403 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5404 !AreElementsOfSameArray(getType(LHSValue.Base),
5405 LHSDesignator, RHSDesignator))
5406 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
5407
Chris Lattner882bdf22010-04-20 17:13:14 +00005408 QualType Type = E->getLHS()->getType();
5409 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005410
Richard Smithd62306a2011-11-10 06:34:14 +00005411 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00005412 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00005413 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005414
Richard Smith1b470412012-02-01 08:10:20 +00005415 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
5416 // and produce incorrect results when it overflows. Such behavior
5417 // appears to be non-conforming, but is common, so perhaps we should
5418 // assume the standard intended for such cases to be undefined behavior
5419 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00005420
Richard Smith1b470412012-02-01 08:10:20 +00005421 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
5422 // overflow in the final conversion to ptrdiff_t.
5423 APSInt LHS(
5424 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
5425 APSInt RHS(
5426 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
5427 APSInt ElemSize(
5428 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
5429 APSInt TrueResult = (LHS - RHS) / ElemSize;
5430 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
5431
5432 if (Result.extend(65) != TrueResult)
5433 HandleOverflow(Info, E, TrueResult, E->getType());
5434 return Success(Result, E);
5435 }
Richard Smithde21b242012-01-31 06:41:30 +00005436
5437 // C++11 [expr.rel]p3:
5438 // Pointers to void (after pointer conversions) can be compared, with a
5439 // result defined as follows: If both pointers represent the same
5440 // address or are both the null pointer value, the result is true if the
5441 // operator is <= or >= and false otherwise; otherwise the result is
5442 // unspecified.
5443 // We interpret this as applying to pointers to *cv* void.
5444 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00005445 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00005446 CCEDiag(E, diag::note_constexpr_void_comparison);
5447
Richard Smith84f6dcf2012-02-02 01:16:57 +00005448 // C++11 [expr.rel]p2:
5449 // - If two pointers point to non-static data members of the same object,
5450 // or to subobjects or array elements fo such members, recursively, the
5451 // pointer to the later declared member compares greater provided the
5452 // two members have the same access control and provided their class is
5453 // not a union.
5454 // [...]
5455 // - Otherwise pointer comparisons are unspecified.
5456 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5457 E->isRelationalOp()) {
5458 bool WasArrayIndex;
5459 unsigned Mismatch =
5460 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5461 RHSDesignator, WasArrayIndex);
5462 // At the point where the designators diverge, the comparison has a
5463 // specified value if:
5464 // - we are comparing array indices
5465 // - we are comparing fields of a union, or fields with the same access
5466 // Otherwise, the result is unspecified and thus the comparison is not a
5467 // constant expression.
5468 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5469 Mismatch < RHSDesignator.Entries.size()) {
5470 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5471 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5472 if (!LF && !RF)
5473 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5474 else if (!LF)
5475 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5476 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5477 << RF->getParent() << RF;
5478 else if (!RF)
5479 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5480 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
5481 << LF->getParent() << LF;
5482 else if (!LF->getParent()->isUnion() &&
5483 LF->getAccess() != RF->getAccess())
5484 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
5485 << LF << LF->getAccess() << RF << RF->getAccess()
5486 << LF->getParent();
5487 }
5488 }
5489
Eli Friedman6c31cb42012-04-16 04:30:08 +00005490 // The comparison here must be unsigned, and performed with the same
5491 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00005492 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
5493 uint64_t CompareLHS = LHSOffset.getQuantity();
5494 uint64_t CompareRHS = RHSOffset.getQuantity();
5495 assert(PtrSize <= 64 && "Unexpected pointer width");
5496 uint64_t Mask = ~0ULL >> (64 - PtrSize);
5497 CompareLHS &= Mask;
5498 CompareRHS &= Mask;
5499
Eli Friedman2f5b7c52012-04-16 19:23:57 +00005500 // If there is a base and this is a relational operator, we can only
5501 // compare pointers within the object in question; otherwise, the result
5502 // depends on where the object is located in memory.
5503 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
5504 QualType BaseTy = getType(LHSValue.Base);
5505 if (BaseTy->isIncompleteType())
5506 return Error(E);
5507 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
5508 uint64_t OffsetLimit = Size.getQuantity();
5509 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
5510 return Error(E);
5511 }
5512
Richard Smith8b3497e2011-10-31 01:37:14 +00005513 switch (E->getOpcode()) {
5514 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00005515 case BO_LT: return Success(CompareLHS < CompareRHS, E);
5516 case BO_GT: return Success(CompareLHS > CompareRHS, E);
5517 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
5518 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
5519 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
5520 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00005521 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005522 }
5523 }
Richard Smith7bb00672012-02-01 01:42:44 +00005524
5525 if (LHSTy->isMemberPointerType()) {
5526 assert(E->isEqualityOp() && "unexpected member pointer operation");
5527 assert(RHSTy->isMemberPointerType() && "invalid comparison");
5528
5529 MemberPtr LHSValue, RHSValue;
5530
5531 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
5532 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5533 return false;
5534
5535 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5536 return false;
5537
5538 // C++11 [expr.eq]p2:
5539 // If both operands are null, they compare equal. Otherwise if only one is
5540 // null, they compare unequal.
5541 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
5542 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
5543 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5544 }
5545
5546 // Otherwise if either is a pointer to a virtual member function, the
5547 // result is unspecified.
5548 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
5549 if (MD->isVirtual())
5550 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5551 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
5552 if (MD->isVirtual())
5553 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5554
5555 // Otherwise they compare equal if and only if they would refer to the
5556 // same member of the same most derived object or the same subobject if
5557 // they were dereferenced with a hypothetical object of the associated
5558 // class type.
5559 bool Equal = LHSValue == RHSValue;
5560 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5561 }
5562
Richard Smithab44d9b2012-02-14 22:35:28 +00005563 if (LHSTy->isNullPtrType()) {
5564 assert(E->isComparisonOp() && "unexpected nullptr operation");
5565 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
5566 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
5567 // are compared, the result is true of the operator is <=, >= or ==, and
5568 // false otherwise.
5569 BinaryOperator::Opcode Opcode = E->getOpcode();
5570 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
5571 }
5572
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005573 assert((!LHSTy->isIntegralOrEnumerationType() ||
5574 !RHSTy->isIntegralOrEnumerationType()) &&
5575 "DataRecursiveIntBinOpEvaluator should have handled integral types");
5576 // We can't continue from here for non-integral types.
5577 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00005578}
5579
Ken Dyck160146e2010-01-27 17:10:57 +00005580CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00005581 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
5582 // result shall be the alignment of the referenced type."
5583 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5584 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00005585
5586 // __alignof is defined to return the preferred alignment.
5587 return Info.Ctx.toCharUnitsFromBits(
5588 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00005589}
5590
Ken Dyck160146e2010-01-27 17:10:57 +00005591CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00005592 E = E->IgnoreParens();
5593
5594 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00005595 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00005596 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00005597 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5598 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00005599
Chris Lattner68061312009-01-24 21:53:27 +00005600 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00005601 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5602 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00005603
Chris Lattner24aeeab2009-01-24 21:09:06 +00005604 return GetAlignOfType(E->getType());
5605}
5606
5607
Peter Collingbournee190dee2011-03-11 19:24:49 +00005608/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5609/// a result as the expression's type.
5610bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5611 const UnaryExprOrTypeTraitExpr *E) {
5612 switch(E->getKind()) {
5613 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00005614 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00005615 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00005616 else
Ken Dyckdbc01912011-03-11 02:13:43 +00005617 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00005618 }
Eli Friedman64004332009-03-23 04:38:34 +00005619
Peter Collingbournee190dee2011-03-11 19:24:49 +00005620 case UETT_VecStep: {
5621 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00005622
Peter Collingbournee190dee2011-03-11 19:24:49 +00005623 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00005624 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00005625
Peter Collingbournee190dee2011-03-11 19:24:49 +00005626 // The vec_step built-in functions that take a 3-component
5627 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5628 if (n == 3)
5629 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00005630
Peter Collingbournee190dee2011-03-11 19:24:49 +00005631 return Success(n, E);
5632 } else
5633 return Success(1, E);
5634 }
5635
5636 case UETT_SizeOf: {
5637 QualType SrcTy = E->getTypeOfArgument();
5638 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5639 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00005640 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5641 SrcTy = Ref->getPointeeType();
5642
Richard Smithd62306a2011-11-10 06:34:14 +00005643 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00005644 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00005645 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005646 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005647 }
5648 }
5649
5650 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005651}
5652
Peter Collingbournee9200682011-05-13 03:29:01 +00005653bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00005654 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00005655 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00005656 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005657 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00005658 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00005659 for (unsigned i = 0; i != n; ++i) {
5660 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5661 switch (ON.getKind()) {
5662 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00005663 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00005664 APSInt IdxResult;
5665 if (!EvaluateInteger(Idx, IdxResult, Info))
5666 return false;
5667 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5668 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005669 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00005670 CurrentType = AT->getElementType();
5671 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5672 Result += IdxResult.getSExtValue() * ElementSize;
5673 break;
5674 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005675
Douglas Gregor882211c2010-04-28 22:16:22 +00005676 case OffsetOfExpr::OffsetOfNode::Field: {
5677 FieldDecl *MemberDecl = ON.getField();
5678 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005679 if (!RT)
5680 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00005681 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00005682 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00005683 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00005684 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00005685 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00005686 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00005687 CurrentType = MemberDecl->getType().getNonReferenceType();
5688 break;
5689 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005690
Douglas Gregor882211c2010-04-28 22:16:22 +00005691 case OffsetOfExpr::OffsetOfNode::Identifier:
5692 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00005693
Douglas Gregord1702062010-04-29 00:18:15 +00005694 case OffsetOfExpr::OffsetOfNode::Base: {
5695 CXXBaseSpecifier *BaseSpec = ON.getBase();
5696 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005697 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00005698
5699 // Find the layout of the class whose base we are looking into.
5700 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005701 if (!RT)
5702 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00005703 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00005704 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00005705 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5706
5707 // Find the base class itself.
5708 CurrentType = BaseSpec->getType();
5709 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5710 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005711 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00005712
5713 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00005714 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00005715 break;
5716 }
Douglas Gregor882211c2010-04-28 22:16:22 +00005717 }
5718 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005719 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00005720}
5721
Chris Lattnere13042c2008-07-11 19:10:17 +00005722bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005723 switch (E->getOpcode()) {
5724 default:
5725 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5726 // See C99 6.6p3.
5727 return Error(E);
5728 case UO_Extension:
5729 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5730 // If so, we could clear the diagnostic ID.
5731 return Visit(E->getSubExpr());
5732 case UO_Plus:
5733 // The result is just the value.
5734 return Visit(E->getSubExpr());
5735 case UO_Minus: {
5736 if (!Visit(E->getSubExpr()))
5737 return false;
5738 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00005739 const APSInt &Value = Result.getInt();
5740 if (Value.isSigned() && Value.isMinSignedValue())
5741 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5742 E->getType());
5743 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005744 }
5745 case UO_Not: {
5746 if (!Visit(E->getSubExpr()))
5747 return false;
5748 if (!Result.isInt()) return Error(E);
5749 return Success(~Result.getInt(), E);
5750 }
5751 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00005752 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00005753 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00005754 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005755 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00005756 }
Anders Carlsson9c181652008-07-08 14:35:21 +00005757 }
Anders Carlsson9c181652008-07-08 14:35:21 +00005758}
Mike Stump11289f42009-09-09 15:08:12 +00005759
Chris Lattner477c4be2008-07-12 01:15:53 +00005760/// HandleCast - This is used to evaluate implicit or explicit casts where the
5761/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00005762bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5763 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00005764 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00005765 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00005766
Eli Friedmanc757de22011-03-25 00:43:55 +00005767 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00005768 case CK_BaseToDerived:
5769 case CK_DerivedToBase:
5770 case CK_UncheckedDerivedToBase:
5771 case CK_Dynamic:
5772 case CK_ToUnion:
5773 case CK_ArrayToPointerDecay:
5774 case CK_FunctionToPointerDecay:
5775 case CK_NullToPointer:
5776 case CK_NullToMemberPointer:
5777 case CK_BaseToDerivedMemberPointer:
5778 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00005779 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00005780 case CK_ConstructorConversion:
5781 case CK_IntegralToPointer:
5782 case CK_ToVoid:
5783 case CK_VectorSplat:
5784 case CK_IntegralToFloating:
5785 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00005786 case CK_CPointerToObjCPointerCast:
5787 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00005788 case CK_AnyPointerToBlockPointerCast:
5789 case CK_ObjCObjectLValueCast:
5790 case CK_FloatingRealToComplex:
5791 case CK_FloatingComplexToReal:
5792 case CK_FloatingComplexCast:
5793 case CK_FloatingComplexToIntegralComplex:
5794 case CK_IntegralRealToComplex:
5795 case CK_IntegralComplexCast:
5796 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00005797 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005798 case CK_ZeroToOCLEvent:
Eli Friedmanc757de22011-03-25 00:43:55 +00005799 llvm_unreachable("invalid cast kind for integral value");
5800
Eli Friedman9faf2f92011-03-25 19:07:11 +00005801 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00005802 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00005803 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00005804 case CK_ARCProduceObject:
5805 case CK_ARCConsumeObject:
5806 case CK_ARCReclaimReturnedObject:
5807 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00005808 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00005809 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005810
Richard Smith4ef685b2012-01-17 21:17:26 +00005811 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00005812 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00005813 case CK_AtomicToNonAtomic:
5814 case CK_NonAtomicToAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00005815 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00005816 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005817
5818 case CK_MemberPointerToBoolean:
5819 case CK_PointerToBoolean:
5820 case CK_IntegralToBoolean:
5821 case CK_FloatingToBoolean:
5822 case CK_FloatingComplexToBoolean:
5823 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00005824 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00005825 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00005826 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005827 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005828 }
5829
Eli Friedmanc757de22011-03-25 00:43:55 +00005830 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00005831 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00005832 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00005833
Eli Friedman742421e2009-02-20 01:15:07 +00005834 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005835 // Allow casts of address-of-label differences if they are no-ops
5836 // or narrowing. (The narrowing case isn't actually guaranteed to
5837 // be constant-evaluatable except in some narrow cases which are hard
5838 // to detect here. We let it through on the assumption the user knows
5839 // what they are doing.)
5840 if (Result.isAddrLabelDiff())
5841 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00005842 // Only allow casts of lvalues if they are lossless.
5843 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5844 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005845
Richard Smith911e1422012-01-30 22:27:01 +00005846 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5847 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00005848 }
Mike Stump11289f42009-09-09 15:08:12 +00005849
Eli Friedmanc757de22011-03-25 00:43:55 +00005850 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005851 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5852
John McCall45d55e42010-05-07 21:00:08 +00005853 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00005854 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00005855 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00005856
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00005857 if (LV.getLValueBase()) {
5858 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00005859 // FIXME: Allow a larger integer size than the pointer size, and allow
5860 // narrowing back down to pointer width in subsequent integral casts.
5861 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00005862 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005863 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005864
Richard Smithcf74da72011-11-16 07:18:12 +00005865 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00005866 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00005867 return true;
5868 }
5869
Ken Dyck02990832010-01-15 12:37:54 +00005870 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5871 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00005872 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005873 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005874
Eli Friedmanc757de22011-03-25 00:43:55 +00005875 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00005876 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00005877 if (!EvaluateComplex(SubExpr, C, Info))
5878 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00005879 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00005880 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00005881
Eli Friedmanc757de22011-03-25 00:43:55 +00005882 case CK_FloatingToIntegral: {
5883 APFloat F(0.0);
5884 if (!EvaluateFloat(SubExpr, F, Info))
5885 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00005886
Richard Smith357362d2011-12-13 06:39:58 +00005887 APSInt Value;
5888 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5889 return false;
5890 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005891 }
5892 }
Mike Stump11289f42009-09-09 15:08:12 +00005893
Eli Friedmanc757de22011-03-25 00:43:55 +00005894 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00005895}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005896
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005897bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5898 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00005899 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005900 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5901 return false;
5902 if (!LV.isComplexInt())
5903 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005904 return Success(LV.getComplexIntReal(), E);
5905 }
5906
5907 return Visit(E->getSubExpr());
5908}
5909
Eli Friedman4e7a2412009-02-27 04:45:43 +00005910bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005911 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00005912 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005913 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5914 return false;
5915 if (!LV.isComplexInt())
5916 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005917 return Success(LV.getComplexIntImag(), E);
5918 }
5919
Richard Smith4a678122011-10-24 18:44:57 +00005920 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00005921 return Success(0, E);
5922}
5923
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005924bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5925 return Success(E->getPackLength(), E);
5926}
5927
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005928bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5929 return Success(E->getValue(), E);
5930}
5931
Chris Lattner05706e882008-07-11 18:11:29 +00005932//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00005933// Float Evaluation
5934//===----------------------------------------------------------------------===//
5935
5936namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005937class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00005938 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00005939 APFloat &Result;
5940public:
5941 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005942 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00005943
Richard Smith2e312c82012-03-03 22:46:17 +00005944 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005945 Result = V.getFloat();
5946 return true;
5947 }
Eli Friedman24c01542008-08-22 00:06:13 +00005948
Richard Smithfddd3842011-12-30 21:15:51 +00005949 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00005950 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5951 return true;
5952 }
5953
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005954 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00005955
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005956 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00005957 bool VisitBinaryOperator(const BinaryOperator *E);
5958 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005959 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00005960
John McCallb1fb0d32010-05-07 22:08:54 +00005961 bool VisitUnaryReal(const UnaryOperator *E);
5962 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00005963
Richard Smithfddd3842011-12-30 21:15:51 +00005964 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00005965};
5966} // end anonymous namespace
5967
5968static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005969 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005970 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00005971}
5972
Jay Foad39c79802011-01-12 09:06:06 +00005973static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00005974 QualType ResultTy,
5975 const Expr *Arg,
5976 bool SNaN,
5977 llvm::APFloat &Result) {
5978 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5979 if (!S) return false;
5980
5981 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5982
5983 llvm::APInt fill;
5984
5985 // Treat empty strings as if they were zero.
5986 if (S->getString().empty())
5987 fill = llvm::APInt(32, 0);
5988 else if (S->getString().getAsInteger(0, fill))
5989 return false;
5990
5991 if (SNaN)
5992 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5993 else
5994 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5995 return true;
5996}
5997
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005998bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005999 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006000 default:
6001 return ExprEvaluatorBaseTy::VisitCallExpr(E);
6002
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006003 case Builtin::BI__builtin_huge_val:
6004 case Builtin::BI__builtin_huge_valf:
6005 case Builtin::BI__builtin_huge_vall:
6006 case Builtin::BI__builtin_inf:
6007 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00006008 case Builtin::BI__builtin_infl: {
6009 const llvm::fltSemantics &Sem =
6010 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00006011 Result = llvm::APFloat::getInf(Sem);
6012 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00006013 }
Mike Stump11289f42009-09-09 15:08:12 +00006014
John McCall16291492010-02-28 13:00:19 +00006015 case Builtin::BI__builtin_nans:
6016 case Builtin::BI__builtin_nansf:
6017 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006018 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6019 true, Result))
6020 return Error(E);
6021 return true;
John McCall16291492010-02-28 13:00:19 +00006022
Chris Lattner0b7282e2008-10-06 06:31:58 +00006023 case Builtin::BI__builtin_nan:
6024 case Builtin::BI__builtin_nanf:
6025 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00006026 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00006027 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00006028 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6029 false, Result))
6030 return Error(E);
6031 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006032
6033 case Builtin::BI__builtin_fabs:
6034 case Builtin::BI__builtin_fabsf:
6035 case Builtin::BI__builtin_fabsl:
6036 if (!EvaluateFloat(E->getArg(0), Result, Info))
6037 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006038
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006039 if (Result.isNegative())
6040 Result.changeSign();
6041 return true;
6042
Mike Stump11289f42009-09-09 15:08:12 +00006043 case Builtin::BI__builtin_copysign:
6044 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006045 case Builtin::BI__builtin_copysignl: {
6046 APFloat RHS(0.);
6047 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
6048 !EvaluateFloat(E->getArg(1), RHS, Info))
6049 return false;
6050 Result.copySign(RHS);
6051 return true;
6052 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006053 }
6054}
6055
John McCallb1fb0d32010-05-07 22:08:54 +00006056bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00006057 if (E->getSubExpr()->getType()->isAnyComplexType()) {
6058 ComplexValue CV;
6059 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
6060 return false;
6061 Result = CV.FloatReal;
6062 return true;
6063 }
6064
6065 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00006066}
6067
6068bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00006069 if (E->getSubExpr()->getType()->isAnyComplexType()) {
6070 ComplexValue CV;
6071 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
6072 return false;
6073 Result = CV.FloatImag;
6074 return true;
6075 }
6076
Richard Smith4a678122011-10-24 18:44:57 +00006077 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00006078 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
6079 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00006080 return true;
6081}
6082
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006083bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006084 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006085 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006086 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00006087 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00006088 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00006089 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
6090 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006091 Result.changeSign();
6092 return true;
6093 }
6094}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006095
Eli Friedman24c01542008-08-22 00:06:13 +00006096bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006097 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
6098 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00006099
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006100 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00006101 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
6102 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00006103 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006104 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedman24c01542008-08-22 00:06:13 +00006105 return false;
6106
6107 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006108 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006109 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00006110 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00006111 break;
John McCalle3027922010-08-25 11:45:40 +00006112 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00006113 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00006114 break;
John McCalle3027922010-08-25 11:45:40 +00006115 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00006116 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00006117 break;
John McCalle3027922010-08-25 11:45:40 +00006118 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00006119 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00006120 break;
Eli Friedman24c01542008-08-22 00:06:13 +00006121 }
Richard Smithc8042322012-02-01 05:53:12 +00006122
6123 if (Result.isInfinity() || Result.isNaN())
6124 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
6125 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00006126}
6127
6128bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
6129 Result = E->getValue();
6130 return true;
6131}
6132
Peter Collingbournee9200682011-05-13 03:29:01 +00006133bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
6134 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00006135
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006136 switch (E->getCastKind()) {
6137 default:
Richard Smith11562c52011-10-28 17:51:58 +00006138 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006139
6140 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006141 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00006142 return EvaluateInteger(SubExpr, IntResult, Info) &&
6143 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
6144 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006145 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006146
6147 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006148 if (!Visit(SubExpr))
6149 return false;
Richard Smith357362d2011-12-13 06:39:58 +00006150 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
6151 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006152 }
John McCalld7646252010-11-14 08:17:51 +00006153
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006154 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00006155 ComplexValue V;
6156 if (!EvaluateComplex(SubExpr, V, Info))
6157 return false;
6158 Result = V.getComplexFloatReal();
6159 return true;
6160 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006161 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006162}
6163
Eli Friedman24c01542008-08-22 00:06:13 +00006164//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006165// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00006166//===----------------------------------------------------------------------===//
6167
6168namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006169class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00006170 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00006171 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00006172
Anders Carlsson537969c2008-11-16 20:27:53 +00006173public:
John McCall93d91dc2010-05-07 17:22:02 +00006174 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006175 : ExprEvaluatorBaseTy(info), Result(Result) {}
6176
Richard Smith2e312c82012-03-03 22:46:17 +00006177 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006178 Result.setFrom(V);
6179 return true;
6180 }
Mike Stump11289f42009-09-09 15:08:12 +00006181
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006182 bool ZeroInitialization(const Expr *E);
6183
Anders Carlsson537969c2008-11-16 20:27:53 +00006184 //===--------------------------------------------------------------------===//
6185 // Visitor Methods
6186 //===--------------------------------------------------------------------===//
6187
Peter Collingbournee9200682011-05-13 03:29:01 +00006188 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006189 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00006190 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006191 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006192 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00006193};
6194} // end anonymous namespace
6195
John McCall93d91dc2010-05-07 17:22:02 +00006196static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
6197 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006198 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006199 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00006200}
6201
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006202bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00006203 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006204 if (ElemTy->isRealFloatingType()) {
6205 Result.makeComplexFloat();
6206 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
6207 Result.FloatReal = Zero;
6208 Result.FloatImag = Zero;
6209 } else {
6210 Result.makeComplexInt();
6211 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
6212 Result.IntReal = Zero;
6213 Result.IntImag = Zero;
6214 }
6215 return true;
6216}
6217
Peter Collingbournee9200682011-05-13 03:29:01 +00006218bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
6219 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006220
6221 if (SubExpr->getType()->isRealFloatingType()) {
6222 Result.makeComplexFloat();
6223 APFloat &Imag = Result.FloatImag;
6224 if (!EvaluateFloat(SubExpr, Imag, Info))
6225 return false;
6226
6227 Result.FloatReal = APFloat(Imag.getSemantics());
6228 return true;
6229 } else {
6230 assert(SubExpr->getType()->isIntegerType() &&
6231 "Unexpected imaginary literal.");
6232
6233 Result.makeComplexInt();
6234 APSInt &Imag = Result.IntImag;
6235 if (!EvaluateInteger(SubExpr, Imag, Info))
6236 return false;
6237
6238 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
6239 return true;
6240 }
6241}
6242
Peter Collingbournee9200682011-05-13 03:29:01 +00006243bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006244
John McCallfcef3cf2010-12-14 17:51:41 +00006245 switch (E->getCastKind()) {
6246 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006247 case CK_BaseToDerived:
6248 case CK_DerivedToBase:
6249 case CK_UncheckedDerivedToBase:
6250 case CK_Dynamic:
6251 case CK_ToUnion:
6252 case CK_ArrayToPointerDecay:
6253 case CK_FunctionToPointerDecay:
6254 case CK_NullToPointer:
6255 case CK_NullToMemberPointer:
6256 case CK_BaseToDerivedMemberPointer:
6257 case CK_DerivedToBaseMemberPointer:
6258 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00006259 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00006260 case CK_ConstructorConversion:
6261 case CK_IntegralToPointer:
6262 case CK_PointerToIntegral:
6263 case CK_PointerToBoolean:
6264 case CK_ToVoid:
6265 case CK_VectorSplat:
6266 case CK_IntegralCast:
6267 case CK_IntegralToBoolean:
6268 case CK_IntegralToFloating:
6269 case CK_FloatingToIntegral:
6270 case CK_FloatingToBoolean:
6271 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00006272 case CK_CPointerToObjCPointerCast:
6273 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006274 case CK_AnyPointerToBlockPointerCast:
6275 case CK_ObjCObjectLValueCast:
6276 case CK_FloatingComplexToReal:
6277 case CK_FloatingComplexToBoolean:
6278 case CK_IntegralComplexToReal:
6279 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00006280 case CK_ARCProduceObject:
6281 case CK_ARCConsumeObject:
6282 case CK_ARCReclaimReturnedObject:
6283 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00006284 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00006285 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006286 case CK_ZeroToOCLEvent:
John McCallfcef3cf2010-12-14 17:51:41 +00006287 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00006288
John McCallfcef3cf2010-12-14 17:51:41 +00006289 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006290 case CK_AtomicToNonAtomic:
6291 case CK_NonAtomicToAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00006292 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00006293 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00006294
6295 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006296 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006297 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006298 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00006299
6300 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006301 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00006302 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006303 return false;
6304
John McCallfcef3cf2010-12-14 17:51:41 +00006305 Result.makeComplexFloat();
6306 Result.FloatImag = APFloat(Real.getSemantics());
6307 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006308 }
6309
John McCallfcef3cf2010-12-14 17:51:41 +00006310 case CK_FloatingComplexCast: {
6311 if (!Visit(E->getSubExpr()))
6312 return false;
6313
6314 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6315 QualType From
6316 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6317
Richard Smith357362d2011-12-13 06:39:58 +00006318 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
6319 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006320 }
6321
6322 case CK_FloatingComplexToIntegralComplex: {
6323 if (!Visit(E->getSubExpr()))
6324 return false;
6325
6326 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6327 QualType From
6328 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6329 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00006330 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
6331 To, Result.IntReal) &&
6332 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
6333 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006334 }
6335
6336 case CK_IntegralRealToComplex: {
6337 APSInt &Real = Result.IntReal;
6338 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
6339 return false;
6340
6341 Result.makeComplexInt();
6342 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
6343 return true;
6344 }
6345
6346 case CK_IntegralComplexCast: {
6347 if (!Visit(E->getSubExpr()))
6348 return false;
6349
6350 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6351 QualType From
6352 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6353
Richard Smith911e1422012-01-30 22:27:01 +00006354 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
6355 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006356 return true;
6357 }
6358
6359 case CK_IntegralComplexToFloatingComplex: {
6360 if (!Visit(E->getSubExpr()))
6361 return false;
6362
Ted Kremenek28831752012-08-23 20:46:57 +00006363 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00006364 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00006365 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00006366 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00006367 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
6368 To, Result.FloatReal) &&
6369 HandleIntToFloatCast(Info, E, From, Result.IntImag,
6370 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006371 }
6372 }
6373
6374 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006375}
6376
John McCall93d91dc2010-05-07 17:22:02 +00006377bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006378 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00006379 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6380
Richard Smith253c2a32012-01-27 01:14:48 +00006381 bool LHSOK = Visit(E->getLHS());
6382 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00006383 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006384
John McCall93d91dc2010-05-07 17:22:02 +00006385 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00006386 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00006387 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006388
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006389 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
6390 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006391 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006392 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006393 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006394 if (Result.isComplexFloat()) {
6395 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
6396 APFloat::rmNearestTiesToEven);
6397 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
6398 APFloat::rmNearestTiesToEven);
6399 } else {
6400 Result.getComplexIntReal() += RHS.getComplexIntReal();
6401 Result.getComplexIntImag() += RHS.getComplexIntImag();
6402 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006403 break;
John McCalle3027922010-08-25 11:45:40 +00006404 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006405 if (Result.isComplexFloat()) {
6406 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
6407 APFloat::rmNearestTiesToEven);
6408 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
6409 APFloat::rmNearestTiesToEven);
6410 } else {
6411 Result.getComplexIntReal() -= RHS.getComplexIntReal();
6412 Result.getComplexIntImag() -= RHS.getComplexIntImag();
6413 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006414 break;
John McCalle3027922010-08-25 11:45:40 +00006415 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006416 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00006417 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006418 APFloat &LHS_r = LHS.getComplexFloatReal();
6419 APFloat &LHS_i = LHS.getComplexFloatImag();
6420 APFloat &RHS_r = RHS.getComplexFloatReal();
6421 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00006422
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006423 APFloat Tmp = LHS_r;
6424 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6425 Result.getComplexFloatReal() = Tmp;
6426 Tmp = LHS_i;
6427 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6428 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
6429
6430 Tmp = LHS_r;
6431 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6432 Result.getComplexFloatImag() = Tmp;
6433 Tmp = LHS_i;
6434 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6435 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
6436 } else {
John McCall93d91dc2010-05-07 17:22:02 +00006437 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00006438 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006439 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
6440 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00006441 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006442 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6443 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6444 }
6445 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006446 case BO_Div:
6447 if (Result.isComplexFloat()) {
6448 ComplexValue LHS = Result;
6449 APFloat &LHS_r = LHS.getComplexFloatReal();
6450 APFloat &LHS_i = LHS.getComplexFloatImag();
6451 APFloat &RHS_r = RHS.getComplexFloatReal();
6452 APFloat &RHS_i = RHS.getComplexFloatImag();
6453 APFloat &Res_r = Result.getComplexFloatReal();
6454 APFloat &Res_i = Result.getComplexFloatImag();
6455
6456 APFloat Den = RHS_r;
6457 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6458 APFloat Tmp = RHS_i;
6459 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6460 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6461
6462 Res_r = LHS_r;
6463 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6464 Tmp = LHS_i;
6465 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6466 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6467 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6468
6469 Res_i = LHS_i;
6470 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6471 Tmp = LHS_r;
6472 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6473 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6474 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6475 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006476 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6477 return Error(E, diag::note_expr_divide_by_zero);
6478
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006479 ComplexValue LHS = Result;
6480 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6481 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6482 Result.getComplexIntReal() =
6483 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6484 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6485 Result.getComplexIntImag() =
6486 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6487 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6488 }
6489 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006490 }
6491
John McCall93d91dc2010-05-07 17:22:02 +00006492 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006493}
6494
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006495bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6496 // Get the operand value into 'Result'.
6497 if (!Visit(E->getSubExpr()))
6498 return false;
6499
6500 switch (E->getOpcode()) {
6501 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006502 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006503 case UO_Extension:
6504 return true;
6505 case UO_Plus:
6506 // The result is always just the subexpr.
6507 return true;
6508 case UO_Minus:
6509 if (Result.isComplexFloat()) {
6510 Result.getComplexFloatReal().changeSign();
6511 Result.getComplexFloatImag().changeSign();
6512 }
6513 else {
6514 Result.getComplexIntReal() = -Result.getComplexIntReal();
6515 Result.getComplexIntImag() = -Result.getComplexIntImag();
6516 }
6517 return true;
6518 case UO_Not:
6519 if (Result.isComplexFloat())
6520 Result.getComplexFloatImag().changeSign();
6521 else
6522 Result.getComplexIntImag() = -Result.getComplexIntImag();
6523 return true;
6524 }
6525}
6526
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006527bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6528 if (E->getNumInits() == 2) {
6529 if (E->getType()->isComplexType()) {
6530 Result.makeComplexFloat();
6531 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
6532 return false;
6533 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
6534 return false;
6535 } else {
6536 Result.makeComplexInt();
6537 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
6538 return false;
6539 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
6540 return false;
6541 }
6542 return true;
6543 }
6544 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
6545}
6546
Anders Carlsson537969c2008-11-16 20:27:53 +00006547//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00006548// Void expression evaluation, primarily for a cast to void on the LHS of a
6549// comma operator
6550//===----------------------------------------------------------------------===//
6551
6552namespace {
6553class VoidExprEvaluator
6554 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
6555public:
6556 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
6557
Richard Smith2e312c82012-03-03 22:46:17 +00006558 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00006559
6560 bool VisitCastExpr(const CastExpr *E) {
6561 switch (E->getCastKind()) {
6562 default:
6563 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6564 case CK_ToVoid:
6565 VisitIgnoredValue(E->getSubExpr());
6566 return true;
6567 }
6568 }
6569};
6570} // end anonymous namespace
6571
6572static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
6573 assert(E->isRValue() && E->getType()->isVoidType());
6574 return VoidExprEvaluator(Info).Visit(E);
6575}
6576
6577//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00006578// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00006579//===----------------------------------------------------------------------===//
6580
Richard Smith2e312c82012-03-03 22:46:17 +00006581static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006582 // In C, function designators are not lvalues, but we evaluate them as if they
6583 // are.
6584 if (E->isGLValue() || E->getType()->isFunctionType()) {
6585 LValue LV;
6586 if (!EvaluateLValue(E, LV, Info))
6587 return false;
6588 LV.moveInto(Result);
6589 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00006590 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006591 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006592 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00006593 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006594 return false;
John McCall45d55e42010-05-07 21:00:08 +00006595 } else if (E->getType()->hasPointerRepresentation()) {
6596 LValue LV;
6597 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006598 return false;
Richard Smith725810a2011-10-16 21:26:27 +00006599 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00006600 } else if (E->getType()->isRealFloatingType()) {
6601 llvm::APFloat F(0.0);
6602 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006603 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006604 Result = APValue(F);
John McCall45d55e42010-05-07 21:00:08 +00006605 } else if (E->getType()->isAnyComplexType()) {
6606 ComplexValue C;
6607 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006608 return false;
Richard Smith725810a2011-10-16 21:26:27 +00006609 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00006610 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00006611 MemberPtr P;
6612 if (!EvaluateMemberPointer(E, P, Info))
6613 return false;
6614 P.moveInto(Result);
6615 return true;
Richard Smithfddd3842011-12-30 21:15:51 +00006616 } else if (E->getType()->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006617 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00006618 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00006619 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00006620 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006621 Result = Info.CurrentCall->Temporaries[E];
Richard Smithfddd3842011-12-30 21:15:51 +00006622 } else if (E->getType()->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006623 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00006624 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00006625 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6626 return false;
6627 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00006628 } else if (E->getType()->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006629 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006630 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00006631 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00006632 if (!EvaluateVoid(E, Info))
6633 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006634 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00006635 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00006636 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006637 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00006638 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00006639 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006640 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006641
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00006642 return true;
6643}
6644
Richard Smithb228a862012-02-15 02:18:13 +00006645/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6646/// cases, the in-place evaluation is essential, since later initializers for
6647/// an object can indirectly refer to subobjects which were initialized earlier.
6648static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6649 const Expr *E, CheckConstantExpressionKind CCEK,
6650 bool AllowNonLiteralTypes) {
Richard Smith6331c402012-02-13 22:16:19 +00006651 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +00006652 return false;
6653
6654 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00006655 // Evaluate arrays and record types in-place, so that later initializers can
6656 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00006657 if (E->getType()->isArrayType())
6658 return EvaluateArray(E, This, Result, Info);
6659 else if (E->getType()->isRecordType())
6660 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00006661 }
6662
6663 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00006664 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00006665}
6666
Richard Smithf57d8cb2011-12-09 22:58:01 +00006667/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6668/// lvalue-to-rvalue cast if it is an lvalue.
6669static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00006670 if (!CheckLiteralType(Info, E))
6671 return false;
6672
Richard Smith2e312c82012-03-03 22:46:17 +00006673 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006674 return false;
6675
6676 if (E->isGLValue()) {
6677 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00006678 LV.setFrom(Info.Ctx, Result);
6679 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006680 return false;
6681 }
6682
Richard Smith2e312c82012-03-03 22:46:17 +00006683 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00006684 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006685}
Richard Smith11562c52011-10-28 17:51:58 +00006686
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006687static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
6688 const ASTContext &Ctx, bool &IsConst) {
6689 // Fast-path evaluations of integer literals, since we sometimes see files
6690 // containing vast quantities of these.
6691 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
6692 Result.Val = APValue(APSInt(L->getValue(),
6693 L->getType()->isUnsignedIntegerType()));
6694 IsConst = true;
6695 return true;
6696 }
6697
6698 // FIXME: Evaluating values of large array and record types can cause
6699 // performance problems. Only do so in C++11 for now.
6700 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
6701 Exp->getType()->isRecordType()) &&
6702 !Ctx.getLangOpts().CPlusPlus11) {
6703 IsConst = false;
6704 return true;
6705 }
6706 return false;
6707}
6708
6709
Richard Smith7b553f12011-10-29 00:50:52 +00006710/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00006711/// any crazy technique (that has nothing to do with language standards) that
6712/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00006713/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6714/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00006715bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006716 bool IsConst;
6717 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
6718 return IsConst;
6719
Richard Smithf57d8cb2011-12-09 22:58:01 +00006720 EvalInfo Info(Ctx, Result);
6721 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00006722}
6723
Jay Foad39c79802011-01-12 09:06:06 +00006724bool Expr::EvaluateAsBooleanCondition(bool &Result,
6725 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00006726 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00006727 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00006728 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00006729}
6730
Richard Smith5fab0c92011-12-28 19:48:30 +00006731bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6732 SideEffectsKind AllowSideEffects) const {
6733 if (!getType()->isIntegralOrEnumerationType())
6734 return false;
6735
Richard Smith11562c52011-10-28 17:51:58 +00006736 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00006737 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6738 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00006739 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006740
Richard Smith11562c52011-10-28 17:51:58 +00006741 Result = ExprResult.Val.getInt();
6742 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00006743}
6744
Jay Foad39c79802011-01-12 09:06:06 +00006745bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00006746 EvalInfo Info(Ctx, Result);
6747
John McCall45d55e42010-05-07 21:00:08 +00006748 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00006749 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6750 !CheckLValueConstantExpression(Info, getExprLoc(),
6751 Ctx.getLValueReferenceType(getType()), LV))
6752 return false;
6753
Richard Smith2e312c82012-03-03 22:46:17 +00006754 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00006755 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00006756}
6757
Richard Smithd0b4dd62011-12-19 06:19:21 +00006758bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6759 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006760 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00006761 // FIXME: Evaluating initializers for large array and record types can cause
6762 // performance problems. Only do so in C++11 for now.
6763 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006764 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00006765 return false;
6766
Richard Smithd0b4dd62011-12-19 06:19:21 +00006767 Expr::EvalStatus EStatus;
6768 EStatus.Diag = &Notes;
6769
6770 EvalInfo InitInfo(Ctx, EStatus);
6771 InitInfo.setEvaluatingDecl(VD, Value);
6772
6773 LValue LVal;
6774 LVal.set(VD);
6775
Richard Smithfddd3842011-12-30 21:15:51 +00006776 // C++11 [basic.start.init]p2:
6777 // Variables with static storage duration or thread storage duration shall be
6778 // zero-initialized before any other initialization takes place.
6779 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006780 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00006781 !VD->getType()->isReferenceType()) {
6782 ImplicitValueInitExpr VIE(VD->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006783 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6784 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00006785 return false;
6786 }
6787
Richard Smithb228a862012-02-15 02:18:13 +00006788 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6789 /*AllowNonLiteralTypes=*/true) ||
6790 EStatus.HasSideEffects)
6791 return false;
6792
6793 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6794 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00006795}
6796
Richard Smith7b553f12011-10-29 00:50:52 +00006797/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6798/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00006799bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00006800 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00006801 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00006802}
Anders Carlsson59689ed2008-11-22 21:04:56 +00006803
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00006804APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006805 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00006806 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00006807 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00006808 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00006809 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00006810 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00006811 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00006812
Anders Carlsson6736d1a22008-12-19 20:58:05 +00006813 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00006814}
John McCall864e3962010-05-07 05:32:02 +00006815
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006816void Expr::EvaluateForOverflow(const ASTContext &Ctx,
6817 SmallVectorImpl<PartialDiagnosticAt> *Diags) const {
6818 bool IsConst;
6819 EvalResult EvalResult;
6820 EvalResult.Diag = Diags;
6821 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
6822 EvalInfo Info(Ctx, EvalResult, true);
6823 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
6824 }
6825}
6826
Abramo Bagnaraf8199452010-05-14 17:07:14 +00006827 bool Expr::EvalResult::isGlobalLValue() const {
6828 assert(Val.isLValue());
6829 return IsGlobalLValue(Val.getLValueBase());
6830 }
6831
6832
John McCall864e3962010-05-07 05:32:02 +00006833/// isIntegerConstantExpr - this recursive routine will test if an expression is
6834/// an integer constant expression.
6835
6836/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6837/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00006838
6839// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00006840// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
6841// and a (possibly null) SourceLocation indicating the location of the problem.
6842//
John McCall864e3962010-05-07 05:32:02 +00006843// Note that to reduce code duplication, this helper does no evaluation
6844// itself; the caller checks whether the expression is evaluatable, and
6845// in the rare cases where CheckICE actually cares about the evaluated
6846// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00006847
Dan Gohman28ade552010-07-26 21:25:24 +00006848namespace {
6849
Richard Smith9e575da2012-12-28 13:25:52 +00006850enum ICEKind {
6851 /// This expression is an ICE.
6852 IK_ICE,
6853 /// This expression is not an ICE, but if it isn't evaluated, it's
6854 /// a legal subexpression for an ICE. This return value is used to handle
6855 /// the comma operator in C99 mode, and non-constant subexpressions.
6856 IK_ICEIfUnevaluated,
6857 /// This expression is not an ICE, and is not a legal subexpression for one.
6858 IK_NotICE
6859};
6860
John McCall864e3962010-05-07 05:32:02 +00006861struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00006862 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00006863 SourceLocation Loc;
6864
Richard Smith9e575da2012-12-28 13:25:52 +00006865 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00006866};
6867
Dan Gohman28ade552010-07-26 21:25:24 +00006868}
6869
Richard Smith9e575da2012-12-28 13:25:52 +00006870static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
6871
6872static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00006873
6874static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6875 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00006876 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00006877 !EVResult.Val.isInt())
6878 return ICEDiag(IK_NotICE, E->getLocStart());
6879
John McCall864e3962010-05-07 05:32:02 +00006880 return NoDiag();
6881}
6882
6883static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6884 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00006885 if (!E->getType()->isIntegralOrEnumerationType())
6886 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006887
6888 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00006889#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00006890#define STMT(Node, Base) case Expr::Node##Class:
6891#define EXPR(Node, Base)
6892#include "clang/AST/StmtNodes.inc"
6893 case Expr::PredefinedExprClass:
6894 case Expr::FloatingLiteralClass:
6895 case Expr::ImaginaryLiteralClass:
6896 case Expr::StringLiteralClass:
6897 case Expr::ArraySubscriptExprClass:
6898 case Expr::MemberExprClass:
6899 case Expr::CompoundAssignOperatorClass:
6900 case Expr::CompoundLiteralExprClass:
6901 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00006902 case Expr::DesignatedInitExprClass:
6903 case Expr::ImplicitValueInitExprClass:
6904 case Expr::ParenListExprClass:
6905 case Expr::VAArgExprClass:
6906 case Expr::AddrLabelExprClass:
6907 case Expr::StmtExprClass:
6908 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00006909 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00006910 case Expr::CXXDynamicCastExprClass:
6911 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00006912 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00006913 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00006914 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00006915 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00006916 case Expr::CXXThisExprClass:
6917 case Expr::CXXThrowExprClass:
6918 case Expr::CXXNewExprClass:
6919 case Expr::CXXDeleteExprClass:
6920 case Expr::CXXPseudoDestructorExprClass:
6921 case Expr::UnresolvedLookupExprClass:
6922 case Expr::DependentScopeDeclRefExprClass:
6923 case Expr::CXXConstructExprClass:
6924 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00006925 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00006926 case Expr::CXXTemporaryObjectExprClass:
6927 case Expr::CXXUnresolvedConstructExprClass:
6928 case Expr::CXXDependentScopeMemberExprClass:
6929 case Expr::UnresolvedMemberExprClass:
6930 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00006931 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00006932 case Expr::ObjCArrayLiteralClass:
6933 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00006934 case Expr::ObjCEncodeExprClass:
6935 case Expr::ObjCMessageExprClass:
6936 case Expr::ObjCSelectorExprClass:
6937 case Expr::ObjCProtocolExprClass:
6938 case Expr::ObjCIvarRefExprClass:
6939 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00006940 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00006941 case Expr::ObjCIsaExprClass:
6942 case Expr::ShuffleVectorExprClass:
6943 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00006944 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00006945 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00006946 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00006947 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00006948 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00006949 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00006950 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00006951 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00006952 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00006953 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00006954 case Expr::InitListExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00006955 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00006956 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00006957
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006958 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00006959 case Expr::GNUNullExprClass:
6960 // GCC considers the GNU __null value to be an integral constant expression.
6961 return NoDiag();
6962
John McCall7c454bb2011-07-15 05:09:51 +00006963 case Expr::SubstNonTypeTemplateParmExprClass:
6964 return
6965 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6966
John McCall864e3962010-05-07 05:32:02 +00006967 case Expr::ParenExprClass:
6968 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00006969 case Expr::GenericSelectionExprClass:
6970 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00006971 case Expr::IntegerLiteralClass:
6972 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00006973 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00006974 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00006975 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00006976 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00006977 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00006978 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00006979 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00006980 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006981 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00006982 return NoDiag();
6983 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00006984 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00006985 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6986 // constant expressions, but they can never be ICEs because an ICE cannot
6987 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00006988 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006989 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00006990 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00006991 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006992 }
Richard Smith6365c912012-02-24 22:12:32 +00006993 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00006994 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6995 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00006996 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006997 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00006998 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00006999 // Parameter variables are never constants. Without this check,
7000 // getAnyInitializer() can find a default argument, which leads
7001 // to chaos.
7002 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00007003 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00007004
7005 // C++ 7.1.5.1p2
7006 // A variable of non-volatile const-qualified integral or enumeration
7007 // type initialized by an ICE can be used in ICEs.
7008 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00007009 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00007010 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00007011
Richard Smithd0b4dd62011-12-19 06:19:21 +00007012 const VarDecl *VD;
7013 // Look for a declaration of this variable that has an initializer, and
7014 // check whether it is an ICE.
7015 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
7016 return NoDiag();
7017 else
Richard Smith9e575da2012-12-28 13:25:52 +00007018 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00007019 }
7020 }
Richard Smith9e575da2012-12-28 13:25:52 +00007021 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00007022 }
John McCall864e3962010-05-07 05:32:02 +00007023 case Expr::UnaryOperatorClass: {
7024 const UnaryOperator *Exp = cast<UnaryOperator>(E);
7025 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007026 case UO_PostInc:
7027 case UO_PostDec:
7028 case UO_PreInc:
7029 case UO_PreDec:
7030 case UO_AddrOf:
7031 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00007032 // C99 6.6/3 allows increment and decrement within unevaluated
7033 // subexpressions of constant expressions, but they can never be ICEs
7034 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00007035 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00007036 case UO_Extension:
7037 case UO_LNot:
7038 case UO_Plus:
7039 case UO_Minus:
7040 case UO_Not:
7041 case UO_Real:
7042 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00007043 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007044 }
Richard Smith9e575da2012-12-28 13:25:52 +00007045
John McCall864e3962010-05-07 05:32:02 +00007046 // OffsetOf falls through here.
7047 }
7048 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00007049 // Note that per C99, offsetof must be an ICE. And AFAIK, using
7050 // EvaluateAsRValue matches the proposed gcc behavior for cases like
7051 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
7052 // compliance: we should warn earlier for offsetof expressions with
7053 // array subscripts that aren't ICEs, and if the array subscripts
7054 // are ICEs, the value of the offsetof must be an integer constant.
7055 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00007056 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00007057 case Expr::UnaryExprOrTypeTraitExprClass: {
7058 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
7059 if ((Exp->getKind() == UETT_SizeOf) &&
7060 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00007061 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007062 return NoDiag();
7063 }
7064 case Expr::BinaryOperatorClass: {
7065 const BinaryOperator *Exp = cast<BinaryOperator>(E);
7066 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007067 case BO_PtrMemD:
7068 case BO_PtrMemI:
7069 case BO_Assign:
7070 case BO_MulAssign:
7071 case BO_DivAssign:
7072 case BO_RemAssign:
7073 case BO_AddAssign:
7074 case BO_SubAssign:
7075 case BO_ShlAssign:
7076 case BO_ShrAssign:
7077 case BO_AndAssign:
7078 case BO_XorAssign:
7079 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00007080 // C99 6.6/3 allows assignments within unevaluated subexpressions of
7081 // constant expressions, but they can never be ICEs because an ICE cannot
7082 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00007083 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007084
John McCalle3027922010-08-25 11:45:40 +00007085 case BO_Mul:
7086 case BO_Div:
7087 case BO_Rem:
7088 case BO_Add:
7089 case BO_Sub:
7090 case BO_Shl:
7091 case BO_Shr:
7092 case BO_LT:
7093 case BO_GT:
7094 case BO_LE:
7095 case BO_GE:
7096 case BO_EQ:
7097 case BO_NE:
7098 case BO_And:
7099 case BO_Xor:
7100 case BO_Or:
7101 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00007102 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
7103 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00007104 if (Exp->getOpcode() == BO_Div ||
7105 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00007106 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00007107 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00007108 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00007109 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00007110 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00007111 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007112 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00007113 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00007114 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00007115 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007116 }
7117 }
7118 }
John McCalle3027922010-08-25 11:45:40 +00007119 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007120 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00007121 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
7122 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00007123 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
7124 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007125 } else {
7126 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00007127 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007128 }
7129 }
Richard Smith9e575da2012-12-28 13:25:52 +00007130 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00007131 }
John McCalle3027922010-08-25 11:45:40 +00007132 case BO_LAnd:
7133 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00007134 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
7135 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007136 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00007137 // Rare case where the RHS has a comma "side-effect"; we need
7138 // to actually check the condition to see whether the side
7139 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00007140 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00007141 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00007142 return RHSResult;
7143 return NoDiag();
7144 }
7145
Richard Smith9e575da2012-12-28 13:25:52 +00007146 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00007147 }
7148 }
7149 }
7150 case Expr::ImplicitCastExprClass:
7151 case Expr::CStyleCastExprClass:
7152 case Expr::CXXFunctionalCastExprClass:
7153 case Expr::CXXStaticCastExprClass:
7154 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00007155 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007156 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00007157 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00007158 if (isa<ExplicitCastExpr>(E)) {
7159 if (const FloatingLiteral *FL
7160 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
7161 unsigned DestWidth = Ctx.getIntWidth(E->getType());
7162 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
7163 APSInt IgnoredVal(DestWidth, !DestSigned);
7164 bool Ignored;
7165 // If the value does not fit in the destination type, the behavior is
7166 // undefined, so we are not required to treat it as a constant
7167 // expression.
7168 if (FL->getValue().convertToInteger(IgnoredVal,
7169 llvm::APFloat::rmTowardZero,
7170 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00007171 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00007172 return NoDiag();
7173 }
7174 }
Eli Friedman76d4e432011-09-29 21:49:34 +00007175 switch (cast<CastExpr>(E)->getCastKind()) {
7176 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007177 case CK_AtomicToNonAtomic:
7178 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00007179 case CK_NoOp:
7180 case CK_IntegralToBoolean:
7181 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00007182 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00007183 default:
Richard Smith9e575da2012-12-28 13:25:52 +00007184 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00007185 }
John McCall864e3962010-05-07 05:32:02 +00007186 }
John McCallc07a0c72011-02-17 10:25:35 +00007187 case Expr::BinaryConditionalOperatorClass: {
7188 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
7189 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007190 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00007191 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007192 if (FalseResult.Kind == IK_NotICE) return FalseResult;
7193 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
7194 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00007195 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00007196 return FalseResult;
7197 }
John McCall864e3962010-05-07 05:32:02 +00007198 case Expr::ConditionalOperatorClass: {
7199 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
7200 // If the condition (ignoring parens) is a __builtin_constant_p call,
7201 // then only the true side is actually considered in an integer constant
7202 // expression, and it is fully evaluated. This is an important GNU
7203 // extension. See GCC PR38377 for discussion.
7204 if (const CallExpr *CallCE
7205 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00007206 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
7207 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00007208 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007209 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007210 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007211
Richard Smithf57d8cb2011-12-09 22:58:01 +00007212 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
7213 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007214
Richard Smith9e575da2012-12-28 13:25:52 +00007215 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007216 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007217 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007218 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007219 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00007220 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007221 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00007222 return NoDiag();
7223 // Rare case where the diagnostics depend on which side is evaluated
7224 // Note that if we get here, CondResult is 0, and at least one of
7225 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00007226 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00007227 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00007228 return TrueResult;
7229 }
7230 case Expr::CXXDefaultArgExprClass:
7231 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00007232 case Expr::CXXDefaultInitExprClass:
7233 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007234 case Expr::ChooseExprClass: {
7235 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
7236 }
7237 }
7238
David Blaikiee4d798f2012-01-20 21:50:17 +00007239 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00007240}
7241
Richard Smithf57d8cb2011-12-09 22:58:01 +00007242/// Evaluate an expression as a C++11 integral constant expression.
7243static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
7244 const Expr *E,
7245 llvm::APSInt *Value,
7246 SourceLocation *Loc) {
7247 if (!E->getType()->isIntegralOrEnumerationType()) {
7248 if (Loc) *Loc = E->getExprLoc();
7249 return false;
7250 }
7251
Richard Smith66e05fe2012-01-18 05:21:49 +00007252 APValue Result;
7253 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00007254 return false;
7255
Richard Smith66e05fe2012-01-18 05:21:49 +00007256 assert(Result.isInt() && "pointer cast to int is not an ICE");
7257 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00007258 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007259}
7260
Richard Smith92b1ce02011-12-12 09:28:41 +00007261bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007262 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007263 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
7264
Richard Smith9e575da2012-12-28 13:25:52 +00007265 ICEDiag D = CheckICE(this, Ctx);
7266 if (D.Kind != IK_ICE) {
7267 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00007268 return false;
7269 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007270 return true;
7271}
7272
7273bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
7274 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007275 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007276 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
7277
7278 if (!isIntegerConstantExpr(Ctx, Loc))
7279 return false;
7280 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00007281 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00007282 return true;
7283}
Richard Smith66e05fe2012-01-18 05:21:49 +00007284
Richard Smith98a0a492012-02-14 21:38:30 +00007285bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00007286 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00007287}
7288
Richard Smith66e05fe2012-01-18 05:21:49 +00007289bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
7290 SourceLocation *Loc) const {
7291 // We support this checking in C++98 mode in order to diagnose compatibility
7292 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007293 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00007294
Richard Smith98a0a492012-02-14 21:38:30 +00007295 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00007296 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007297 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00007298 Status.Diag = &Diags;
7299 EvalInfo Info(Ctx, Status);
7300
7301 APValue Scratch;
7302 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
7303
7304 if (!Diags.empty()) {
7305 IsConstExpr = false;
7306 if (Loc) *Loc = Diags[0].first;
7307 } else if (!IsConstExpr) {
7308 // FIXME: This shouldn't happen.
7309 if (Loc) *Loc = getExprLoc();
7310 }
7311
7312 return IsConstExpr;
7313}
Richard Smith253c2a32012-01-27 01:14:48 +00007314
7315bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007316 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00007317 PartialDiagnosticAt> &Diags) {
7318 // FIXME: It would be useful to check constexpr function templates, but at the
7319 // moment the constant expression evaluator cannot cope with the non-rigorous
7320 // ASTs which we build for dependent expressions.
7321 if (FD->isDependentContext())
7322 return true;
7323
7324 Expr::EvalStatus Status;
7325 Status.Diag = &Diags;
7326
7327 EvalInfo Info(FD->getASTContext(), Status);
7328 Info.CheckingPotentialConstantExpression = true;
7329
7330 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7331 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
7332
7333 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
7334 // is a temporary being used as the 'this' pointer.
7335 LValue This;
7336 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00007337 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00007338
Richard Smith253c2a32012-01-27 01:14:48 +00007339 ArrayRef<const Expr*> Args;
7340
7341 SourceLocation Loc = FD->getLocation();
7342
Richard Smith2e312c82012-03-03 22:46:17 +00007343 APValue Scratch;
7344 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith253c2a32012-01-27 01:14:48 +00007345 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith2e312c82012-03-03 22:46:17 +00007346 else
Richard Smith253c2a32012-01-27 01:14:48 +00007347 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
7348 Args, FD->getBody(), Info, Scratch);
7349
7350 return Diags.empty();
7351}