blob: 0f449854716752681c3b2fc65a603a7871178204 [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
Richard Smith861b5b52013-05-07 23:34:45 +000026// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27// too, why the expression could not be folded.
Richard Smith253c2a32012-01-27 01:14:48 +000028//
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 Smitha3d3bd22013-05-08 02:12:03 +0000383 /// StepsLeft - The remaining number of evaluation steps we're permitted
384 /// to perform. This is essentially a limit for the number of statements
385 /// we will evaluate.
386 unsigned StepsLeft;
387
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000388 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000389 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000390 CallStackFrame BottomFrame;
391
Richard Smithd62306a2011-11-10 06:34:14 +0000392 /// EvaluatingDecl - This is the declaration whose initializer is being
393 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000394 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000395
396 /// EvaluatingDeclValue - This is the value being constructed for the
397 /// declaration whose initializer is being evaluated, if any.
398 APValue *EvaluatingDeclValue;
399
Richard Smith357362d2011-12-13 06:39:58 +0000400 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
401 /// notes attached to it will also be stored, otherwise they will not be.
402 bool HasActiveDiagnostic;
403
Richard Smith253c2a32012-01-27 01:14:48 +0000404 /// CheckingPotentialConstantExpression - Are we checking whether the
405 /// expression is a potential constant expression? If so, some diagnostics
406 /// are suppressed.
407 bool CheckingPotentialConstantExpression;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000408
409 bool IntOverflowCheckMode;
Richard Smith253c2a32012-01-27 01:14:48 +0000410
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000411 EvalInfo(const ASTContext &C, Expr::EvalStatus &S,
Richard Smitha3d3bd22013-05-08 02:12:03 +0000412 bool OverflowCheckMode = false)
Richard Smith92b1ce02011-12-12 09:28:41 +0000413 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smithb228a862012-02-15 02:18:13 +0000414 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000415 StepsLeft(getLangOpts().ConstexprStepLimit),
Richard Smithb228a862012-02-15 02:18:13 +0000416 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith7525ff62013-05-09 07:14:00 +0000417 EvaluatingDecl((const ValueDecl*)0), EvaluatingDeclValue(0),
418 HasActiveDiagnostic(false), CheckingPotentialConstantExpression(false),
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000419 IntOverflowCheckMode(OverflowCheckMode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000420
Richard Smith7525ff62013-05-09 07:14:00 +0000421 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
422 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000423 EvaluatingDeclValue = &Value;
424 }
425
David Blaikiebbafb8a2012-03-11 07:00:24 +0000426 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000427
Richard Smith357362d2011-12-13 06:39:58 +0000428 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000429 // Don't perform any constexpr calls (other than the call we're checking)
430 // when checking a potential constant expression.
431 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
432 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000433 if (NextCallIndex == 0) {
434 // NextCallIndex has wrapped around.
435 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
436 return false;
437 }
Richard Smith357362d2011-12-13 06:39:58 +0000438 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
439 return true;
440 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
441 << getLangOpts().ConstexprCallDepth;
442 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000443 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000444
Richard Smithb228a862012-02-15 02:18:13 +0000445 CallStackFrame *getCallFrame(unsigned CallIndex) {
446 assert(CallIndex && "no call index in getCallFrame");
447 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
448 // be null in this loop.
449 CallStackFrame *Frame = CurrentCall;
450 while (Frame->Index > CallIndex)
451 Frame = Frame->Caller;
452 return (Frame->Index == CallIndex) ? Frame : 0;
453 }
454
Richard Smitha3d3bd22013-05-08 02:12:03 +0000455 bool nextStep(const Stmt *S) {
456 if (!StepsLeft) {
457 Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
458 return false;
459 }
460 --StepsLeft;
461 return true;
462 }
463
Richard Smith357362d2011-12-13 06:39:58 +0000464 private:
465 /// Add a diagnostic to the diagnostics list.
466 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
467 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
468 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
469 return EvalStatus.Diag->back().second;
470 }
471
Richard Smithf6f003a2011-12-16 19:06:07 +0000472 /// Add notes containing a call stack to the current point of evaluation.
473 void addCallStack(unsigned Limit);
474
Richard Smith357362d2011-12-13 06:39:58 +0000475 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000476 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000477 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
478 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000479 unsigned ExtraNotes = 0) {
Richard Smithf57d8cb2011-12-09 22:58:01 +0000480 // If we have a prior diagnostic, it will be noting that the expression
481 // isn't a constant expression. This diagnostic is more important.
482 // FIXME: We might want to show both diagnostics to the user.
Richard Smith92b1ce02011-12-12 09:28:41 +0000483 if (EvalStatus.Diag) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000484 unsigned CallStackNotes = CallStackDepth - 1;
485 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
486 if (Limit)
487 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith253c2a32012-01-27 01:14:48 +0000488 if (CheckingPotentialConstantExpression)
489 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000490
Richard Smith357362d2011-12-13 06:39:58 +0000491 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000492 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000493 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
494 addDiag(Loc, DiagId);
Richard Smith253c2a32012-01-27 01:14:48 +0000495 if (!CheckingPotentialConstantExpression)
496 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000497 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000498 }
Richard Smith357362d2011-12-13 06:39:58 +0000499 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000500 return OptionalDiagnostic();
501 }
502
Richard Smithce1ec5e2012-03-15 04:53:45 +0000503 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
504 = diag::note_invalid_subexpr_in_const_expr,
505 unsigned ExtraNotes = 0) {
506 if (EvalStatus.Diag)
507 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
508 HasActiveDiagnostic = false;
509 return OptionalDiagnostic();
510 }
511
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000512 bool getIntOverflowCheckMode() { return IntOverflowCheckMode; }
513
Richard Smith92b1ce02011-12-12 09:28:41 +0000514 /// Diagnose that the evaluation does not produce a C++11 core constant
515 /// expression.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000516 template<typename LocArg>
517 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000518 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000519 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000520 // Don't override a previous diagnostic.
Eli Friedmanebea9af2012-02-21 22:41:33 +0000521 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
522 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000523 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000524 }
Richard Smith357362d2011-12-13 06:39:58 +0000525 return Diag(Loc, DiagId, ExtraNotes);
526 }
527
528 /// Add a note to a prior diagnostic.
529 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
530 if (!HasActiveDiagnostic)
531 return OptionalDiagnostic();
532 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000533 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000534
535 /// Add a stack of notes to a prior diagnostic.
536 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
537 if (HasActiveDiagnostic) {
538 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
539 Diags.begin(), Diags.end());
540 }
541 }
Richard Smith253c2a32012-01-27 01:14:48 +0000542
543 /// Should we continue evaluation as much as possible after encountering a
544 /// construct which can't be folded?
545 bool keepEvaluatingAfterFailure() {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000546 // Should return true in IntOverflowCheckMode, so that we check for
547 // overflow even if some subexpressions can't be evaluated as constants.
Richard Smitha3d3bd22013-05-08 02:12:03 +0000548 return StepsLeft && (IntOverflowCheckMode ||
549 (CheckingPotentialConstantExpression &&
550 EvalStatus.Diag && EvalStatus.Diag->empty()));
Richard Smith253c2a32012-01-27 01:14:48 +0000551 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000552 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000553
554 /// Object used to treat all foldable expressions as constant expressions.
555 struct FoldConstant {
556 bool Enabled;
557
558 explicit FoldConstant(EvalInfo &Info)
559 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
560 !Info.EvalStatus.HasSideEffects) {
561 }
562 // Treat the value we've computed since this object was created as constant.
563 void Fold(EvalInfo &Info) {
564 if (Enabled && !Info.EvalStatus.Diag->empty() &&
565 !Info.EvalStatus.HasSideEffects)
566 Info.EvalStatus.Diag->clear();
567 }
568 };
Richard Smith17100ba2012-02-16 02:46:34 +0000569
570 /// RAII object used to suppress diagnostics and side-effects from a
571 /// speculative evaluation.
572 class SpeculativeEvaluationRAII {
573 EvalInfo &Info;
574 Expr::EvalStatus Old;
575
576 public:
577 SpeculativeEvaluationRAII(EvalInfo &Info,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000578 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = 0)
Richard Smith17100ba2012-02-16 02:46:34 +0000579 : Info(Info), Old(Info.EvalStatus) {
580 Info.EvalStatus.Diag = NewDiag;
581 }
582 ~SpeculativeEvaluationRAII() {
583 Info.EvalStatus = Old;
584 }
585 };
Richard Smithf6f003a2011-12-16 19:06:07 +0000586}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000587
Richard Smitha8105bc2012-01-06 16:39:00 +0000588bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
589 CheckSubobjectKind CSK) {
590 if (Invalid)
591 return false;
592 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000593 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000594 << CSK;
595 setInvalid();
596 return false;
597 }
598 return true;
599}
600
601void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
602 const Expr *E, uint64_t N) {
603 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000604 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000605 << static_cast<int>(N) << /*array*/ 0
606 << static_cast<unsigned>(MostDerivedArraySize);
607 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000608 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000609 << static_cast<int>(N) << /*non-array*/ 1;
610 setInvalid();
611}
612
Richard Smithf6f003a2011-12-16 19:06:07 +0000613CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
614 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000615 APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000616 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000617 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000618 Info.CurrentCall = this;
619 ++Info.CallStackDepth;
620}
621
622CallStackFrame::~CallStackFrame() {
623 assert(Info.CurrentCall == this && "calls retired out of order");
624 --Info.CallStackDepth;
625 Info.CurrentCall = Caller;
626}
627
628/// Produce a string describing the given constexpr call.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000629static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000630 unsigned ArgIndex = 0;
631 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith74388b42012-02-04 00:33:54 +0000632 !isa<CXXConstructorDecl>(Frame->Callee) &&
633 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smithf6f003a2011-12-16 19:06:07 +0000634
635 if (!IsMemberCall)
636 Out << *Frame->Callee << '(';
637
638 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
639 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumib8efa1e2012-01-26 09:37:36 +0000640 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smithf6f003a2011-12-16 19:06:07 +0000641 Out << ", ";
642
643 const ParmVarDecl *Param = *I;
Richard Smith2e312c82012-03-03 22:46:17 +0000644 const APValue &Arg = Frame->Arguments[ArgIndex];
645 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
Richard Smithf6f003a2011-12-16 19:06:07 +0000646
647 if (ArgIndex == 0 && IsMemberCall)
648 Out << "->" << *Frame->Callee << '(';
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000649 }
650
Richard Smithf6f003a2011-12-16 19:06:07 +0000651 Out << ')';
652}
653
654void EvalInfo::addCallStack(unsigned Limit) {
655 // Determine which calls to skip, if any.
656 unsigned ActiveCalls = CallStackDepth - 1;
657 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
658 if (Limit && Limit < ActiveCalls) {
659 SkipStart = Limit / 2 + Limit % 2;
660 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000661 }
662
Richard Smithf6f003a2011-12-16 19:06:07 +0000663 // Walk the call stack and add the diagnostics.
664 unsigned CallIdx = 0;
665 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
666 Frame = Frame->Caller, ++CallIdx) {
667 // Skip this call?
668 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
669 if (CallIdx == SkipStart) {
670 // Note that we're skipping calls.
671 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
672 << unsigned(ActiveCalls - Limit);
673 }
674 continue;
675 }
676
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000677 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +0000678 llvm::raw_svector_ostream Out(Buffer);
679 describeCall(Frame, Out);
680 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
681 }
682}
683
684namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000685 struct ComplexValue {
686 private:
687 bool IsInt;
688
689 public:
690 APSInt IntReal, IntImag;
691 APFloat FloatReal, FloatImag;
692
693 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
694
695 void makeComplexFloat() { IsInt = false; }
696 bool isComplexFloat() const { return !IsInt; }
697 APFloat &getComplexFloatReal() { return FloatReal; }
698 APFloat &getComplexFloatImag() { return FloatImag; }
699
700 void makeComplexInt() { IsInt = true; }
701 bool isComplexInt() const { return IsInt; }
702 APSInt &getComplexIntReal() { return IntReal; }
703 APSInt &getComplexIntImag() { return IntImag; }
704
Richard Smith2e312c82012-03-03 22:46:17 +0000705 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000706 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +0000707 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000708 else
Richard Smith2e312c82012-03-03 22:46:17 +0000709 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000710 }
Richard Smith2e312c82012-03-03 22:46:17 +0000711 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000712 assert(v.isComplexFloat() || v.isComplexInt());
713 if (v.isComplexFloat()) {
714 makeComplexFloat();
715 FloatReal = v.getComplexFloatReal();
716 FloatImag = v.getComplexFloatImag();
717 } else {
718 makeComplexInt();
719 IntReal = v.getComplexIntReal();
720 IntImag = v.getComplexIntImag();
721 }
722 }
John McCall93d91dc2010-05-07 17:22:02 +0000723 };
John McCall45d55e42010-05-07 21:00:08 +0000724
725 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000726 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000727 CharUnits Offset;
Richard Smithb228a862012-02-15 02:18:13 +0000728 unsigned CallIndex;
Richard Smith96e0c102011-11-04 02:25:55 +0000729 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000730
Richard Smithce40ad62011-11-12 22:28:03 +0000731 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000732 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000733 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +0000734 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +0000735 SubobjectDesignator &getLValueDesignator() { return Designator; }
736 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000737
Richard Smith2e312c82012-03-03 22:46:17 +0000738 void moveInto(APValue &V) const {
739 if (Designator.Invalid)
740 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
741 else
742 V = APValue(Base, Offset, Designator.Entries,
743 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000744 }
Richard Smith2e312c82012-03-03 22:46:17 +0000745 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000746 assert(V.isLValue());
747 Base = V.getLValueBase();
748 Offset = V.getLValueOffset();
Richard Smithb228a862012-02-15 02:18:13 +0000749 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +0000750 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +0000751 }
752
Richard Smithb228a862012-02-15 02:18:13 +0000753 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smithce40ad62011-11-12 22:28:03 +0000754 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000755 Offset = CharUnits::Zero();
Richard Smithb228a862012-02-15 02:18:13 +0000756 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +0000757 Designator = SubobjectDesignator(getType(B));
758 }
759
760 // Check that this LValue is not based on a null pointer. If it is, produce
761 // a diagnostic and mark the designator as invalid.
762 bool checkNullPointer(EvalInfo &Info, const Expr *E,
763 CheckSubobjectKind CSK) {
764 if (Designator.Invalid)
765 return false;
766 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000767 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000768 << CSK;
769 Designator.setInvalid();
770 return false;
771 }
772 return true;
773 }
774
775 // Check this LValue refers to an object. If not, set the designator to be
776 // invalid and emit a diagnostic.
777 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000778 // Outside C++11, do not build a designator referring to a subobject of
779 // any object: we won't use such a designator for anything.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000780 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000781 Designator.setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000782 return checkNullPointer(Info, E, CSK) &&
783 Designator.checkSubobject(Info, E, CSK);
784 }
785
786 void addDecl(EvalInfo &Info, const Expr *E,
787 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000788 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
789 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +0000790 }
791 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000792 if (checkSubobject(Info, E, CSK_ArrayToPointer))
793 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +0000794 }
Richard Smith66c96992012-02-18 22:04:06 +0000795 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000796 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
797 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +0000798 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000799 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000800 if (checkNullPointer(Info, E, CSK_ArrayIndex))
801 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +0000802 }
John McCall45d55e42010-05-07 21:00:08 +0000803 };
Richard Smith027bf112011-11-17 22:56:20 +0000804
805 struct MemberPtr {
806 MemberPtr() {}
807 explicit MemberPtr(const ValueDecl *Decl) :
808 DeclAndIsDerivedMember(Decl, false), Path() {}
809
810 /// The member or (direct or indirect) field referred to by this member
811 /// pointer, or 0 if this is a null member pointer.
812 const ValueDecl *getDecl() const {
813 return DeclAndIsDerivedMember.getPointer();
814 }
815 /// Is this actually a member of some type derived from the relevant class?
816 bool isDerivedMember() const {
817 return DeclAndIsDerivedMember.getInt();
818 }
819 /// Get the class which the declaration actually lives in.
820 const CXXRecordDecl *getContainingRecord() const {
821 return cast<CXXRecordDecl>(
822 DeclAndIsDerivedMember.getPointer()->getDeclContext());
823 }
824
Richard Smith2e312c82012-03-03 22:46:17 +0000825 void moveInto(APValue &V) const {
826 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +0000827 }
Richard Smith2e312c82012-03-03 22:46:17 +0000828 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +0000829 assert(V.isMemberPointer());
830 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
831 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
832 Path.clear();
833 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
834 Path.insert(Path.end(), P.begin(), P.end());
835 }
836
837 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
838 /// whether the member is a member of some class derived from the class type
839 /// of the member pointer.
840 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
841 /// Path - The path of base/derived classes from the member declaration's
842 /// class (exclusive) to the class type of the member pointer (inclusive).
843 SmallVector<const CXXRecordDecl*, 4> Path;
844
845 /// Perform a cast towards the class of the Decl (either up or down the
846 /// hierarchy).
847 bool castBack(const CXXRecordDecl *Class) {
848 assert(!Path.empty());
849 const CXXRecordDecl *Expected;
850 if (Path.size() >= 2)
851 Expected = Path[Path.size() - 2];
852 else
853 Expected = getContainingRecord();
854 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
855 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
856 // if B does not contain the original member and is not a base or
857 // derived class of the class containing the original member, the result
858 // of the cast is undefined.
859 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
860 // (D::*). We consider that to be a language defect.
861 return false;
862 }
863 Path.pop_back();
864 return true;
865 }
866 /// Perform a base-to-derived member pointer cast.
867 bool castToDerived(const CXXRecordDecl *Derived) {
868 if (!getDecl())
869 return true;
870 if (!isDerivedMember()) {
871 Path.push_back(Derived);
872 return true;
873 }
874 if (!castBack(Derived))
875 return false;
876 if (Path.empty())
877 DeclAndIsDerivedMember.setInt(false);
878 return true;
879 }
880 /// Perform a derived-to-base member pointer cast.
881 bool castToBase(const CXXRecordDecl *Base) {
882 if (!getDecl())
883 return true;
884 if (Path.empty())
885 DeclAndIsDerivedMember.setInt(true);
886 if (isDerivedMember()) {
887 Path.push_back(Base);
888 return true;
889 }
890 return castBack(Base);
891 }
892 };
Richard Smith357362d2011-12-13 06:39:58 +0000893
Richard Smith7bb00672012-02-01 01:42:44 +0000894 /// Compare two member pointers, which are assumed to be of the same type.
895 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
896 if (!LHS.getDecl() || !RHS.getDecl())
897 return !LHS.getDecl() && !RHS.getDecl();
898 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
899 return false;
900 return LHS.Path == RHS.Path;
901 }
John McCall93d91dc2010-05-07 17:22:02 +0000902}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000903
Richard Smith2e312c82012-03-03 22:46:17 +0000904static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +0000905static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
906 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +0000907 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +0000908static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
909static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +0000910static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
911 EvalInfo &Info);
912static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000913static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +0000914static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000915 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000916static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000917static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000918
919//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000920// Misc utilities
921//===----------------------------------------------------------------------===//
922
Richard Smithd9f663b2013-04-22 15:31:51 +0000923/// Evaluate an expression to see if it had side-effects, and discard its
924/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +0000925/// \return \c true if the caller should keep evaluating.
926static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000927 APValue Scratch;
Richard Smith4e18ca52013-05-06 05:56:11 +0000928 if (!Evaluate(Scratch, Info, E)) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000929 Info.EvalStatus.HasSideEffects = true;
Richard Smith4e18ca52013-05-06 05:56:11 +0000930 return Info.keepEvaluatingAfterFailure();
931 }
932 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +0000933}
934
Richard Smith861b5b52013-05-07 23:34:45 +0000935/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
936/// return its existing value.
937static int64_t getExtValue(const APSInt &Value) {
938 return Value.isSigned() ? Value.getSExtValue()
939 : static_cast<int64_t>(Value.getZExtValue());
940}
941
Richard Smithd62306a2011-11-10 06:34:14 +0000942/// Should this call expression be treated as a string literal?
943static bool IsStringLiteralCall(const CallExpr *E) {
944 unsigned Builtin = E->isBuiltinCall();
945 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
946 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
947}
948
Richard Smithce40ad62011-11-12 22:28:03 +0000949static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +0000950 // C++11 [expr.const]p3 An address constant expression is a prvalue core
951 // constant expression of pointer type that evaluates to...
952
953 // ... a null pointer value, or a prvalue core constant expression of type
954 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +0000955 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +0000956
Richard Smithce40ad62011-11-12 22:28:03 +0000957 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
958 // ... the address of an object with static storage duration,
959 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
960 return VD->hasGlobalStorage();
961 // ... the address of a function,
962 return isa<FunctionDecl>(D);
963 }
964
965 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +0000966 switch (E->getStmtClass()) {
967 default:
968 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +0000969 case Expr::CompoundLiteralExprClass: {
970 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
971 return CLE->isFileScope() && CLE->isLValue();
972 }
Richard Smithd62306a2011-11-10 06:34:14 +0000973 // A string literal has static storage duration.
974 case Expr::StringLiteralClass:
975 case Expr::PredefinedExprClass:
976 case Expr::ObjCStringLiteralClass:
977 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +0000978 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +0000979 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +0000980 return true;
981 case Expr::CallExprClass:
982 return IsStringLiteralCall(cast<CallExpr>(E));
983 // For GCC compatibility, &&label has static storage duration.
984 case Expr::AddrLabelExprClass:
985 return true;
986 // A Block literal expression may be used as the initialization value for
987 // Block variables at global or local static scope.
988 case Expr::BlockExprClass:
989 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +0000990 case Expr::ImplicitValueInitExprClass:
991 // FIXME:
992 // We can never form an lvalue with an implicit value initialization as its
993 // base through expression evaluation, so these only appear in one case: the
994 // implicit variable declaration we invent when checking whether a constexpr
995 // constructor can produce a constant expression. We must assume that such
996 // an expression might be a global lvalue.
997 return true;
Richard Smithd62306a2011-11-10 06:34:14 +0000998 }
John McCall95007602010-05-10 23:27:23 +0000999}
1000
Richard Smithb228a862012-02-15 02:18:13 +00001001static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1002 assert(Base && "no location for a null lvalue");
1003 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1004 if (VD)
1005 Info.Note(VD->getLocation(), diag::note_declared_at);
1006 else
Ted Kremenek28831752012-08-23 20:46:57 +00001007 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001008 diag::note_constexpr_temporary_here);
1009}
1010
Richard Smith80815602011-11-07 05:07:52 +00001011/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001012/// value for an address or reference constant expression. Return true if we
1013/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001014static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1015 QualType Type, const LValue &LVal) {
1016 bool IsReferenceType = Type->isReferenceType();
1017
Richard Smith357362d2011-12-13 06:39:58 +00001018 APValue::LValueBase Base = LVal.getLValueBase();
1019 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1020
Richard Smith0dea49e2012-02-18 04:58:18 +00001021 // Check that the object is a global. Note that the fake 'this' object we
1022 // manufacture when checking potential constant expressions is conservatively
1023 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001024 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001025 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001026 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001027 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1028 << IsReferenceType << !Designator.Entries.empty()
1029 << !!VD << VD;
1030 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001031 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001032 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001033 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001034 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001035 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001036 }
Richard Smithb228a862012-02-15 02:18:13 +00001037 assert((Info.CheckingPotentialConstantExpression ||
1038 LVal.getLValueCallIndex() == 0) &&
1039 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001040
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001041 // Check if this is a thread-local variable.
1042 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1043 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
Richard Smithfd3834f2013-04-13 02:43:54 +00001044 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001045 return false;
1046 }
1047 }
1048
Richard Smitha8105bc2012-01-06 16:39:00 +00001049 // Allow address constant expressions to be past-the-end pointers. This is
1050 // an extension: the standard requires them to point to an object.
1051 if (!IsReferenceType)
1052 return true;
1053
1054 // A reference constant expression must refer to an object.
1055 if (!Base) {
1056 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001057 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001058 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001059 }
1060
Richard Smith357362d2011-12-13 06:39:58 +00001061 // Does this refer one past the end of some object?
Richard Smitha8105bc2012-01-06 16:39:00 +00001062 if (Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001063 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001064 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001065 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001066 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001067 }
1068
Richard Smith80815602011-11-07 05:07:52 +00001069 return true;
1070}
1071
Richard Smithfddd3842011-12-30 21:15:51 +00001072/// Check that this core constant expression is of literal type, and if not,
1073/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001074static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1075 const LValue *This = 0) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001076 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001077 return true;
1078
Richard Smith7525ff62013-05-09 07:14:00 +00001079 // C++1y: A constant initializer for an object o [...] may also invoke
1080 // constexpr constructors for o and its subobjects even if those objects
1081 // are of non-literal class types.
1082 if (Info.getLangOpts().CPlusPlus1y && This &&
1083 Info.EvaluatingDecl.getOpaqueValue() ==
1084 This->getLValueBase().getOpaqueValue())
1085 return true;
1086
Richard Smithfddd3842011-12-30 21:15:51 +00001087 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001088 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001089 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001090 << E->getType();
1091 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001092 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001093 return false;
1094}
1095
Richard Smith0b0a0b62011-10-29 20:57:55 +00001096/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001097/// constant expression. If not, report an appropriate diagnostic. Does not
1098/// check that the expression is of literal type.
1099static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1100 QualType Type, const APValue &Value) {
1101 // Core issue 1454: For a literal constant expression of array or class type,
1102 // each subobject of its value shall have been initialized by a constant
1103 // expression.
1104 if (Value.isArray()) {
1105 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1106 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1107 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1108 Value.getArrayInitializedElt(I)))
1109 return false;
1110 }
1111 if (!Value.hasArrayFiller())
1112 return true;
1113 return CheckConstantExpression(Info, DiagLoc, EltTy,
1114 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001115 }
Richard Smithb228a862012-02-15 02:18:13 +00001116 if (Value.isUnion() && Value.getUnionField()) {
1117 return CheckConstantExpression(Info, DiagLoc,
1118 Value.getUnionField()->getType(),
1119 Value.getUnionValue());
1120 }
1121 if (Value.isStruct()) {
1122 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1123 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1124 unsigned BaseIndex = 0;
1125 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1126 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1127 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1128 Value.getStructBase(BaseIndex)))
1129 return false;
1130 }
1131 }
1132 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1133 I != E; ++I) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001134 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1135 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001136 return false;
1137 }
1138 }
1139
1140 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001141 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001142 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001143 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1144 }
1145
1146 // Everything else is fine.
1147 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001148}
1149
Richard Smith83c68212011-10-31 05:11:32 +00001150const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001151 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001152}
1153
1154static bool IsLiteralLValue(const LValue &Value) {
Richard Smithb228a862012-02-15 02:18:13 +00001155 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith83c68212011-10-31 05:11:32 +00001156}
1157
Richard Smithcecf1842011-11-01 21:06:14 +00001158static bool IsWeakLValue(const LValue &Value) {
1159 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001160 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001161}
1162
Richard Smith2e312c82012-03-03 22:46:17 +00001163static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001164 // A null base expression indicates a null pointer. These are always
1165 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001166 if (!Value.getLValueBase()) {
1167 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001168 return true;
1169 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001170
Richard Smith027bf112011-11-17 22:56:20 +00001171 // We have a non-null base. These are generally known to be true, but if it's
1172 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001173 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001174 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001175 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001176}
1177
Richard Smith2e312c82012-03-03 22:46:17 +00001178static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001179 switch (Val.getKind()) {
1180 case APValue::Uninitialized:
1181 return false;
1182 case APValue::Int:
1183 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001184 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001185 case APValue::Float:
1186 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001187 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001188 case APValue::ComplexInt:
1189 Result = Val.getComplexIntReal().getBoolValue() ||
1190 Val.getComplexIntImag().getBoolValue();
1191 return true;
1192 case APValue::ComplexFloat:
1193 Result = !Val.getComplexFloatReal().isZero() ||
1194 !Val.getComplexFloatImag().isZero();
1195 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001196 case APValue::LValue:
1197 return EvalPointerValueAsBool(Val, Result);
1198 case APValue::MemberPointer:
1199 Result = Val.getMemberPointerDecl();
1200 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001201 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001202 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001203 case APValue::Struct:
1204 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001205 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001206 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001207 }
1208
Richard Smith11562c52011-10-28 17:51:58 +00001209 llvm_unreachable("unknown APValue kind");
1210}
1211
1212static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1213 EvalInfo &Info) {
1214 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001215 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001216 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001217 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001218 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001219}
1220
Richard Smith357362d2011-12-13 06:39:58 +00001221template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001222static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001223 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001224 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001225 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001226}
1227
1228static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1229 QualType SrcType, const APFloat &Value,
1230 QualType DestType, APSInt &Result) {
1231 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001232 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001233 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001234
Richard Smith357362d2011-12-13 06:39:58 +00001235 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001236 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001237 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1238 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001239 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001240 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001241}
1242
Richard Smith357362d2011-12-13 06:39:58 +00001243static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1244 QualType SrcType, QualType DestType,
1245 APFloat &Result) {
1246 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001247 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001248 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1249 APFloat::rmNearestTiesToEven, &ignored)
1250 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001251 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001252 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001253}
1254
Richard Smith911e1422012-01-30 22:27:01 +00001255static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1256 QualType DestType, QualType SrcType,
1257 APSInt &Value) {
1258 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001259 APSInt Result = Value;
1260 // Figure out if this is a truncate, extend or noop cast.
1261 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001262 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001263 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001264 return Result;
1265}
1266
Richard Smith357362d2011-12-13 06:39:58 +00001267static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1268 QualType SrcType, const APSInt &Value,
1269 QualType DestType, APFloat &Result) {
1270 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1271 if (Result.convertFromAPInt(Value, Value.isSigned(),
1272 APFloat::rmNearestTiesToEven)
1273 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001274 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001275 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001276}
1277
Eli Friedman803acb32011-12-22 03:51:45 +00001278static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1279 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001280 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001281 if (!Evaluate(SVal, Info, E))
1282 return false;
1283 if (SVal.isInt()) {
1284 Res = SVal.getInt();
1285 return true;
1286 }
1287 if (SVal.isFloat()) {
1288 Res = SVal.getFloat().bitcastToAPInt();
1289 return true;
1290 }
1291 if (SVal.isVector()) {
1292 QualType VecTy = E->getType();
1293 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1294 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1295 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1296 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1297 Res = llvm::APInt::getNullValue(VecSize);
1298 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1299 APValue &Elt = SVal.getVectorElt(i);
1300 llvm::APInt EltAsInt;
1301 if (Elt.isInt()) {
1302 EltAsInt = Elt.getInt();
1303 } else if (Elt.isFloat()) {
1304 EltAsInt = Elt.getFloat().bitcastToAPInt();
1305 } else {
1306 // Don't try to handle vectors of anything other than int or float
1307 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001308 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001309 return false;
1310 }
1311 unsigned BaseEltSize = EltAsInt.getBitWidth();
1312 if (BigEndian)
1313 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1314 else
1315 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1316 }
1317 return true;
1318 }
1319 // Give up if the input isn't an int, float, or vector. For example, we
1320 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001321 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001322 return false;
1323}
1324
Richard Smith43e77732013-05-07 04:50:00 +00001325/// Perform the given integer operation, which is known to need at most BitWidth
1326/// bits, and check for overflow in the original type (if that type was not an
1327/// unsigned type).
1328template<typename Operation>
1329static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1330 const APSInt &LHS, const APSInt &RHS,
1331 unsigned BitWidth, Operation Op) {
1332 if (LHS.isUnsigned())
1333 return Op(LHS, RHS);
1334
1335 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1336 APSInt Result = Value.trunc(LHS.getBitWidth());
1337 if (Result.extend(BitWidth) != Value) {
1338 if (Info.getIntOverflowCheckMode())
1339 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1340 diag::warn_integer_constant_overflow)
1341 << Result.toString(10) << E->getType();
1342 else
1343 HandleOverflow(Info, E, Value, E->getType());
1344 }
1345 return Result;
1346}
1347
1348/// Perform the given binary integer operation.
1349static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1350 BinaryOperatorKind Opcode, APSInt RHS,
1351 APSInt &Result) {
1352 switch (Opcode) {
1353 default:
1354 Info.Diag(E);
1355 return false;
1356 case BO_Mul:
1357 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1358 std::multiplies<APSInt>());
1359 return true;
1360 case BO_Add:
1361 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1362 std::plus<APSInt>());
1363 return true;
1364 case BO_Sub:
1365 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1366 std::minus<APSInt>());
1367 return true;
1368 case BO_And: Result = LHS & RHS; return true;
1369 case BO_Xor: Result = LHS ^ RHS; return true;
1370 case BO_Or: Result = LHS | RHS; return true;
1371 case BO_Div:
1372 case BO_Rem:
1373 if (RHS == 0) {
1374 Info.Diag(E, diag::note_expr_divide_by_zero);
1375 return false;
1376 }
1377 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1378 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1379 LHS.isSigned() && LHS.isMinSignedValue())
1380 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1381 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1382 return true;
1383 case BO_Shl: {
1384 if (Info.getLangOpts().OpenCL)
1385 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1386 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1387 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1388 RHS.isUnsigned());
1389 else if (RHS.isSigned() && RHS.isNegative()) {
1390 // During constant-folding, a negative shift is an opposite shift. Such
1391 // a shift is not a constant expression.
1392 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1393 RHS = -RHS;
1394 goto shift_right;
1395 }
1396 shift_left:
1397 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1398 // the shifted type.
1399 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1400 if (SA != RHS) {
1401 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1402 << RHS << E->getType() << LHS.getBitWidth();
1403 } else if (LHS.isSigned()) {
1404 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1405 // operand, and must not overflow the corresponding unsigned type.
1406 if (LHS.isNegative())
1407 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1408 else if (LHS.countLeadingZeros() < SA)
1409 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1410 }
1411 Result = LHS << SA;
1412 return true;
1413 }
1414 case BO_Shr: {
1415 if (Info.getLangOpts().OpenCL)
1416 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1417 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1418 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1419 RHS.isUnsigned());
1420 else if (RHS.isSigned() && RHS.isNegative()) {
1421 // During constant-folding, a negative shift is an opposite shift. Such a
1422 // shift is not a constant expression.
1423 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1424 RHS = -RHS;
1425 goto shift_left;
1426 }
1427 shift_right:
1428 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1429 // shifted type.
1430 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1431 if (SA != RHS)
1432 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1433 << RHS << E->getType() << LHS.getBitWidth();
1434 Result = LHS >> SA;
1435 return true;
1436 }
1437
1438 case BO_LT: Result = LHS < RHS; return true;
1439 case BO_GT: Result = LHS > RHS; return true;
1440 case BO_LE: Result = LHS <= RHS; return true;
1441 case BO_GE: Result = LHS >= RHS; return true;
1442 case BO_EQ: Result = LHS == RHS; return true;
1443 case BO_NE: Result = LHS != RHS; return true;
1444 }
1445}
1446
Richard Smith861b5b52013-05-07 23:34:45 +00001447/// Perform the given binary floating-point operation, in-place, on LHS.
1448static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1449 APFloat &LHS, BinaryOperatorKind Opcode,
1450 const APFloat &RHS) {
1451 switch (Opcode) {
1452 default:
1453 Info.Diag(E);
1454 return false;
1455 case BO_Mul:
1456 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1457 break;
1458 case BO_Add:
1459 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1460 break;
1461 case BO_Sub:
1462 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1463 break;
1464 case BO_Div:
1465 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1466 break;
1467 }
1468
1469 if (LHS.isInfinity() || LHS.isNaN())
1470 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1471 return true;
1472}
1473
Richard Smitha8105bc2012-01-06 16:39:00 +00001474/// Cast an lvalue referring to a base subobject to a derived class, by
1475/// truncating the lvalue's path to the given length.
1476static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1477 const RecordDecl *TruncatedType,
1478 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001479 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001480
1481 // Check we actually point to a derived class object.
1482 if (TruncatedElements == D.Entries.size())
1483 return true;
1484 assert(TruncatedElements >= D.MostDerivedPathLength &&
1485 "not casting to a derived class");
1486 if (!Result.checkSubobject(Info, E, CSK_Derived))
1487 return false;
1488
1489 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001490 const RecordDecl *RD = TruncatedType;
1491 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001492 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001493 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1494 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001495 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001496 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001497 else
Richard Smithd62306a2011-11-10 06:34:14 +00001498 Result.Offset -= Layout.getBaseClassOffset(Base);
1499 RD = Base;
1500 }
Richard Smith027bf112011-11-17 22:56:20 +00001501 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001502 return true;
1503}
1504
John McCalld7bca762012-05-01 00:38:49 +00001505static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001506 const CXXRecordDecl *Derived,
1507 const CXXRecordDecl *Base,
1508 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001509 if (!RL) {
1510 if (Derived->isInvalidDecl()) return false;
1511 RL = &Info.Ctx.getASTRecordLayout(Derived);
1512 }
1513
Richard Smithd62306a2011-11-10 06:34:14 +00001514 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001515 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001516 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001517}
1518
Richard Smitha8105bc2012-01-06 16:39:00 +00001519static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001520 const CXXRecordDecl *DerivedDecl,
1521 const CXXBaseSpecifier *Base) {
1522 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1523
John McCalld7bca762012-05-01 00:38:49 +00001524 if (!Base->isVirtual())
1525 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001526
Richard Smitha8105bc2012-01-06 16:39:00 +00001527 SubobjectDesignator &D = Obj.Designator;
1528 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001529 return false;
1530
Richard Smitha8105bc2012-01-06 16:39:00 +00001531 // Extract most-derived object and corresponding type.
1532 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1533 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1534 return false;
1535
1536 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001537 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001538 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1539 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001540 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001541 return true;
1542}
1543
1544/// Update LVal to refer to the given field, which must be a member of the type
1545/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001546static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001547 const FieldDecl *FD,
1548 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001549 if (!RL) {
1550 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001551 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001552 }
Richard Smithd62306a2011-11-10 06:34:14 +00001553
1554 unsigned I = FD->getFieldIndex();
1555 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001556 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001557 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001558}
1559
Richard Smith1b78b3d2012-01-25 22:15:11 +00001560/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001561static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001562 LValue &LVal,
1563 const IndirectFieldDecl *IFD) {
1564 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1565 CE = IFD->chain_end(); C != CE; ++C)
John McCalld7bca762012-05-01 00:38:49 +00001566 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1567 return false;
1568 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001569}
1570
Richard Smithd62306a2011-11-10 06:34:14 +00001571/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001572static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1573 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001574 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1575 // extension.
1576 if (Type->isVoidType() || Type->isFunctionType()) {
1577 Size = CharUnits::One();
1578 return true;
1579 }
1580
1581 if (!Type->isConstantSizeType()) {
1582 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001583 // FIXME: Better diagnostic.
1584 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001585 return false;
1586 }
1587
1588 Size = Info.Ctx.getTypeSizeInChars(Type);
1589 return true;
1590}
1591
1592/// Update a pointer value to model pointer arithmetic.
1593/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001594/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001595/// \param LVal - The pointer value to be updated.
1596/// \param EltTy - The pointee type represented by LVal.
1597/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001598static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1599 LValue &LVal, QualType EltTy,
1600 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001601 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001602 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001603 return false;
1604
1605 // Compute the new offset in the appropriate width.
1606 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001607 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001608 return true;
1609}
1610
Richard Smith66c96992012-02-18 22:04:06 +00001611/// Update an lvalue to refer to a component of a complex number.
1612/// \param Info - Information about the ongoing evaluation.
1613/// \param LVal - The lvalue to be updated.
1614/// \param EltTy - The complex number's component type.
1615/// \param Imag - False for the real component, true for the imaginary.
1616static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1617 LValue &LVal, QualType EltTy,
1618 bool Imag) {
1619 if (Imag) {
1620 CharUnits SizeOfComponent;
1621 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1622 return false;
1623 LVal.Offset += SizeOfComponent;
1624 }
1625 LVal.addComplex(Info, E, EltTy, Imag);
1626 return true;
1627}
1628
Richard Smith27908702011-10-24 17:54:18 +00001629/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001630///
1631/// \param Info Information about the ongoing evaluation.
1632/// \param E An expression to be used when printing diagnostics.
1633/// \param VD The variable whose initializer should be obtained.
1634/// \param Frame The frame in which the variable was created. Must be null
1635/// if this variable is not local to the evaluation.
1636/// \param Result Filled in with a pointer to the value of the variable.
1637static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1638 const VarDecl *VD, CallStackFrame *Frame,
1639 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001640 // If this is a parameter to an active constexpr function call, perform
1641 // argument substitution.
1642 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001643 // Assume arguments of a potential constant expression are unknown
1644 // constant expressions.
1645 if (Info.CheckingPotentialConstantExpression)
1646 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001647 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001648 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001649 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001650 }
Richard Smith3229b742013-05-05 21:17:10 +00001651 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00001652 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001653 }
Richard Smith27908702011-10-24 17:54:18 +00001654
Richard Smithd9f663b2013-04-22 15:31:51 +00001655 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00001656 if (Frame) {
1657 Result = &Frame->Temporaries[VD];
Richard Smithd9f663b2013-04-22 15:31:51 +00001658 // If we've carried on past an unevaluatable local variable initializer,
1659 // we can't go any further. This can happen during potential constant
1660 // expression checking.
Richard Smith3229b742013-05-05 21:17:10 +00001661 return !Result->isUninit();
Richard Smithd9f663b2013-04-22 15:31:51 +00001662 }
1663
Richard Smithd0b4dd62011-12-19 06:19:21 +00001664 // Dig out the initializer, and use the declaration which it's attached to.
1665 const Expr *Init = VD->getAnyInitializer(VD);
1666 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001667 // If we're checking a potential constant expression, the variable could be
1668 // initialized later.
1669 if (!Info.CheckingPotentialConstantExpression)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001670 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001671 return false;
1672 }
1673
Richard Smithd62306a2011-11-10 06:34:14 +00001674 // If we're currently evaluating the initializer of this declaration, use that
1675 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00001676 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00001677 Result = Info.EvaluatingDeclValue;
1678 return !Result->isUninit();
Richard Smithd62306a2011-11-10 06:34:14 +00001679 }
1680
Richard Smithcecf1842011-11-01 21:06:14 +00001681 // Never evaluate the initializer of a weak variable. We can't be sure that
1682 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001683 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001684 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001685 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001686 }
Richard Smithcecf1842011-11-01 21:06:14 +00001687
Richard Smithd0b4dd62011-12-19 06:19:21 +00001688 // Check that we can fold the initializer. In C++, we will have already done
1689 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001690 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001691 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001692 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001693 Notes.size() + 1) << VD;
1694 Info.Note(VD->getLocation(), diag::note_declared_at);
1695 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001696 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001697 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001698 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001699 Notes.size() + 1) << VD;
1700 Info.Note(VD->getLocation(), diag::note_declared_at);
1701 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001702 }
Richard Smith27908702011-10-24 17:54:18 +00001703
Richard Smith3229b742013-05-05 21:17:10 +00001704 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001705 return true;
Richard Smith27908702011-10-24 17:54:18 +00001706}
1707
Richard Smith11562c52011-10-28 17:51:58 +00001708static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001709 Qualifiers Quals = T.getQualifiers();
1710 return Quals.hasConst() && !Quals.hasVolatile();
1711}
1712
Richard Smithe97cbd72011-11-11 04:05:33 +00001713/// Get the base index of the given base class within an APValue representing
1714/// the given derived class.
1715static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1716 const CXXRecordDecl *Base) {
1717 Base = Base->getCanonicalDecl();
1718 unsigned Index = 0;
1719 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1720 E = Derived->bases_end(); I != E; ++I, ++Index) {
1721 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1722 return Index;
1723 }
1724
1725 llvm_unreachable("base class missing from derived class's bases list");
1726}
1727
Richard Smith3da88fa2013-04-26 14:36:30 +00001728/// Extract the value of a character from a string literal.
1729static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1730 uint64_t Index) {
Richard Smith14a94132012-02-17 03:35:37 +00001731 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith3da88fa2013-04-26 14:36:30 +00001732 const StringLiteral *S = cast<StringLiteral>(Lit);
1733 const ConstantArrayType *CAT =
1734 Info.Ctx.getAsConstantArrayType(S->getType());
1735 assert(CAT && "string literal isn't an array");
1736 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00001737 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00001738
1739 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00001740 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00001741 if (Index < S->getLength())
1742 Value = S->getCodeUnit(Index);
1743 return Value;
1744}
1745
Richard Smith3da88fa2013-04-26 14:36:30 +00001746// Expand a string literal into an array of characters.
1747static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
1748 APValue &Result) {
1749 const StringLiteral *S = cast<StringLiteral>(Lit);
1750 const ConstantArrayType *CAT =
1751 Info.Ctx.getAsConstantArrayType(S->getType());
1752 assert(CAT && "string literal isn't an array");
1753 QualType CharType = CAT->getElementType();
1754 assert(CharType->isIntegerType() && "unexpected character type");
1755
1756 unsigned Elts = CAT->getSize().getZExtValue();
1757 Result = APValue(APValue::UninitArray(),
1758 std::min(S->getLength(), Elts), Elts);
1759 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1760 CharType->isUnsignedIntegerType());
1761 if (Result.hasArrayFiller())
1762 Result.getArrayFiller() = APValue(Value);
1763 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
1764 Value = S->getCodeUnit(I);
1765 Result.getArrayInitializedElt(I) = APValue(Value);
1766 }
1767}
1768
1769// Expand an array so that it has more than Index filled elements.
1770static void expandArray(APValue &Array, unsigned Index) {
1771 unsigned Size = Array.getArraySize();
1772 assert(Index < Size);
1773
1774 // Always at least double the number of elements for which we store a value.
1775 unsigned OldElts = Array.getArrayInitializedElts();
1776 unsigned NewElts = std::max(Index+1, OldElts * 2);
1777 NewElts = std::min(Size, std::max(NewElts, 8u));
1778
1779 // Copy the data across.
1780 APValue NewValue(APValue::UninitArray(), NewElts, Size);
1781 for (unsigned I = 0; I != OldElts; ++I)
1782 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
1783 for (unsigned I = OldElts; I != NewElts; ++I)
1784 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
1785 if (NewValue.hasArrayFiller())
1786 NewValue.getArrayFiller() = Array.getArrayFiller();
1787 Array.swap(NewValue);
1788}
1789
Richard Smith861b5b52013-05-07 23:34:45 +00001790/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00001791enum AccessKinds {
1792 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00001793 AK_Assign,
1794 AK_Increment,
1795 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00001796};
1797
Richard Smith3229b742013-05-05 21:17:10 +00001798/// A handle to a complete object (an object that is not a subobject of
1799/// another object).
1800struct CompleteObject {
1801 /// The value of the complete object.
1802 APValue *Value;
1803 /// The type of the complete object.
1804 QualType Type;
1805
1806 CompleteObject() : Value(0) {}
1807 CompleteObject(APValue *Value, QualType Type)
1808 : Value(Value), Type(Type) {
1809 assert(Value && "missing value for complete object");
1810 }
1811
1812 operator bool() const { return Value; }
1813};
1814
Richard Smith3da88fa2013-04-26 14:36:30 +00001815/// Find the designated sub-object of an rvalue.
1816template<typename SubobjectHandler>
1817typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00001818findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00001819 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001820 if (Sub.Invalid)
1821 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00001822 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00001823 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001824 if (Info.getLangOpts().CPlusPlus11)
1825 Info.Diag(E, diag::note_constexpr_access_past_end)
1826 << handler.AccessKind;
1827 else
1828 Info.Diag(E);
1829 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001830 }
Richard Smith6804be52011-11-11 08:28:03 +00001831 if (Sub.Entries.empty())
Richard Smith3229b742013-05-05 21:17:10 +00001832 return handler.found(*Obj.Value, Obj.Type);
1833 if (Info.CheckingPotentialConstantExpression && Obj.Value->isUninit())
Richard Smith253c2a32012-01-27 01:14:48 +00001834 // This object might be initialized later.
Richard Smith3da88fa2013-04-26 14:36:30 +00001835 return handler.failed();
Richard Smithf3e9e432011-11-07 09:22:26 +00001836
Richard Smith3229b742013-05-05 21:17:10 +00001837 APValue *O = Obj.Value;
1838 QualType ObjType = Obj.Type;
Richard Smithd62306a2011-11-10 06:34:14 +00001839 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001840 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001841 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001842 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001843 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001844 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001845 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001846 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001847 // Note, it should not be possible to form a pointer with a valid
1848 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00001849 if (Info.getLangOpts().CPlusPlus11)
1850 Info.Diag(E, diag::note_constexpr_access_past_end)
1851 << handler.AccessKind;
1852 else
1853 Info.Diag(E);
1854 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001855 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001856
1857 ObjType = CAT->getElementType();
1858
Richard Smith14a94132012-02-17 03:35:37 +00001859 // An array object is represented as either an Array APValue or as an
1860 // LValue which refers to a string literal.
1861 if (O->isLValue()) {
1862 assert(I == N - 1 && "extracting subobject of character?");
1863 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00001864 if (handler.AccessKind != AK_Read)
1865 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
1866 *O);
1867 else
1868 return handler.foundString(*O, ObjType, Index);
1869 }
1870
1871 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00001872 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00001873 else if (handler.AccessKind != AK_Read) {
1874 expandArray(*O, Index);
1875 O = &O->getArrayInitializedElt(Index);
1876 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00001877 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00001878 } else if (ObjType->isAnyComplexType()) {
1879 // Next subobject is a complex number.
1880 uint64_t Index = Sub.Entries[I].ArrayIndex;
1881 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001882 if (Info.getLangOpts().CPlusPlus11)
1883 Info.Diag(E, diag::note_constexpr_access_past_end)
1884 << handler.AccessKind;
1885 else
1886 Info.Diag(E);
1887 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00001888 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001889
1890 bool WasConstQualified = ObjType.isConstQualified();
1891 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1892 if (WasConstQualified)
1893 ObjType.addConst();
1894
Richard Smith66c96992012-02-18 22:04:06 +00001895 assert(I == N - 1 && "extracting subobject of scalar?");
1896 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001897 return handler.found(Index ? O->getComplexIntImag()
1898 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001899 } else {
1900 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00001901 return handler.found(Index ? O->getComplexFloatImag()
1902 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001903 }
Richard Smithd62306a2011-11-10 06:34:14 +00001904 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001905 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001906 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00001907 << Field;
1908 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00001909 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00001910 }
1911
Richard Smithd62306a2011-11-10 06:34:14 +00001912 // Next subobject is a class, struct or union field.
1913 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1914 if (RD->isUnion()) {
1915 const FieldDecl *UnionField = O->getUnionField();
1916 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001917 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001918 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
1919 << handler.AccessKind << Field << !UnionField << UnionField;
1920 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001921 }
Richard Smithd62306a2011-11-10 06:34:14 +00001922 O = &O->getUnionValue();
1923 } else
1924 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00001925
1926 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00001927 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00001928 if (WasConstQualified && !Field->isMutable())
1929 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00001930
1931 if (ObjType.isVolatileQualified()) {
1932 if (Info.getLangOpts().CPlusPlus) {
1933 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00001934 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
1935 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00001936 Info.Note(Field->getLocation(), diag::note_declared_at);
1937 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001938 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001939 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001940 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001941 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001942 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001943 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001944 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1945 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1946 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00001947
1948 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00001949 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00001950 if (WasConstQualified)
1951 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00001952 }
Richard Smithd62306a2011-11-10 06:34:14 +00001953
Richard Smithf57d8cb2011-12-09 22:58:01 +00001954 if (O->isUninit()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001955 if (!Info.CheckingPotentialConstantExpression)
Richard Smith3da88fa2013-04-26 14:36:30 +00001956 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
1957 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001958 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001959 }
1960
Richard Smith3da88fa2013-04-26 14:36:30 +00001961 return handler.found(*O, ObjType);
1962}
1963
Benjamin Kramer62498ab2013-04-26 22:01:47 +00001964namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00001965struct ExtractSubobjectHandler {
1966 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00001967 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00001968
1969 static const AccessKinds AccessKind = AK_Read;
1970
1971 typedef bool result_type;
1972 bool failed() { return false; }
1973 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00001974 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00001975 return true;
1976 }
1977 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00001978 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00001979 return true;
1980 }
1981 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00001982 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00001983 return true;
1984 }
1985 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00001986 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00001987 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
1988 return true;
1989 }
1990};
Richard Smith3229b742013-05-05 21:17:10 +00001991} // end anonymous namespace
1992
Richard Smith3da88fa2013-04-26 14:36:30 +00001993const AccessKinds ExtractSubobjectHandler::AccessKind;
1994
1995/// Extract the designated sub-object of an rvalue.
1996static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00001997 const CompleteObject &Obj,
1998 const SubobjectDesignator &Sub,
1999 APValue &Result) {
2000 ExtractSubobjectHandler Handler = { Info, Result };
2001 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002002}
2003
Richard Smith3229b742013-05-05 21:17:10 +00002004namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002005struct ModifySubobjectHandler {
2006 EvalInfo &Info;
2007 APValue &NewVal;
2008 const Expr *E;
2009
2010 typedef bool result_type;
2011 static const AccessKinds AccessKind = AK_Assign;
2012
2013 bool checkConst(QualType QT) {
2014 // Assigning to a const object has undefined behavior.
2015 if (QT.isConstQualified()) {
2016 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2017 return false;
2018 }
2019 return true;
2020 }
2021
2022 bool failed() { return false; }
2023 bool found(APValue &Subobj, QualType SubobjType) {
2024 if (!checkConst(SubobjType))
2025 return false;
2026 // We've been given ownership of NewVal, so just swap it in.
2027 Subobj.swap(NewVal);
2028 return true;
2029 }
2030 bool found(APSInt &Value, QualType SubobjType) {
2031 if (!checkConst(SubobjType))
2032 return false;
2033 if (!NewVal.isInt()) {
2034 // Maybe trying to write a cast pointer value into a complex?
2035 Info.Diag(E);
2036 return false;
2037 }
2038 Value = NewVal.getInt();
2039 return true;
2040 }
2041 bool found(APFloat &Value, QualType SubobjType) {
2042 if (!checkConst(SubobjType))
2043 return false;
2044 Value = NewVal.getFloat();
2045 return true;
2046 }
2047 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2048 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2049 }
2050};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002051} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002052
Richard Smith3229b742013-05-05 21:17:10 +00002053const AccessKinds ModifySubobjectHandler::AccessKind;
2054
Richard Smith3da88fa2013-04-26 14:36:30 +00002055/// Update the designated sub-object of an rvalue to the given value.
2056static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002057 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002058 const SubobjectDesignator &Sub,
2059 APValue &NewVal) {
2060 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002061 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002062}
2063
Richard Smith84f6dcf2012-02-02 01:16:57 +00002064/// Find the position where two subobject designators diverge, or equivalently
2065/// the length of the common initial subsequence.
2066static unsigned FindDesignatorMismatch(QualType ObjType,
2067 const SubobjectDesignator &A,
2068 const SubobjectDesignator &B,
2069 bool &WasArrayIndex) {
2070 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2071 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002072 if (!ObjType.isNull() &&
2073 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002074 // Next subobject is an array element.
2075 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2076 WasArrayIndex = true;
2077 return I;
2078 }
Richard Smith66c96992012-02-18 22:04:06 +00002079 if (ObjType->isAnyComplexType())
2080 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2081 else
2082 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002083 } else {
2084 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2085 WasArrayIndex = false;
2086 return I;
2087 }
2088 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2089 // Next subobject is a field.
2090 ObjType = FD->getType();
2091 else
2092 // Next subobject is a base class.
2093 ObjType = QualType();
2094 }
2095 }
2096 WasArrayIndex = false;
2097 return I;
2098}
2099
2100/// Determine whether the given subobject designators refer to elements of the
2101/// same array object.
2102static bool AreElementsOfSameArray(QualType ObjType,
2103 const SubobjectDesignator &A,
2104 const SubobjectDesignator &B) {
2105 if (A.Entries.size() != B.Entries.size())
2106 return false;
2107
2108 bool IsArray = A.MostDerivedArraySize != 0;
2109 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2110 // A is a subobject of the array element.
2111 return false;
2112
2113 // If A (and B) designates an array element, the last entry will be the array
2114 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2115 // of length 1' case, and the entire path must match.
2116 bool WasArrayIndex;
2117 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2118 return CommonLength >= A.Entries.size() - IsArray;
2119}
2120
Richard Smith3229b742013-05-05 21:17:10 +00002121/// Find the complete object to which an LValue refers.
2122CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
2123 const LValue &LVal, QualType LValType) {
2124 if (!LVal.Base) {
2125 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2126 return CompleteObject();
2127 }
2128
2129 CallStackFrame *Frame = 0;
2130 if (LVal.CallIndex) {
2131 Frame = Info.getCallFrame(LVal.CallIndex);
2132 if (!Frame) {
2133 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2134 << AK << LVal.Base.is<const ValueDecl*>();
2135 NoteLValueLocation(Info, LVal.Base);
2136 return CompleteObject();
2137 }
Richard Smith3229b742013-05-05 21:17:10 +00002138 }
2139
2140 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2141 // is not a constant expression (even if the object is non-volatile). We also
2142 // apply this rule to C++98, in order to conform to the expected 'volatile'
2143 // semantics.
2144 if (LValType.isVolatileQualified()) {
2145 if (Info.getLangOpts().CPlusPlus)
2146 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2147 << AK << LValType;
2148 else
2149 Info.Diag(E);
2150 return CompleteObject();
2151 }
2152
2153 // Compute value storage location and type of base object.
2154 APValue *BaseVal = 0;
2155 QualType BaseType;
2156
2157 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2158 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2159 // In C++11, constexpr, non-volatile variables initialized with constant
2160 // expressions are constant expressions too. Inside constexpr functions,
2161 // parameters are constant expressions even if they're non-const.
2162 // In C++1y, objects local to a constant expression (those with a Frame) are
2163 // both readable and writable inside constant expressions.
2164 // In C, such things can also be folded, although they are not ICEs.
2165 const VarDecl *VD = dyn_cast<VarDecl>(D);
2166 if (VD) {
2167 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2168 VD = VDef;
2169 }
2170 if (!VD || VD->isInvalidDecl()) {
2171 Info.Diag(E);
2172 return CompleteObject();
2173 }
2174
2175 // Accesses of volatile-qualified objects are not allowed.
2176 BaseType = VD->getType();
2177 if (BaseType.isVolatileQualified()) {
2178 if (Info.getLangOpts().CPlusPlus) {
2179 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2180 << AK << 1 << VD;
2181 Info.Note(VD->getLocation(), diag::note_declared_at);
2182 } else {
2183 Info.Diag(E);
2184 }
2185 return CompleteObject();
2186 }
2187
2188 // Unless we're looking at a local variable or argument in a constexpr call,
2189 // the variable we're reading must be const.
2190 if (!Frame) {
Richard Smith7525ff62013-05-09 07:14:00 +00002191 if (Info.getLangOpts().CPlusPlus1y &&
2192 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2193 // OK, we can read and modify an object if we're in the process of
2194 // evaluating its initializer, because its lifetime began in this
2195 // evaluation.
2196 } else if (AK != AK_Read) {
2197 // All the remaining cases only permit reading.
2198 Info.Diag(E, diag::note_constexpr_modify_global);
2199 return CompleteObject();
2200 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002201 // OK, we can read this variable.
2202 } else if (BaseType->isIntegralOrEnumerationType()) {
2203 if (!BaseType.isConstQualified()) {
2204 if (Info.getLangOpts().CPlusPlus) {
2205 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2206 Info.Note(VD->getLocation(), diag::note_declared_at);
2207 } else {
2208 Info.Diag(E);
2209 }
2210 return CompleteObject();
2211 }
2212 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2213 // We support folding of const floating-point types, in order to make
2214 // static const data members of such types (supported as an extension)
2215 // more useful.
2216 if (Info.getLangOpts().CPlusPlus11) {
2217 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2218 Info.Note(VD->getLocation(), diag::note_declared_at);
2219 } else {
2220 Info.CCEDiag(E);
2221 }
2222 } else {
2223 // FIXME: Allow folding of values of any literal type in all languages.
2224 if (Info.getLangOpts().CPlusPlus11) {
2225 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2226 Info.Note(VD->getLocation(), diag::note_declared_at);
2227 } else {
2228 Info.Diag(E);
2229 }
2230 return CompleteObject();
2231 }
2232 }
2233
2234 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2235 return CompleteObject();
2236 } else {
2237 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2238
2239 if (!Frame) {
2240 Info.Diag(E);
2241 return CompleteObject();
2242 }
2243
2244 BaseType = Base->getType();
2245 BaseVal = &Frame->Temporaries[Base];
2246
2247 // Volatile temporary objects cannot be accessed in constant expressions.
2248 if (BaseType.isVolatileQualified()) {
2249 if (Info.getLangOpts().CPlusPlus) {
2250 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2251 << AK << 0;
2252 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2253 } else {
2254 Info.Diag(E);
2255 }
2256 return CompleteObject();
2257 }
2258 }
2259
Richard Smith7525ff62013-05-09 07:14:00 +00002260 // During the construction of an object, it is not yet 'const'.
2261 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2262 // and this doesn't do quite the right thing for const subobjects of the
2263 // object under construction.
2264 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2265 BaseType = Info.Ctx.getCanonicalType(BaseType);
2266 BaseType.removeLocalConst();
2267 }
2268
Richard Smith3229b742013-05-05 21:17:10 +00002269 // In C++1y, we can't safely access any mutable state when checking a
2270 // potential constant expression.
2271 if (Frame && Info.getLangOpts().CPlusPlus1y &&
2272 Info.CheckingPotentialConstantExpression)
2273 return CompleteObject();
2274
2275 return CompleteObject(BaseVal, BaseType);
2276}
2277
Richard Smith243ef902013-05-05 23:31:59 +00002278/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2279/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2280/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002281///
2282/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002283/// \param Conv - The expression for which we are performing the conversion.
2284/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002285/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2286/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002287/// \param LVal - The glvalue on which we are attempting to perform this action.
2288/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002289static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002290 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002291 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002292 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002293 return false;
2294
Richard Smith3229b742013-05-05 21:17:10 +00002295 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002296 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith3229b742013-05-05 21:17:10 +00002297 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2298 !Type.isVolatileQualified()) {
2299 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2300 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2301 // initializer until now for such expressions. Such an expression can't be
2302 // an ICE in C, so this only matters for fold.
2303 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2304 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002305 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002306 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002307 }
Richard Smith3229b742013-05-05 21:17:10 +00002308 APValue Lit;
2309 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2310 return false;
2311 CompleteObject LitObj(&Lit, Base->getType());
2312 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2313 } else if (isa<StringLiteral>(Base)) {
2314 // We represent a string literal array as an lvalue pointing at the
2315 // corresponding expression, rather than building an array of chars.
2316 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2317 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2318 CompleteObject StrObj(&Str, Base->getType());
2319 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002320 }
Richard Smith11562c52011-10-28 17:51:58 +00002321 }
2322
Richard Smith3229b742013-05-05 21:17:10 +00002323 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2324 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002325}
2326
2327/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002328static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002329 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002330 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002331 return false;
2332
Richard Smith3229b742013-05-05 21:17:10 +00002333 if (!Info.getLangOpts().CPlusPlus1y) {
2334 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002335 return false;
2336 }
2337
Richard Smith3229b742013-05-05 21:17:10 +00002338 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2339 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002340}
2341
Richard Smith243ef902013-05-05 23:31:59 +00002342static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2343 return T->isSignedIntegerType() &&
2344 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2345}
2346
2347namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002348struct CompoundAssignSubobjectHandler {
2349 EvalInfo &Info;
2350 const Expr *E;
2351 QualType PromotedLHSType;
2352 BinaryOperatorKind Opcode;
2353 const APValue &RHS;
2354
2355 static const AccessKinds AccessKind = AK_Assign;
2356
2357 typedef bool result_type;
2358
2359 bool checkConst(QualType QT) {
2360 // Assigning to a const object has undefined behavior.
2361 if (QT.isConstQualified()) {
2362 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2363 return false;
2364 }
2365 return true;
2366 }
2367
2368 bool failed() { return false; }
2369 bool found(APValue &Subobj, QualType SubobjType) {
2370 switch (Subobj.getKind()) {
2371 case APValue::Int:
2372 return found(Subobj.getInt(), SubobjType);
2373 case APValue::Float:
2374 return found(Subobj.getFloat(), SubobjType);
2375 case APValue::ComplexInt:
2376 case APValue::ComplexFloat:
2377 // FIXME: Implement complex compound assignment.
2378 Info.Diag(E);
2379 return false;
2380 case APValue::LValue:
2381 return foundPointer(Subobj, SubobjType);
2382 default:
2383 // FIXME: can this happen?
2384 Info.Diag(E);
2385 return false;
2386 }
2387 }
2388 bool found(APSInt &Value, QualType SubobjType) {
2389 if (!checkConst(SubobjType))
2390 return false;
2391
2392 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2393 // We don't support compound assignment on integer-cast-to-pointer
2394 // values.
2395 Info.Diag(E);
2396 return false;
2397 }
2398
2399 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2400 SubobjType, Value);
2401 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2402 return false;
2403 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2404 return true;
2405 }
2406 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002407 return checkConst(SubobjType) &&
2408 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2409 Value) &&
2410 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2411 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00002412 }
2413 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2414 if (!checkConst(SubobjType))
2415 return false;
2416
2417 QualType PointeeType;
2418 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2419 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00002420
2421 if (PointeeType.isNull() || !RHS.isInt() ||
2422 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00002423 Info.Diag(E);
2424 return false;
2425 }
2426
Richard Smith861b5b52013-05-07 23:34:45 +00002427 int64_t Offset = getExtValue(RHS.getInt());
2428 if (Opcode == BO_Sub)
2429 Offset = -Offset;
2430
2431 LValue LVal;
2432 LVal.setFrom(Info.Ctx, Subobj);
2433 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2434 return false;
2435 LVal.moveInto(Subobj);
2436 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002437 }
2438 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2439 llvm_unreachable("shouldn't encounter string elements here");
2440 }
2441};
2442} // end anonymous namespace
2443
2444const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2445
2446/// Perform a compound assignment of LVal <op>= RVal.
2447static bool handleCompoundAssignment(
2448 EvalInfo &Info, const Expr *E,
2449 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2450 BinaryOperatorKind Opcode, const APValue &RVal) {
2451 if (LVal.Designator.Invalid)
2452 return false;
2453
2454 if (!Info.getLangOpts().CPlusPlus1y) {
2455 Info.Diag(E);
2456 return false;
2457 }
2458
2459 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2460 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2461 RVal };
2462 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2463}
2464
2465namespace {
Richard Smith243ef902013-05-05 23:31:59 +00002466struct IncDecSubobjectHandler {
2467 EvalInfo &Info;
2468 const Expr *E;
2469 AccessKinds AccessKind;
2470 APValue *Old;
2471
2472 typedef bool result_type;
2473
2474 bool checkConst(QualType QT) {
2475 // Assigning to a const object has undefined behavior.
2476 if (QT.isConstQualified()) {
2477 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2478 return false;
2479 }
2480 return true;
2481 }
2482
2483 bool failed() { return false; }
2484 bool found(APValue &Subobj, QualType SubobjType) {
2485 // Stash the old value. Also clear Old, so we don't clobber it later
2486 // if we're post-incrementing a complex.
2487 if (Old) {
2488 *Old = Subobj;
2489 Old = 0;
2490 }
2491
2492 switch (Subobj.getKind()) {
2493 case APValue::Int:
2494 return found(Subobj.getInt(), SubobjType);
2495 case APValue::Float:
2496 return found(Subobj.getFloat(), SubobjType);
2497 case APValue::ComplexInt:
2498 return found(Subobj.getComplexIntReal(),
2499 SubobjType->castAs<ComplexType>()->getElementType()
2500 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2501 case APValue::ComplexFloat:
2502 return found(Subobj.getComplexFloatReal(),
2503 SubobjType->castAs<ComplexType>()->getElementType()
2504 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2505 case APValue::LValue:
2506 return foundPointer(Subobj, SubobjType);
2507 default:
2508 // FIXME: can this happen?
2509 Info.Diag(E);
2510 return false;
2511 }
2512 }
2513 bool found(APSInt &Value, QualType SubobjType) {
2514 if (!checkConst(SubobjType))
2515 return false;
2516
2517 if (!SubobjType->isIntegerType()) {
2518 // We don't support increment / decrement on integer-cast-to-pointer
2519 // values.
2520 Info.Diag(E);
2521 return false;
2522 }
2523
2524 if (Old) *Old = APValue(Value);
2525
2526 // bool arithmetic promotes to int, and the conversion back to bool
2527 // doesn't reduce mod 2^n, so special-case it.
2528 if (SubobjType->isBooleanType()) {
2529 if (AccessKind == AK_Increment)
2530 Value = 1;
2531 else
2532 Value = !Value;
2533 return true;
2534 }
2535
2536 bool WasNegative = Value.isNegative();
2537 if (AccessKind == AK_Increment) {
2538 ++Value;
2539
2540 if (!WasNegative && Value.isNegative() &&
2541 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2542 APSInt ActualValue(Value, /*IsUnsigned*/true);
2543 HandleOverflow(Info, E, ActualValue, SubobjType);
2544 }
2545 } else {
2546 --Value;
2547
2548 if (WasNegative && !Value.isNegative() &&
2549 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2550 unsigned BitWidth = Value.getBitWidth();
2551 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2552 ActualValue.setBit(BitWidth);
2553 HandleOverflow(Info, E, ActualValue, SubobjType);
2554 }
2555 }
2556 return true;
2557 }
2558 bool found(APFloat &Value, QualType SubobjType) {
2559 if (!checkConst(SubobjType))
2560 return false;
2561
2562 if (Old) *Old = APValue(Value);
2563
2564 APFloat One(Value.getSemantics(), 1);
2565 if (AccessKind == AK_Increment)
2566 Value.add(One, APFloat::rmNearestTiesToEven);
2567 else
2568 Value.subtract(One, APFloat::rmNearestTiesToEven);
2569 return true;
2570 }
2571 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2572 if (!checkConst(SubobjType))
2573 return false;
2574
2575 QualType PointeeType;
2576 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2577 PointeeType = PT->getPointeeType();
2578 else {
2579 Info.Diag(E);
2580 return false;
2581 }
2582
2583 LValue LVal;
2584 LVal.setFrom(Info.Ctx, Subobj);
2585 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2586 AccessKind == AK_Increment ? 1 : -1))
2587 return false;
2588 LVal.moveInto(Subobj);
2589 return true;
2590 }
2591 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2592 llvm_unreachable("shouldn't encounter string elements here");
2593 }
2594};
2595} // end anonymous namespace
2596
2597/// Perform an increment or decrement on LVal.
2598static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
2599 QualType LValType, bool IsIncrement, APValue *Old) {
2600 if (LVal.Designator.Invalid)
2601 return false;
2602
2603 if (!Info.getLangOpts().CPlusPlus1y) {
2604 Info.Diag(E);
2605 return false;
2606 }
2607
2608 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
2609 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
2610 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
2611 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2612}
2613
Richard Smithe97cbd72011-11-11 04:05:33 +00002614/// Build an lvalue for the object argument of a member function call.
2615static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2616 LValue &This) {
2617 if (Object->getType()->isPointerType())
2618 return EvaluatePointer(Object, This, Info);
2619
2620 if (Object->isGLValue())
2621 return EvaluateLValue(Object, This, Info);
2622
Richard Smithd9f663b2013-04-22 15:31:51 +00002623 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00002624 return EvaluateTemporary(Object, This, Info);
2625
2626 return false;
2627}
2628
2629/// HandleMemberPointerAccess - Evaluate a member access operation and build an
2630/// lvalue referring to the result.
2631///
2632/// \param Info - Information about the ongoing evaluation.
2633/// \param BO - The member pointer access operation.
2634/// \param LV - Filled in with a reference to the resulting object.
2635/// \param IncludeMember - Specifies whether the member itself is included in
2636/// the resulting LValue subobject designator. This is not possible when
2637/// creating a bound member function.
2638/// \return The field or method declaration to which the member pointer refers,
2639/// or 0 if evaluation fails.
2640static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
2641 const BinaryOperator *BO,
2642 LValue &LV,
2643 bool IncludeMember = true) {
2644 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
2645
Richard Smith253c2a32012-01-27 01:14:48 +00002646 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
2647 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smith027bf112011-11-17 22:56:20 +00002648 return 0;
2649
2650 MemberPtr MemPtr;
2651 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
2652 return 0;
2653
2654 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2655 // member value, the behavior is undefined.
2656 if (!MemPtr.getDecl())
2657 return 0;
2658
Richard Smith253c2a32012-01-27 01:14:48 +00002659 if (!EvalObjOK)
2660 return 0;
2661
Richard Smith027bf112011-11-17 22:56:20 +00002662 if (MemPtr.isDerivedMember()) {
2663 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00002664 // The end of the derived-to-base path for the base object must match the
2665 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00002666 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith027bf112011-11-17 22:56:20 +00002667 LV.Designator.Entries.size())
2668 return 0;
2669 unsigned PathLengthToMember =
2670 LV.Designator.Entries.size() - MemPtr.Path.size();
2671 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
2672 const CXXRecordDecl *LVDecl = getAsBaseClass(
2673 LV.Designator.Entries[PathLengthToMember + I]);
2674 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
2675 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
2676 return 0;
2677 }
2678
2679 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002680 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
2681 PathLengthToMember))
2682 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002683 } else if (!MemPtr.Path.empty()) {
2684 // Extend the LValue path with the member pointer's path.
2685 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
2686 MemPtr.Path.size() + IncludeMember);
2687
2688 // Walk down to the appropriate base class.
2689 QualType LVType = BO->getLHS()->getType();
2690 if (const PointerType *PT = LVType->getAs<PointerType>())
2691 LVType = PT->getPointeeType();
2692 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
2693 assert(RD && "member pointer access on non-class-type expression");
2694 // The first class in the path is that of the lvalue.
2695 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
2696 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
John McCalld7bca762012-05-01 00:38:49 +00002697 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
2698 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002699 RD = Base;
2700 }
2701 // Finally cast to the class containing the member.
John McCalld7bca762012-05-01 00:38:49 +00002702 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
2703 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002704 }
2705
2706 // Add the member. Note that we cannot build bound member functions here.
2707 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00002708 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
2709 if (!HandleLValueMember(Info, BO, LV, FD))
2710 return 0;
2711 } else if (const IndirectFieldDecl *IFD =
2712 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
2713 if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
2714 return 0;
2715 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002716 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00002717 }
Richard Smith027bf112011-11-17 22:56:20 +00002718 }
2719
2720 return MemPtr.getDecl();
2721}
2722
2723/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
2724/// the provided lvalue, which currently refers to the base object.
2725static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
2726 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00002727 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002728 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00002729 return false;
2730
Richard Smitha8105bc2012-01-06 16:39:00 +00002731 QualType TargetQT = E->getType();
2732 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2733 TargetQT = PT->getPointeeType();
2734
2735 // Check this cast lands within the final derived-to-base subobject path.
2736 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002737 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002738 << D.MostDerivedType << TargetQT;
2739 return false;
2740 }
2741
Richard Smith027bf112011-11-17 22:56:20 +00002742 // Check the type of the final cast. We don't need to check the path,
2743 // since a cast can only be formed if the path is unique.
2744 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00002745 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2746 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00002747 if (NewEntriesSize == D.MostDerivedPathLength)
2748 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2749 else
Richard Smith027bf112011-11-17 22:56:20 +00002750 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00002751 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002752 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002753 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00002754 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00002755 }
Richard Smith027bf112011-11-17 22:56:20 +00002756
2757 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002758 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00002759}
2760
Mike Stump876387b2009-10-27 22:09:17 +00002761namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00002762enum EvalStmtResult {
2763 /// Evaluation failed.
2764 ESR_Failed,
2765 /// Hit a 'return' statement.
2766 ESR_Returned,
2767 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00002768 ESR_Succeeded,
2769 /// Hit a 'continue' statement.
2770 ESR_Continue,
2771 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00002772 ESR_Break,
2773 /// Still scanning for 'case' or 'default' statement.
2774 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00002775};
2776}
2777
Richard Smithd9f663b2013-04-22 15:31:51 +00002778static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
2779 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2780 // We don't need to evaluate the initializer for a static local.
2781 if (!VD->hasLocalStorage())
2782 return true;
2783
2784 LValue Result;
2785 Result.set(VD, Info.CurrentCall->Index);
2786 APValue &Val = Info.CurrentCall->Temporaries[VD];
2787
2788 if (!EvaluateInPlace(Val, Info, Result, VD->getInit())) {
2789 // Wipe out any partially-computed value, to allow tracking that this
2790 // evaluation failed.
2791 Val = APValue();
2792 return false;
2793 }
2794 }
2795
2796 return true;
2797}
2798
Richard Smith4e18ca52013-05-06 05:56:11 +00002799/// Evaluate a condition (either a variable declaration or an expression).
2800static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
2801 const Expr *Cond, bool &Result) {
2802 if (CondDecl && !EvaluateDecl(Info, CondDecl))
2803 return false;
2804 return EvaluateAsBooleanCondition(Cond, Result, Info);
2805}
2806
2807static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00002808 const Stmt *S, const SwitchCase *SC = 0);
Richard Smith4e18ca52013-05-06 05:56:11 +00002809
2810/// Evaluate the body of a loop, and translate the result as appropriate.
2811static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00002812 const Stmt *Body,
2813 const SwitchCase *Case = 0) {
2814 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00002815 case ESR_Break:
2816 return ESR_Succeeded;
2817 case ESR_Succeeded:
2818 case ESR_Continue:
2819 return ESR_Continue;
2820 case ESR_Failed:
2821 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00002822 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00002823 return ESR;
2824 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00002825 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00002826}
2827
Richard Smith496ddcf2013-05-12 17:32:42 +00002828/// Evaluate a switch statement.
2829static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
2830 const SwitchStmt *SS) {
2831 // Evaluate the switch condition.
2832 if (SS->getConditionVariable() &&
2833 !EvaluateDecl(Info, SS->getConditionVariable()))
2834 return ESR_Failed;
2835 APSInt Value;
2836 if (!EvaluateInteger(SS->getCond(), Value, Info))
2837 return ESR_Failed;
2838
2839 // Find the switch case corresponding to the value of the condition.
2840 // FIXME: Cache this lookup.
2841 const SwitchCase *Found = 0;
2842 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
2843 SC = SC->getNextSwitchCase()) {
2844 if (isa<DefaultStmt>(SC)) {
2845 Found = SC;
2846 continue;
2847 }
2848
2849 const CaseStmt *CS = cast<CaseStmt>(SC);
2850 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
2851 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
2852 : LHS;
2853 if (LHS <= Value && Value <= RHS) {
2854 Found = SC;
2855 break;
2856 }
2857 }
2858
2859 if (!Found)
2860 return ESR_Succeeded;
2861
2862 // Search the switch body for the switch case and evaluate it from there.
2863 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
2864 case ESR_Break:
2865 return ESR_Succeeded;
2866 case ESR_Succeeded:
2867 case ESR_Continue:
2868 case ESR_Failed:
2869 case ESR_Returned:
2870 return ESR;
2871 case ESR_CaseNotFound:
Richard Smith496ddcf2013-05-12 17:32:42 +00002872 llvm_unreachable("couldn't find switch case");
2873 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00002874 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00002875}
2876
Richard Smith254a73d2011-10-28 22:34:42 +00002877// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00002878static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00002879 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00002880 if (!Info.nextStep(S))
2881 return ESR_Failed;
2882
Richard Smith496ddcf2013-05-12 17:32:42 +00002883 // If we're hunting down a 'case' or 'default' label, recurse through
2884 // substatements until we hit the label.
2885 if (Case) {
2886 // FIXME: We don't start the lifetime of objects whose initialization we
2887 // jump over. However, such objects must be of class type with a trivial
2888 // default constructor that initialize all subobjects, so must be empty,
2889 // so this almost never matters.
2890 switch (S->getStmtClass()) {
2891 case Stmt::CompoundStmtClass:
2892 // FIXME: Precompute which substatement of a compound statement we
2893 // would jump to, and go straight there rather than performing a
2894 // linear scan each time.
2895 case Stmt::LabelStmtClass:
2896 case Stmt::AttributedStmtClass:
2897 case Stmt::DoStmtClass:
2898 break;
2899
2900 case Stmt::CaseStmtClass:
2901 case Stmt::DefaultStmtClass:
2902 if (Case == S)
2903 Case = 0;
2904 break;
2905
2906 case Stmt::IfStmtClass: {
2907 // FIXME: Precompute which side of an 'if' we would jump to, and go
2908 // straight there rather than scanning both sides.
2909 const IfStmt *IS = cast<IfStmt>(S);
2910 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
2911 if (ESR != ESR_CaseNotFound || !IS->getElse())
2912 return ESR;
2913 return EvaluateStmt(Result, Info, IS->getElse(), Case);
2914 }
2915
2916 case Stmt::WhileStmtClass: {
2917 EvalStmtResult ESR =
2918 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
2919 if (ESR != ESR_Continue)
2920 return ESR;
2921 break;
2922 }
2923
2924 case Stmt::ForStmtClass: {
2925 const ForStmt *FS = cast<ForStmt>(S);
2926 EvalStmtResult ESR =
2927 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
2928 if (ESR != ESR_Continue)
2929 return ESR;
2930 if (FS->getInc() && !EvaluateIgnoredValue(Info, FS->getInc()))
2931 return ESR_Failed;
2932 break;
2933 }
2934
2935 case Stmt::DeclStmtClass:
2936 // FIXME: If the variable has initialization that can't be jumped over,
2937 // bail out of any immediately-surrounding compound-statement too.
2938 default:
2939 return ESR_CaseNotFound;
2940 }
2941 }
2942
Richard Smithd9f663b2013-04-22 15:31:51 +00002943 // FIXME: Mark all temporaries in the current frame as destroyed at
2944 // the end of each full-expression.
Richard Smith254a73d2011-10-28 22:34:42 +00002945 switch (S->getStmtClass()) {
2946 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00002947 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002948 // Don't bother evaluating beyond an expression-statement which couldn't
2949 // be evaluated.
Richard Smith4e18ca52013-05-06 05:56:11 +00002950 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00002951 return ESR_Failed;
2952 return ESR_Succeeded;
2953 }
2954
2955 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00002956 return ESR_Failed;
2957
2958 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00002959 return ESR_Succeeded;
2960
Richard Smithd9f663b2013-04-22 15:31:51 +00002961 case Stmt::DeclStmtClass: {
2962 const DeclStmt *DS = cast<DeclStmt>(S);
2963 for (DeclStmt::const_decl_iterator DclIt = DS->decl_begin(),
2964 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt)
2965 if (!EvaluateDecl(Info, *DclIt) && !Info.keepEvaluatingAfterFailure())
2966 return ESR_Failed;
2967 return ESR_Succeeded;
2968 }
2969
Richard Smith357362d2011-12-13 06:39:58 +00002970 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00002971 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smithd9f663b2013-04-22 15:31:51 +00002972 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00002973 return ESR_Failed;
2974 return ESR_Returned;
2975 }
Richard Smith254a73d2011-10-28 22:34:42 +00002976
2977 case Stmt::CompoundStmtClass: {
2978 const CompoundStmt *CS = cast<CompoundStmt>(S);
2979 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2980 BE = CS->body_end(); BI != BE; ++BI) {
Richard Smith496ddcf2013-05-12 17:32:42 +00002981 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI, Case);
2982 if (ESR == ESR_Succeeded)
2983 Case = 0;
2984 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00002985 return ESR;
2986 }
Richard Smith496ddcf2013-05-12 17:32:42 +00002987 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00002988 }
Richard Smithd9f663b2013-04-22 15:31:51 +00002989
2990 case Stmt::IfStmtClass: {
2991 const IfStmt *IS = cast<IfStmt>(S);
2992
2993 // Evaluate the condition, as either a var decl or as an expression.
2994 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00002995 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00002996 return ESR_Failed;
2997
2998 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
2999 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3000 if (ESR != ESR_Succeeded)
3001 return ESR;
3002 }
3003 return ESR_Succeeded;
3004 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003005
3006 case Stmt::WhileStmtClass: {
3007 const WhileStmt *WS = cast<WhileStmt>(S);
3008 while (true) {
3009 bool Continue;
3010 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3011 Continue))
3012 return ESR_Failed;
3013 if (!Continue)
3014 break;
3015
3016 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3017 if (ESR != ESR_Continue)
3018 return ESR;
3019 }
3020 return ESR_Succeeded;
3021 }
3022
3023 case Stmt::DoStmtClass: {
3024 const DoStmt *DS = cast<DoStmt>(S);
3025 bool Continue;
3026 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003027 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003028 if (ESR != ESR_Continue)
3029 return ESR;
Richard Smith496ddcf2013-05-12 17:32:42 +00003030 Case = 0;
Richard Smith4e18ca52013-05-06 05:56:11 +00003031
3032 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3033 return ESR_Failed;
3034 } while (Continue);
3035 return ESR_Succeeded;
3036 }
3037
3038 case Stmt::ForStmtClass: {
3039 const ForStmt *FS = cast<ForStmt>(S);
3040 if (FS->getInit()) {
3041 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3042 if (ESR != ESR_Succeeded)
3043 return ESR;
3044 }
3045 while (true) {
3046 bool Continue = true;
3047 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3048 FS->getCond(), Continue))
3049 return ESR_Failed;
3050 if (!Continue)
3051 break;
3052
3053 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3054 if (ESR != ESR_Continue)
3055 return ESR;
3056
3057 if (FS->getInc() && !EvaluateIgnoredValue(Info, FS->getInc()))
3058 return ESR_Failed;
3059 }
3060 return ESR_Succeeded;
3061 }
3062
Richard Smith896e0d72013-05-06 06:51:17 +00003063 case Stmt::CXXForRangeStmtClass: {
3064 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
3065
3066 // Initialize the __range variable.
3067 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3068 if (ESR != ESR_Succeeded)
3069 return ESR;
3070
3071 // Create the __begin and __end iterators.
3072 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3073 if (ESR != ESR_Succeeded)
3074 return ESR;
3075
3076 while (true) {
3077 // Condition: __begin != __end.
3078 bool Continue = true;
3079 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3080 return ESR_Failed;
3081 if (!Continue)
3082 break;
3083
3084 // User's variable declaration, initialized by *__begin.
3085 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3086 if (ESR != ESR_Succeeded)
3087 return ESR;
3088
3089 // Loop body.
3090 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3091 if (ESR != ESR_Continue)
3092 return ESR;
3093
3094 // Increment: ++__begin
3095 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3096 return ESR_Failed;
3097 }
3098
3099 return ESR_Succeeded;
3100 }
3101
Richard Smith496ddcf2013-05-12 17:32:42 +00003102 case Stmt::SwitchStmtClass:
3103 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3104
Richard Smith4e18ca52013-05-06 05:56:11 +00003105 case Stmt::ContinueStmtClass:
3106 return ESR_Continue;
3107
3108 case Stmt::BreakStmtClass:
3109 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003110
3111 case Stmt::LabelStmtClass:
3112 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3113
3114 case Stmt::AttributedStmtClass:
3115 // As a general principle, C++11 attributes can be ignored without
3116 // any semantic impact.
3117 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3118 Case);
3119
3120 case Stmt::CaseStmtClass:
3121 case Stmt::DefaultStmtClass:
3122 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003123 }
3124}
3125
Richard Smithcc36f692011-12-22 02:22:31 +00003126/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3127/// default constructor. If so, we'll fold it whether or not it's marked as
3128/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3129/// so we need special handling.
3130static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003131 const CXXConstructorDecl *CD,
3132 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003133 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3134 return false;
3135
Richard Smith66e05fe2012-01-18 05:21:49 +00003136 // Value-initialization does not call a trivial default constructor, so such a
3137 // call is a core constant expression whether or not the constructor is
3138 // constexpr.
3139 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003140 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003141 // FIXME: If DiagDecl is an implicitly-declared special member function,
3142 // we should be much more explicit about why it's not constexpr.
3143 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3144 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3145 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003146 } else {
3147 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3148 }
3149 }
3150 return true;
3151}
3152
Richard Smith357362d2011-12-13 06:39:58 +00003153/// CheckConstexprFunction - Check that a function can be called in a constant
3154/// expression.
3155static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3156 const FunctionDecl *Declaration,
3157 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00003158 // Potential constant expressions can contain calls to declared, but not yet
3159 // defined, constexpr functions.
3160 if (Info.CheckingPotentialConstantExpression && !Definition &&
3161 Declaration->isConstexpr())
3162 return false;
3163
Richard Smith357362d2011-12-13 06:39:58 +00003164 // Can we evaluate this function call?
3165 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3166 return true;
3167
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003168 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003169 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003170 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3171 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003172 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3173 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3174 << DiagDecl;
3175 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3176 } else {
3177 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3178 }
3179 return false;
3180}
3181
Richard Smithd62306a2011-11-10 06:34:14 +00003182namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003183typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003184}
3185
3186/// EvaluateArgs - Evaluate the arguments to a function call.
3187static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3188 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003189 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003190 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003191 I != E; ++I) {
3192 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3193 // If we're checking for a potential constant expression, evaluate all
3194 // initializers even if some of them fail.
3195 if (!Info.keepEvaluatingAfterFailure())
3196 return false;
3197 Success = false;
3198 }
3199 }
3200 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003201}
3202
Richard Smith254a73d2011-10-28 22:34:42 +00003203/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003204static bool HandleFunctionCall(SourceLocation CallLoc,
3205 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003206 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00003207 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003208 ArgVector ArgValues(Args.size());
3209 if (!EvaluateArgs(Args, ArgValues, Info))
3210 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003211
Richard Smith253c2a32012-01-27 01:14:48 +00003212 if (!Info.CheckCallLimit(CallLoc))
3213 return false;
3214
3215 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003216
3217 // For a trivial copy or move assignment, perform an APValue copy. This is
3218 // essential for unions, where the operations performed by the assignment
3219 // operator cannot be represented as statements.
3220 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3221 if (MD && MD->isDefaulted() && MD->isTrivial()) {
3222 assert(This &&
3223 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3224 LValue RHS;
3225 RHS.setFrom(Info.Ctx, ArgValues[0]);
3226 APValue RHSValue;
3227 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3228 RHS, RHSValue))
3229 return false;
3230 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3231 RHSValue))
3232 return false;
3233 This->moveInto(Result);
3234 return true;
3235 }
3236
Richard Smithd9f663b2013-04-22 15:31:51 +00003237 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003238 if (ESR == ESR_Succeeded) {
3239 if (Callee->getResultType()->isVoidType())
3240 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003241 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003242 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003243 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003244}
3245
Richard Smithd62306a2011-11-10 06:34:14 +00003246/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003247static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003248 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003249 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003250 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003251 ArgVector ArgValues(Args.size());
3252 if (!EvaluateArgs(Args, ArgValues, Info))
3253 return false;
3254
Richard Smith253c2a32012-01-27 01:14:48 +00003255 if (!Info.CheckCallLimit(CallLoc))
3256 return false;
3257
Richard Smith3607ffe2012-02-13 03:54:03 +00003258 const CXXRecordDecl *RD = Definition->getParent();
3259 if (RD->getNumVBases()) {
3260 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3261 return false;
3262 }
3263
Richard Smith253c2a32012-01-27 01:14:48 +00003264 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003265
3266 // If it's a delegating constructor, just delegate.
3267 if (Definition->isDelegatingConstructor()) {
3268 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smithd9f663b2013-04-22 15:31:51 +00003269 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3270 return false;
3271 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003272 }
3273
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003274 // For a trivial copy or move constructor, perform an APValue copy. This is
3275 // essential for unions, where the operations performed by the constructor
3276 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003277 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00003278 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3279 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003280 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003281 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003282 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003283 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003284 }
3285
3286 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003287 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003288 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3289 std::distance(RD->field_begin(), RD->field_end()));
3290
John McCalld7bca762012-05-01 00:38:49 +00003291 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003292 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3293
Richard Smith253c2a32012-01-27 01:14:48 +00003294 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003295 unsigned BasesSeen = 0;
3296#ifndef NDEBUG
3297 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3298#endif
3299 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
3300 E = Definition->init_end(); I != E; ++I) {
Richard Smith253c2a32012-01-27 01:14:48 +00003301 LValue Subobject = This;
3302 APValue *Value = &Result;
3303
3304 // Determine the subobject to initialize.
Richard Smithd62306a2011-11-10 06:34:14 +00003305 if ((*I)->isBaseInitializer()) {
3306 QualType BaseType((*I)->getBaseClass(), 0);
3307#ifndef NDEBUG
3308 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003309 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003310 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3311 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3312 "base class initializers not in expected order");
3313 ++BaseIt;
3314#endif
John McCalld7bca762012-05-01 00:38:49 +00003315 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
3316 BaseType->getAsCXXRecordDecl(), &Layout))
3317 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003318 Value = &Result.getStructBase(BasesSeen++);
Richard Smithd62306a2011-11-10 06:34:14 +00003319 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCalld7bca762012-05-01 00:38:49 +00003320 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
3321 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003322 if (RD->isUnion()) {
3323 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003324 Value = &Result.getUnionValue();
3325 } else {
3326 Value = &Result.getStructField(FD->getFieldIndex());
3327 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00003328 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003329 // Walk the indirect field decl's chain to find the object to initialize,
3330 // and make sure we've initialized every step along it.
3331 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
3332 CE = IFD->chain_end();
3333 C != CE; ++C) {
3334 FieldDecl *FD = cast<FieldDecl>(*C);
3335 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3336 // Switch the union field if it differs. This happens if we had
3337 // preceding zero-initialization, and we're now initializing a union
3338 // subobject other than the first.
3339 // FIXME: In this case, the values of the other subobjects are
3340 // specified, since zero-initialization sets all padding bits to zero.
3341 if (Value->isUninit() ||
3342 (Value->isUnion() && Value->getUnionField() != FD)) {
3343 if (CD->isUnion())
3344 *Value = APValue(FD);
3345 else
3346 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
3347 std::distance(CD->field_begin(), CD->field_end()));
3348 }
John McCalld7bca762012-05-01 00:38:49 +00003349 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
3350 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003351 if (CD->isUnion())
3352 Value = &Value->getUnionValue();
3353 else
3354 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00003355 }
Richard Smithd62306a2011-11-10 06:34:14 +00003356 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003357 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00003358 }
Richard Smith253c2a32012-01-27 01:14:48 +00003359
Richard Smith7525ff62013-05-09 07:14:00 +00003360 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit())) {
Richard Smith253c2a32012-01-27 01:14:48 +00003361 // If we're checking for a potential constant expression, evaluate all
3362 // initializers even if some of them fail.
3363 if (!Info.keepEvaluatingAfterFailure())
3364 return false;
3365 Success = false;
3366 }
Richard Smithd62306a2011-11-10 06:34:14 +00003367 }
3368
Richard Smithd9f663b2013-04-22 15:31:51 +00003369 return Success &&
3370 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003371}
3372
Eli Friedman9a156e52008-11-12 09:44:48 +00003373//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00003374// Generic Evaluation
3375//===----------------------------------------------------------------------===//
3376namespace {
3377
Richard Smithf57d8cb2011-12-09 22:58:01 +00003378// FIXME: RetTy is always bool. Remove it.
3379template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00003380class ExprEvaluatorBase
3381 : public ConstStmtVisitor<Derived, RetTy> {
3382private:
Richard Smith2e312c82012-03-03 22:46:17 +00003383 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003384 return static_cast<Derived*>(this)->Success(V, E);
3385 }
Richard Smithfddd3842011-12-30 21:15:51 +00003386 RetTy DerivedZeroInitialization(const Expr *E) {
3387 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003388 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003389
Richard Smith17100ba2012-02-16 02:46:34 +00003390 // Check whether a conditional operator with a non-constant condition is a
3391 // potential constant expression. If neither arm is a potential constant
3392 // expression, then the conditional operator is not either.
3393 template<typename ConditionalOperator>
3394 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
3395 assert(Info.CheckingPotentialConstantExpression);
3396
3397 // Speculatively evaluate both arms.
3398 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003399 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00003400 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3401
3402 StmtVisitorTy::Visit(E->getFalseExpr());
3403 if (Diag.empty())
3404 return;
3405
3406 Diag.clear();
3407 StmtVisitorTy::Visit(E->getTrueExpr());
3408 if (Diag.empty())
3409 return;
3410 }
3411
3412 Error(E, diag::note_constexpr_conditional_never_const);
3413 }
3414
3415
3416 template<typename ConditionalOperator>
3417 bool HandleConditionalOperator(const ConditionalOperator *E) {
3418 bool BoolResult;
3419 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
3420 if (Info.CheckingPotentialConstantExpression)
3421 CheckPotentialConstantConditional(E);
3422 return false;
3423 }
3424
3425 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3426 return StmtVisitorTy::Visit(EvalExpr);
3427 }
3428
Peter Collingbournee9200682011-05-13 03:29:01 +00003429protected:
3430 EvalInfo &Info;
3431 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
3432 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3433
Richard Smith92b1ce02011-12-12 09:28:41 +00003434 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003435 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003436 }
3437
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003438 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
3439
3440public:
3441 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3442
3443 EvalInfo &getEvalInfo() { return Info; }
3444
Richard Smithf57d8cb2011-12-09 22:58:01 +00003445 /// Report an evaluation error. This should only be called when an error is
3446 /// first discovered. When propagating an error, just return false.
3447 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003448 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003449 return false;
3450 }
3451 bool Error(const Expr *E) {
3452 return Error(E, diag::note_invalid_subexpr_in_const_expr);
3453 }
3454
Peter Collingbournee9200682011-05-13 03:29:01 +00003455 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00003456 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00003457 }
3458 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003459 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003460 }
3461
3462 RetTy VisitParenExpr(const ParenExpr *E)
3463 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3464 RetTy VisitUnaryExtension(const UnaryOperator *E)
3465 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3466 RetTy VisitUnaryPlus(const UnaryOperator *E)
3467 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3468 RetTy VisitChooseExpr(const ChooseExpr *E)
3469 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
3470 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
3471 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00003472 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
3473 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00003474 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
3475 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith852c9db2013-04-20 22:23:05 +00003476 RetTy VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
3477 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00003478 // We cannot create any objects for which cleanups are required, so there is
3479 // nothing to do here; all cleanups must come from unevaluated subexpressions.
3480 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
3481 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003482
Richard Smith6d6ecc32011-12-12 12:46:16 +00003483 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
3484 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3485 return static_cast<Derived*>(this)->VisitCastExpr(E);
3486 }
3487 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
3488 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3489 return static_cast<Derived*>(this)->VisitCastExpr(E);
3490 }
3491
Richard Smith027bf112011-11-17 22:56:20 +00003492 RetTy VisitBinaryOperator(const BinaryOperator *E) {
3493 switch (E->getOpcode()) {
3494 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003495 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003496
3497 case BO_Comma:
3498 VisitIgnoredValue(E->getLHS());
3499 return StmtVisitorTy::Visit(E->getRHS());
3500
3501 case BO_PtrMemD:
3502 case BO_PtrMemI: {
3503 LValue Obj;
3504 if (!HandleMemberPointerAccess(Info, E, Obj))
3505 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003506 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00003507 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00003508 return false;
3509 return DerivedSuccess(Result, E);
3510 }
3511 }
3512 }
3513
Peter Collingbournee9200682011-05-13 03:29:01 +00003514 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003515 // Evaluate and cache the common expression. We treat it as a temporary,
3516 // even though it's not quite the same thing.
3517 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
3518 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003519 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00003520
Richard Smith17100ba2012-02-16 02:46:34 +00003521 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003522 }
3523
3524 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003525 bool IsBcpCall = false;
3526 // If the condition (ignoring parens) is a __builtin_constant_p call,
3527 // the result is a constant expression if it can be folded without
3528 // side-effects. This is an important GNU extension. See GCC PR38377
3529 // for discussion.
3530 if (const CallExpr *CallCE =
3531 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
3532 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
3533 IsBcpCall = true;
3534
3535 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3536 // constant expression; we can't check whether it's potentially foldable.
3537 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
3538 return false;
3539
3540 FoldConstant Fold(Info);
3541
Richard Smith17100ba2012-02-16 02:46:34 +00003542 if (!HandleConditionalOperator(E))
Richard Smith84f6dcf2012-02-02 01:16:57 +00003543 return false;
3544
3545 if (IsBcpCall)
3546 Fold.Fold(Info);
3547
3548 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00003549 }
3550
3551 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003552 APValue &Value = Info.CurrentCall->Temporaries[E];
3553 if (Value.isUninit()) {
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003554 const Expr *Source = E->getSourceExpr();
3555 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003556 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003557 if (Source == E) { // sanity checking.
3558 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00003559 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003560 }
3561 return StmtVisitorTy::Visit(Source);
3562 }
Richard Smith26d4cc12012-06-26 08:12:11 +00003563 return DerivedSuccess(Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003564 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003565
Richard Smith254a73d2011-10-28 22:34:42 +00003566 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003567 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00003568 QualType CalleeType = Callee->getType();
3569
Richard Smith254a73d2011-10-28 22:34:42 +00003570 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00003571 LValue *This = 0, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003572 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00003573 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00003574
Richard Smithe97cbd72011-11-11 04:05:33 +00003575 // Extract function decl and 'this' pointer from the callee.
3576 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003577 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00003578 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3579 // Explicit bound member calls, such as x.f() or p->g();
3580 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003581 return false;
3582 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00003583 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00003584 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00003585 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
3586 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00003587 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
3588 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00003589 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00003590 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003591 return Error(Callee);
3592
3593 FD = dyn_cast<FunctionDecl>(Member);
3594 if (!FD)
3595 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003596 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003597 LValue Call;
3598 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003599 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00003600
Richard Smitha8105bc2012-01-06 16:39:00 +00003601 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003602 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00003603 FD = dyn_cast_or_null<FunctionDecl>(
3604 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00003605 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003606 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003607
3608 // Overloaded operator calls to member functions are represented as normal
3609 // calls with '*this' as the first argument.
3610 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
3611 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003612 // FIXME: When selecting an implicit conversion for an overloaded
3613 // operator delete, we sometimes try to evaluate calls to conversion
3614 // operators without a 'this' parameter!
3615 if (Args.empty())
3616 return Error(E);
3617
Richard Smithe97cbd72011-11-11 04:05:33 +00003618 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
3619 return false;
3620 This = &ThisVal;
3621 Args = Args.slice(1);
3622 }
3623
3624 // Don't call function pointers which have been cast to some other type.
3625 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003626 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00003627 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003628 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00003629
Richard Smith47b34932012-02-01 02:39:43 +00003630 if (This && !This->checkSubobject(Info, E, CSK_This))
3631 return false;
3632
Richard Smith3607ffe2012-02-13 03:54:03 +00003633 // DR1358 allows virtual constexpr functions in some cases. Don't allow
3634 // calls to such functions in constant expressions.
3635 if (This && !HasQualifier &&
3636 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
3637 return Error(E, diag::note_constexpr_virtual_call);
3638
Richard Smith357362d2011-12-13 06:39:58 +00003639 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00003640 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00003641 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00003642
Richard Smith357362d2011-12-13 06:39:58 +00003643 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00003644 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
3645 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003646 return false;
3647
Richard Smithb228a862012-02-15 02:18:13 +00003648 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00003649 }
3650
Richard Smith11562c52011-10-28 17:51:58 +00003651 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
3652 return StmtVisitorTy::Visit(E->getInitializer());
3653 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003654 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00003655 if (E->getNumInits() == 0)
3656 return DerivedZeroInitialization(E);
3657 if (E->getNumInits() == 1)
3658 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00003659 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003660 }
3661 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003662 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003663 }
3664 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003665 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003666 }
Richard Smith027bf112011-11-17 22:56:20 +00003667 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003668 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00003669 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003670
Richard Smithd62306a2011-11-10 06:34:14 +00003671 /// A member expression where the object is a prvalue is itself a prvalue.
3672 RetTy VisitMemberExpr(const MemberExpr *E) {
3673 assert(!E->isArrow() && "missing call to bound member function?");
3674
Richard Smith2e312c82012-03-03 22:46:17 +00003675 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00003676 if (!Evaluate(Val, Info, E->getBase()))
3677 return false;
3678
3679 QualType BaseTy = E->getBase()->getType();
3680
3681 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003682 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003683 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00003684 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00003685 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3686
Richard Smith3229b742013-05-05 21:17:10 +00003687 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00003688 SubobjectDesignator Designator(BaseTy);
3689 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00003690
Richard Smith3229b742013-05-05 21:17:10 +00003691 APValue Result;
3692 return extractSubobject(Info, E, Obj, Designator, Result) &&
3693 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00003694 }
3695
Richard Smith11562c52011-10-28 17:51:58 +00003696 RetTy VisitCastExpr(const CastExpr *E) {
3697 switch (E->getCastKind()) {
3698 default:
3699 break;
3700
David Chisnallfa35df62012-01-16 17:27:18 +00003701 case CK_AtomicToNonAtomic:
3702 case CK_NonAtomicToAtomic:
Richard Smith11562c52011-10-28 17:51:58 +00003703 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00003704 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00003705 return StmtVisitorTy::Visit(E->getSubExpr());
3706
3707 case CK_LValueToRValue: {
3708 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003709 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
3710 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003711 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00003712 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00003713 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00003714 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003715 return false;
3716 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00003717 }
3718 }
3719
Richard Smithf57d8cb2011-12-09 22:58:01 +00003720 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003721 }
3722
Richard Smith243ef902013-05-05 23:31:59 +00003723 RetTy VisitUnaryPostInc(const UnaryOperator *UO) {
3724 return VisitUnaryPostIncDec(UO);
3725 }
3726 RetTy VisitUnaryPostDec(const UnaryOperator *UO) {
3727 return VisitUnaryPostIncDec(UO);
3728 }
3729 RetTy VisitUnaryPostIncDec(const UnaryOperator *UO) {
3730 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
3731 return Error(UO);
3732
3733 LValue LVal;
3734 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
3735 return false;
3736 APValue RVal;
3737 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
3738 UO->isIncrementOp(), &RVal))
3739 return false;
3740 return DerivedSuccess(RVal, UO);
3741 }
3742
Richard Smith4a678122011-10-24 18:44:57 +00003743 /// Visit a value which is evaluated, but whose value is ignored.
3744 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003745 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00003746 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003747};
3748
3749}
3750
3751//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003752// Common base class for lvalue and temporary evaluation.
3753//===----------------------------------------------------------------------===//
3754namespace {
3755template<class Derived>
3756class LValueExprEvaluatorBase
3757 : public ExprEvaluatorBase<Derived, bool> {
3758protected:
3759 LValue &Result;
3760 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
3761 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
3762
3763 bool Success(APValue::LValueBase B) {
3764 Result.set(B);
3765 return true;
3766 }
3767
3768public:
3769 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
3770 ExprEvaluatorBaseTy(Info), Result(Result) {}
3771
Richard Smith2e312c82012-03-03 22:46:17 +00003772 bool Success(const APValue &V, const Expr *E) {
3773 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00003774 return true;
3775 }
Richard Smith027bf112011-11-17 22:56:20 +00003776
Richard Smith027bf112011-11-17 22:56:20 +00003777 bool VisitMemberExpr(const MemberExpr *E) {
3778 // Handle non-static data members.
3779 QualType BaseTy;
3780 if (E->isArrow()) {
3781 if (!EvaluatePointer(E->getBase(), Result, this->Info))
3782 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00003783 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00003784 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00003785 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00003786 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
3787 return false;
3788 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003789 } else {
3790 if (!this->Visit(E->getBase()))
3791 return false;
3792 BaseTy = E->getBase()->getType();
3793 }
Richard Smith027bf112011-11-17 22:56:20 +00003794
Richard Smith1b78b3d2012-01-25 22:15:11 +00003795 const ValueDecl *MD = E->getMemberDecl();
3796 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
3797 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
3798 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3799 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00003800 if (!HandleLValueMember(this->Info, E, Result, FD))
3801 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003802 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00003803 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
3804 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003805 } else
3806 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003807
Richard Smith1b78b3d2012-01-25 22:15:11 +00003808 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00003809 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00003810 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00003811 RefValue))
3812 return false;
3813 return Success(RefValue, E);
3814 }
3815 return true;
3816 }
3817
3818 bool VisitBinaryOperator(const BinaryOperator *E) {
3819 switch (E->getOpcode()) {
3820 default:
3821 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
3822
3823 case BO_PtrMemD:
3824 case BO_PtrMemI:
3825 return HandleMemberPointerAccess(this->Info, E, Result);
3826 }
3827 }
3828
3829 bool VisitCastExpr(const CastExpr *E) {
3830 switch (E->getCastKind()) {
3831 default:
3832 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3833
3834 case CK_DerivedToBase:
3835 case CK_UncheckedDerivedToBase: {
3836 if (!this->Visit(E->getSubExpr()))
3837 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003838
3839 // Now figure out the necessary offset to add to the base LV to get from
3840 // the derived class to the base class.
3841 QualType Type = E->getSubExpr()->getType();
3842
3843 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3844 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003845 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smith027bf112011-11-17 22:56:20 +00003846 *PathI))
3847 return false;
3848 Type = (*PathI)->getType();
3849 }
3850
3851 return true;
3852 }
3853 }
3854 }
3855};
3856}
3857
3858//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00003859// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003860//
3861// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
3862// function designators (in C), decl references to void objects (in C), and
3863// temporaries (if building with -Wno-address-of-temporary).
3864//
3865// LValue evaluation produces values comprising a base expression of one of the
3866// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00003867// - Declarations
3868// * VarDecl
3869// * FunctionDecl
3870// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00003871// * CompoundLiteralExpr in C
3872// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00003873// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00003874// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00003875// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00003876// * ObjCEncodeExpr
3877// * AddrLabelExpr
3878// * BlockExpr
3879// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00003880// - Locals and temporaries
Richard Smithb228a862012-02-15 02:18:13 +00003881// * Any Expr, with a CallIndex indicating the function in which the temporary
3882// was evaluated.
Richard Smithce40ad62011-11-12 22:28:03 +00003883// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00003884//===----------------------------------------------------------------------===//
3885namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003886class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00003887 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00003888public:
Richard Smith027bf112011-11-17 22:56:20 +00003889 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
3890 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00003891
Richard Smith11562c52011-10-28 17:51:58 +00003892 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00003893 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00003894
Peter Collingbournee9200682011-05-13 03:29:01 +00003895 bool VisitDeclRefExpr(const DeclRefExpr *E);
3896 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003897 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003898 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
3899 bool VisitMemberExpr(const MemberExpr *E);
3900 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
3901 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00003902 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00003903 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003904 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
3905 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00003906 bool VisitUnaryReal(const UnaryOperator *E);
3907 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00003908 bool VisitUnaryPreInc(const UnaryOperator *UO) {
3909 return VisitUnaryPreIncDec(UO);
3910 }
3911 bool VisitUnaryPreDec(const UnaryOperator *UO) {
3912 return VisitUnaryPreIncDec(UO);
3913 }
Richard Smith3229b742013-05-05 21:17:10 +00003914 bool VisitBinAssign(const BinaryOperator *BO);
3915 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00003916
Peter Collingbournee9200682011-05-13 03:29:01 +00003917 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00003918 switch (E->getCastKind()) {
3919 default:
Richard Smith027bf112011-11-17 22:56:20 +00003920 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00003921
Eli Friedmance3e02a2011-10-11 00:13:24 +00003922 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00003923 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00003924 if (!Visit(E->getSubExpr()))
3925 return false;
3926 Result.Designator.setInvalid();
3927 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00003928
Richard Smith027bf112011-11-17 22:56:20 +00003929 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00003930 if (!Visit(E->getSubExpr()))
3931 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003932 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00003933 }
3934 }
Eli Friedman9a156e52008-11-12 09:44:48 +00003935};
3936} // end anonymous namespace
3937
Richard Smith11562c52011-10-28 17:51:58 +00003938/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smith9f8400e2013-05-01 19:00:39 +00003939/// expressions which are not glvalues, in two cases:
3940/// * function designators in C, and
3941/// * "extern void" objects
3942static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
3943 assert(E->isGLValue() || E->getType()->isFunctionType() ||
3944 E->getType()->isVoidType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003945 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003946}
3947
Peter Collingbournee9200682011-05-13 03:29:01 +00003948bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00003949 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
3950 return Success(FD);
3951 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00003952 return VisitVarDecl(E, VD);
3953 return Error(E);
3954}
Richard Smith733237d2011-10-24 23:14:33 +00003955
Richard Smith11562c52011-10-28 17:51:58 +00003956bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith3229b742013-05-05 21:17:10 +00003957 CallStackFrame *Frame = 0;
3958 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
3959 Frame = Info.CurrentCall;
3960
Richard Smithfec09922011-11-01 16:57:24 +00003961 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00003962 if (Frame) {
3963 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00003964 return true;
3965 }
Richard Smithce40ad62011-11-12 22:28:03 +00003966 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00003967 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00003968
Richard Smith3229b742013-05-05 21:17:10 +00003969 APValue *V;
3970 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003971 return false;
Richard Smith3229b742013-05-05 21:17:10 +00003972 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00003973}
3974
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003975bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
3976 const MaterializeTemporaryExpr *E) {
Jordan Roseb1312a52013-04-11 00:58:58 +00003977 if (E->getType()->isRecordType())
3978 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
Richard Smith027bf112011-11-17 22:56:20 +00003979
Richard Smithb228a862012-02-15 02:18:13 +00003980 Result.set(E, Info.CurrentCall->Index);
Jordan Roseb1312a52013-04-11 00:58:58 +00003981 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
3982 Result, E->GetTemporaryExpr());
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003983}
3984
Peter Collingbournee9200682011-05-13 03:29:01 +00003985bool
3986LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003987 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
3988 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
3989 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00003990 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003991}
3992
Richard Smith6e525142011-12-27 12:18:28 +00003993bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00003994 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00003995 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00003996
3997 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
3998 << E->getExprOperand()->getType()
3999 << E->getExprOperand()->getSourceRange();
4000 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004001}
4002
Francois Pichet0066db92012-04-16 04:08:35 +00004003bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4004 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004005}
Francois Pichet0066db92012-04-16 04:08:35 +00004006
Peter Collingbournee9200682011-05-13 03:29:01 +00004007bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004008 // Handle static data members.
4009 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4010 VisitIgnoredValue(E->getBase());
4011 return VisitVarDecl(E, VD);
4012 }
4013
Richard Smith254a73d2011-10-28 22:34:42 +00004014 // Handle static member functions.
4015 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4016 if (MD->isStatic()) {
4017 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004018 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004019 }
4020 }
4021
Richard Smithd62306a2011-11-10 06:34:14 +00004022 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004023 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004024}
4025
Peter Collingbournee9200682011-05-13 03:29:01 +00004026bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004027 // FIXME: Deal with vectors as array subscript bases.
4028 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004029 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004030
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004031 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004032 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004033
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004034 APSInt Index;
4035 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004036 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004037
Richard Smith861b5b52013-05-07 23:34:45 +00004038 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4039 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004040}
Eli Friedman9a156e52008-11-12 09:44:48 +00004041
Peter Collingbournee9200682011-05-13 03:29:01 +00004042bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004043 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004044}
4045
Richard Smith66c96992012-02-18 22:04:06 +00004046bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4047 if (!Visit(E->getSubExpr()))
4048 return false;
4049 // __real is a no-op on scalar lvalues.
4050 if (E->getSubExpr()->getType()->isAnyComplexType())
4051 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4052 return true;
4053}
4054
4055bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4056 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4057 "lvalue __imag__ on scalar?");
4058 if (!Visit(E->getSubExpr()))
4059 return false;
4060 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4061 return true;
4062}
4063
Richard Smith243ef902013-05-05 23:31:59 +00004064bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4065 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004066 return Error(UO);
4067
4068 if (!this->Visit(UO->getSubExpr()))
4069 return false;
4070
Richard Smith243ef902013-05-05 23:31:59 +00004071 return handleIncDec(
4072 this->Info, UO, Result, UO->getSubExpr()->getType(),
4073 UO->isIncrementOp(), 0);
Richard Smith3229b742013-05-05 21:17:10 +00004074}
4075
4076bool LValueExprEvaluator::VisitCompoundAssignOperator(
4077 const CompoundAssignOperator *CAO) {
Richard Smith243ef902013-05-05 23:31:59 +00004078 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004079 return Error(CAO);
4080
Richard Smith3229b742013-05-05 21:17:10 +00004081 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004082
4083 // The overall lvalue result is the result of evaluating the LHS.
4084 if (!this->Visit(CAO->getLHS())) {
4085 if (Info.keepEvaluatingAfterFailure())
4086 Evaluate(RHS, this->Info, CAO->getRHS());
4087 return false;
4088 }
4089
Richard Smith3229b742013-05-05 21:17:10 +00004090 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4091 return false;
4092
Richard Smith43e77732013-05-07 04:50:00 +00004093 return handleCompoundAssignment(
4094 this->Info, CAO,
4095 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4096 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004097}
4098
4099bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Richard Smith243ef902013-05-05 23:31:59 +00004100 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4101 return Error(E);
4102
Richard Smith3229b742013-05-05 21:17:10 +00004103 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004104
4105 if (!this->Visit(E->getLHS())) {
4106 if (Info.keepEvaluatingAfterFailure())
4107 Evaluate(NewVal, this->Info, E->getRHS());
4108 return false;
4109 }
4110
Richard Smith3229b742013-05-05 21:17:10 +00004111 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4112 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004113
4114 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004115 NewVal);
4116}
4117
Eli Friedman9a156e52008-11-12 09:44:48 +00004118//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004119// Pointer Evaluation
4120//===----------------------------------------------------------------------===//
4121
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004122namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004123class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004124 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00004125 LValue &Result;
4126
Peter Collingbournee9200682011-05-13 03:29:01 +00004127 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004128 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004129 return true;
4130 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004131public:
Mike Stump11289f42009-09-09 15:08:12 +00004132
John McCall45d55e42010-05-07 21:00:08 +00004133 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004134 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004135
Richard Smith2e312c82012-03-03 22:46:17 +00004136 bool Success(const APValue &V, const Expr *E) {
4137 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004138 return true;
4139 }
Richard Smithfddd3842011-12-30 21:15:51 +00004140 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00004141 return Success((Expr*)0);
4142 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004143
John McCall45d55e42010-05-07 21:00:08 +00004144 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004145 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004146 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004147 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004148 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004149 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00004150 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004151 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004152 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004153 bool VisitCallExpr(const CallExpr *E);
4154 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004155 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004156 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004157 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004158 }
Richard Smithd62306a2011-11-10 06:34:14 +00004159 bool VisitCXXThisExpr(const CXXThisExpr *E) {
4160 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004161 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004162 Result = *Info.CurrentCall->This;
4163 return true;
4164 }
John McCallc07a0c72011-02-17 10:25:35 +00004165
Eli Friedman449fe542009-03-23 04:56:01 +00004166 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004167};
Chris Lattner05706e882008-07-11 18:11:29 +00004168} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004169
John McCall45d55e42010-05-07 21:00:08 +00004170static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004171 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004172 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004173}
4174
John McCall45d55e42010-05-07 21:00:08 +00004175bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004176 if (E->getOpcode() != BO_Add &&
4177 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004178 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004179
Chris Lattner05706e882008-07-11 18:11:29 +00004180 const Expr *PExp = E->getLHS();
4181 const Expr *IExp = E->getRHS();
4182 if (IExp->getType()->isPointerType())
4183 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004184
Richard Smith253c2a32012-01-27 01:14:48 +00004185 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4186 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004187 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004188
John McCall45d55e42010-05-07 21:00:08 +00004189 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004190 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004191 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004192
4193 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004194 if (E->getOpcode() == BO_Sub)
4195 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004196
Ted Kremenek28831752012-08-23 20:46:57 +00004197 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004198 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4199 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004200}
Eli Friedman9a156e52008-11-12 09:44:48 +00004201
John McCall45d55e42010-05-07 21:00:08 +00004202bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4203 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004204}
Mike Stump11289f42009-09-09 15:08:12 +00004205
Peter Collingbournee9200682011-05-13 03:29:01 +00004206bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4207 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004208
Eli Friedman847a2bc2009-12-27 05:43:15 +00004209 switch (E->getCastKind()) {
4210 default:
4211 break;
4212
John McCalle3027922010-08-25 11:45:40 +00004213 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004214 case CK_CPointerToObjCPointerCast:
4215 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004216 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004217 if (!Visit(SubExpr))
4218 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004219 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4220 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4221 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004222 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004223 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004224 if (SubExpr->getType()->isVoidPointerType())
4225 CCEDiag(E, diag::note_constexpr_invalid_cast)
4226 << 3 << SubExpr->getType();
4227 else
4228 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4229 }
Richard Smith96e0c102011-11-04 02:25:55 +00004230 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004231
Anders Carlsson18275092010-10-31 20:41:46 +00004232 case CK_DerivedToBase:
4233 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004234 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004235 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004236 if (!Result.Base && Result.Offset.isZero())
4237 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00004238
Richard Smithd62306a2011-11-10 06:34:14 +00004239 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00004240 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00004241 QualType Type =
4242 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00004243
Richard Smithd62306a2011-11-10 06:34:14 +00004244 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00004245 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004246 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
4247 *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00004248 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004249 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00004250 }
4251
Anders Carlsson18275092010-10-31 20:41:46 +00004252 return true;
4253 }
4254
Richard Smith027bf112011-11-17 22:56:20 +00004255 case CK_BaseToDerived:
4256 if (!Visit(E->getSubExpr()))
4257 return false;
4258 if (!Result.Base && Result.Offset.isZero())
4259 return true;
4260 return HandleBaseToDerivedCast(Info, E, Result);
4261
Richard Smith0b0a0b62011-10-29 20:57:55 +00004262 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004263 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004264 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00004265
John McCalle3027922010-08-25 11:45:40 +00004266 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004267 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4268
Richard Smith2e312c82012-03-03 22:46:17 +00004269 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00004270 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00004271 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00004272
John McCall45d55e42010-05-07 21:00:08 +00004273 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004274 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4275 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00004276 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004277 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00004278 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00004279 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004280 return true;
4281 } else {
4282 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00004283 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00004284 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00004285 }
4286 }
John McCalle3027922010-08-25 11:45:40 +00004287 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00004288 if (SubExpr->isGLValue()) {
4289 if (!EvaluateLValue(SubExpr, Result, Info))
4290 return false;
4291 } else {
Richard Smithb228a862012-02-15 02:18:13 +00004292 Result.set(SubExpr, Info.CurrentCall->Index);
4293 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
4294 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00004295 return false;
4296 }
Richard Smith96e0c102011-11-04 02:25:55 +00004297 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00004298 if (const ConstantArrayType *CAT
4299 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4300 Result.addArray(Info, E, CAT);
4301 else
4302 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00004303 return true;
Richard Smithdd785442011-10-31 20:57:44 +00004304
John McCalle3027922010-08-25 11:45:40 +00004305 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00004306 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004307 }
4308
Richard Smith11562c52011-10-28 17:51:58 +00004309 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00004310}
Chris Lattner05706e882008-07-11 18:11:29 +00004311
Peter Collingbournee9200682011-05-13 03:29:01 +00004312bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004313 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00004314 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00004315
Peter Collingbournee9200682011-05-13 03:29:01 +00004316 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004317}
Chris Lattner05706e882008-07-11 18:11:29 +00004318
4319//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004320// Member Pointer Evaluation
4321//===----------------------------------------------------------------------===//
4322
4323namespace {
4324class MemberPointerExprEvaluator
4325 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
4326 MemberPtr &Result;
4327
4328 bool Success(const ValueDecl *D) {
4329 Result = MemberPtr(D);
4330 return true;
4331 }
4332public:
4333
4334 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
4335 : ExprEvaluatorBaseTy(Info), Result(Result) {}
4336
Richard Smith2e312c82012-03-03 22:46:17 +00004337 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004338 Result.setFrom(V);
4339 return true;
4340 }
Richard Smithfddd3842011-12-30 21:15:51 +00004341 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004342 return Success((const ValueDecl*)0);
4343 }
4344
4345 bool VisitCastExpr(const CastExpr *E);
4346 bool VisitUnaryAddrOf(const UnaryOperator *E);
4347};
4348} // end anonymous namespace
4349
4350static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
4351 EvalInfo &Info) {
4352 assert(E->isRValue() && E->getType()->isMemberPointerType());
4353 return MemberPointerExprEvaluator(Info, Result).Visit(E);
4354}
4355
4356bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
4357 switch (E->getCastKind()) {
4358 default:
4359 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4360
4361 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004362 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004363 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004364
4365 case CK_BaseToDerivedMemberPointer: {
4366 if (!Visit(E->getSubExpr()))
4367 return false;
4368 if (E->path_empty())
4369 return true;
4370 // Base-to-derived member pointer casts store the path in derived-to-base
4371 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
4372 // the wrong end of the derived->base arc, so stagger the path by one class.
4373 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
4374 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
4375 PathI != PathE; ++PathI) {
4376 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4377 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
4378 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004379 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004380 }
4381 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
4382 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004383 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004384 return true;
4385 }
4386
4387 case CK_DerivedToBaseMemberPointer:
4388 if (!Visit(E->getSubExpr()))
4389 return false;
4390 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4391 PathE = E->path_end(); PathI != PathE; ++PathI) {
4392 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4393 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4394 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004395 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004396 }
4397 return true;
4398 }
4399}
4400
4401bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4402 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
4403 // member can be formed.
4404 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
4405}
4406
4407//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00004408// Record Evaluation
4409//===----------------------------------------------------------------------===//
4410
4411namespace {
4412 class RecordExprEvaluator
4413 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
4414 const LValue &This;
4415 APValue &Result;
4416 public:
4417
4418 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
4419 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
4420
Richard Smith2e312c82012-03-03 22:46:17 +00004421 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004422 Result = V;
4423 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00004424 }
Richard Smithfddd3842011-12-30 21:15:51 +00004425 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004426
Richard Smithe97cbd72011-11-11 04:05:33 +00004427 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004428 bool VisitInitListExpr(const InitListExpr *E);
4429 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
4430 };
4431}
4432
Richard Smithfddd3842011-12-30 21:15:51 +00004433/// Perform zero-initialization on an object of non-union class type.
4434/// C++11 [dcl.init]p5:
4435/// To zero-initialize an object or reference of type T means:
4436/// [...]
4437/// -- if T is a (possibly cv-qualified) non-union class type,
4438/// each non-static data member and each base-class subobject is
4439/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00004440static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
4441 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00004442 const LValue &This, APValue &Result) {
4443 assert(!RD->isUnion() && "Expected non-union class type");
4444 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
4445 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
4446 std::distance(RD->field_begin(), RD->field_end()));
4447
John McCalld7bca762012-05-01 00:38:49 +00004448 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004449 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4450
4451 if (CD) {
4452 unsigned Index = 0;
4453 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00004454 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00004455 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4456 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004457 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4458 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004459 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00004460 Result.getStructBase(Index)))
4461 return false;
4462 }
4463 }
4464
Richard Smitha8105bc2012-01-06 16:39:00 +00004465 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
4466 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00004467 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004468 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00004469 continue;
4470
4471 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004472 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004473 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004474
David Blaikie2d7c57e2012-04-30 02:36:29 +00004475 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004476 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00004477 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004478 return false;
4479 }
4480
4481 return true;
4482}
4483
4484bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
4485 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004486 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004487 if (RD->isUnion()) {
4488 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4489 // object's first non-static named data member is zero-initialized
4490 RecordDecl::field_iterator I = RD->field_begin();
4491 if (I == RD->field_end()) {
4492 Result = APValue((const FieldDecl*)0);
4493 return true;
4494 }
4495
4496 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004497 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00004498 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00004499 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00004500 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004501 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004502 }
4503
Richard Smith5d108602012-02-17 00:44:16 +00004504 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004505 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00004506 return false;
4507 }
4508
Richard Smitha8105bc2012-01-06 16:39:00 +00004509 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00004510}
4511
Richard Smithe97cbd72011-11-11 04:05:33 +00004512bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
4513 switch (E->getCastKind()) {
4514 default:
4515 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4516
4517 case CK_ConstructorConversion:
4518 return Visit(E->getSubExpr());
4519
4520 case CK_DerivedToBase:
4521 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00004522 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004523 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00004524 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004525 if (!DerivedObject.isStruct())
4526 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00004527
4528 // Derived-to-base rvalue conversion: just slice off the derived part.
4529 APValue *Value = &DerivedObject;
4530 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
4531 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4532 PathE = E->path_end(); PathI != PathE; ++PathI) {
4533 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
4534 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4535 Value = &Value->getStructBase(getBaseIndex(RD, Base));
4536 RD = Base;
4537 }
4538 Result = *Value;
4539 return true;
4540 }
4541 }
4542}
4543
Richard Smithd62306a2011-11-10 06:34:14 +00004544bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redle6c32e62012-02-19 14:53:49 +00004545 // Cannot constant-evaluate std::initializer_list inits.
4546 if (E->initializesStdInitializerList())
4547 return false;
4548
Richard Smithd62306a2011-11-10 06:34:14 +00004549 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004550 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004551 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4552
4553 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00004554 const FieldDecl *Field = E->getInitializedFieldInUnion();
4555 Result = APValue(Field);
4556 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00004557 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00004558
4559 // If the initializer list for a union does not contain any elements, the
4560 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00004561 // FIXME: The element should be initialized from an initializer list.
4562 // Is this difference ever observable for initializer lists which
4563 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00004564 ImplicitValueInitExpr VIE(Field->getType());
4565 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
4566
Richard Smithd62306a2011-11-10 06:34:14 +00004567 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004568 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
4569 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00004570
4571 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4572 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4573 isa<CXXDefaultInitExpr>(InitExpr));
4574
Richard Smithb228a862012-02-15 02:18:13 +00004575 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00004576 }
4577
4578 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
4579 "initializer list for class with base classes");
4580 Result = APValue(APValue::UninitStruct(), 0,
4581 std::distance(RD->field_begin(), RD->field_end()));
4582 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00004583 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004584 for (RecordDecl::field_iterator Field = RD->field_begin(),
4585 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
4586 // Anonymous bit-fields are not considered members of the class for
4587 // purposes of aggregate initialization.
4588 if (Field->isUnnamedBitfield())
4589 continue;
4590
4591 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00004592
Richard Smith253c2a32012-01-27 01:14:48 +00004593 bool HaveInit = ElementNo < E->getNumInits();
4594
4595 // FIXME: Diagnostics here should point to the end of the initializer
4596 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00004597 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie40ed2972012-06-06 20:45:41 +00004598 Subobject, *Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004599 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004600
4601 // Perform an implicit value-initialization for members beyond the end of
4602 // the initializer list.
4603 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00004604 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00004605
Richard Smith852c9db2013-04-20 22:23:05 +00004606 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4607 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4608 isa<CXXDefaultInitExpr>(Init));
4609
4610 if (!EvaluateInPlace(Result.getStructField(Field->getFieldIndex()), Info,
4611 Subobject, Init)) {
Richard Smith253c2a32012-01-27 01:14:48 +00004612 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00004613 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004614 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00004615 }
4616 }
4617
Richard Smith253c2a32012-01-27 01:14:48 +00004618 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004619}
4620
4621bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
4622 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00004623 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
4624
Richard Smithfddd3842011-12-30 21:15:51 +00004625 bool ZeroInit = E->requiresZeroInitialization();
4626 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00004627 // If we've already performed zero-initialization, we're already done.
4628 if (!Result.isUninit())
4629 return true;
4630
Richard Smithfddd3842011-12-30 21:15:51 +00004631 if (ZeroInit)
4632 return ZeroInitialization(E);
4633
Richard Smithcc36f692011-12-22 02:22:31 +00004634 const CXXRecordDecl *RD = FD->getParent();
4635 if (RD->isUnion())
4636 Result = APValue((FieldDecl*)0);
4637 else
4638 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4639 std::distance(RD->field_begin(), RD->field_end()));
4640 return true;
4641 }
4642
Richard Smithd62306a2011-11-10 06:34:14 +00004643 const FunctionDecl *Definition = 0;
4644 FD->getBody(Definition);
4645
Richard Smith357362d2011-12-13 06:39:58 +00004646 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
4647 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004648
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004649 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00004650 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00004651 if (const MaterializeTemporaryExpr *ME
4652 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
4653 return Visit(ME->GetTemporaryExpr());
4654
Richard Smithfddd3842011-12-30 21:15:51 +00004655 if (ZeroInit && !ZeroInitialization(E))
4656 return false;
4657
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004658 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00004659 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004660 cast<CXXConstructorDecl>(Definition), Info,
4661 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00004662}
4663
4664static bool EvaluateRecord(const Expr *E, const LValue &This,
4665 APValue &Result, EvalInfo &Info) {
4666 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00004667 "can't evaluate expression as a record rvalue");
4668 return RecordExprEvaluator(Info, This, Result).Visit(E);
4669}
4670
4671//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004672// Temporary Evaluation
4673//
4674// Temporaries are represented in the AST as rvalues, but generally behave like
4675// lvalues. The full-object of which the temporary is a subobject is implicitly
4676// materialized so that a reference can bind to it.
4677//===----------------------------------------------------------------------===//
4678namespace {
4679class TemporaryExprEvaluator
4680 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
4681public:
4682 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
4683 LValueExprEvaluatorBaseTy(Info, Result) {}
4684
4685 /// Visit an expression which constructs the value of this temporary.
4686 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004687 Result.set(E, Info.CurrentCall->Index);
4688 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00004689 }
4690
4691 bool VisitCastExpr(const CastExpr *E) {
4692 switch (E->getCastKind()) {
4693 default:
4694 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
4695
4696 case CK_ConstructorConversion:
4697 return VisitConstructExpr(E->getSubExpr());
4698 }
4699 }
4700 bool VisitInitListExpr(const InitListExpr *E) {
4701 return VisitConstructExpr(E);
4702 }
4703 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
4704 return VisitConstructExpr(E);
4705 }
4706 bool VisitCallExpr(const CallExpr *E) {
4707 return VisitConstructExpr(E);
4708 }
4709};
4710} // end anonymous namespace
4711
4712/// Evaluate an expression of record type as a temporary.
4713static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004714 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00004715 return TemporaryExprEvaluator(Info, Result).Visit(E);
4716}
4717
4718//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004719// Vector Evaluation
4720//===----------------------------------------------------------------------===//
4721
4722namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004723 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00004724 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
4725 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004726 public:
Mike Stump11289f42009-09-09 15:08:12 +00004727
Richard Smith2d406342011-10-22 21:10:00 +00004728 VectorExprEvaluator(EvalInfo &info, APValue &Result)
4729 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004730
Richard Smith2d406342011-10-22 21:10:00 +00004731 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
4732 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
4733 // FIXME: remove this APValue copy.
4734 Result = APValue(V.data(), V.size());
4735 return true;
4736 }
Richard Smith2e312c82012-03-03 22:46:17 +00004737 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00004738 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00004739 Result = V;
4740 return true;
4741 }
Richard Smithfddd3842011-12-30 21:15:51 +00004742 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00004743
Richard Smith2d406342011-10-22 21:10:00 +00004744 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00004745 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00004746 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00004747 bool VisitInitListExpr(const InitListExpr *E);
4748 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004749 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00004750 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00004751 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004752 };
4753} // end anonymous namespace
4754
4755static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004756 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00004757 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004758}
4759
Richard Smith2d406342011-10-22 21:10:00 +00004760bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
4761 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00004762 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00004763
Richard Smith161f09a2011-12-06 22:44:34 +00004764 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00004765 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004766
Eli Friedmanc757de22011-03-25 00:43:55 +00004767 switch (E->getCastKind()) {
4768 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00004769 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00004770 if (SETy->isIntegerType()) {
4771 APSInt IntResult;
4772 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004773 return false;
Richard Smith2d406342011-10-22 21:10:00 +00004774 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00004775 } else if (SETy->isRealFloatingType()) {
4776 APFloat F(0.0);
4777 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004778 return false;
Richard Smith2d406342011-10-22 21:10:00 +00004779 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00004780 } else {
Richard Smith2d406342011-10-22 21:10:00 +00004781 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004782 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00004783
4784 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00004785 SmallVector<APValue, 4> Elts(NElts, Val);
4786 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00004787 }
Eli Friedman803acb32011-12-22 03:51:45 +00004788 case CK_BitCast: {
4789 // Evaluate the operand into an APInt we can extract from.
4790 llvm::APInt SValInt;
4791 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
4792 return false;
4793 // Extract the elements
4794 QualType EltTy = VTy->getElementType();
4795 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
4796 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
4797 SmallVector<APValue, 4> Elts;
4798 if (EltTy->isRealFloatingType()) {
4799 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00004800 unsigned FloatEltSize = EltSize;
4801 if (&Sem == &APFloat::x87DoubleExtended)
4802 FloatEltSize = 80;
4803 for (unsigned i = 0; i < NElts; i++) {
4804 llvm::APInt Elt;
4805 if (BigEndian)
4806 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
4807 else
4808 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00004809 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00004810 }
4811 } else if (EltTy->isIntegerType()) {
4812 for (unsigned i = 0; i < NElts; i++) {
4813 llvm::APInt Elt;
4814 if (BigEndian)
4815 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
4816 else
4817 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
4818 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
4819 }
4820 } else {
4821 return Error(E);
4822 }
4823 return Success(Elts, E);
4824 }
Eli Friedmanc757de22011-03-25 00:43:55 +00004825 default:
Richard Smith11562c52011-10-28 17:51:58 +00004826 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004827 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004828}
4829
Richard Smith2d406342011-10-22 21:10:00 +00004830bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004831VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00004832 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004833 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00004834 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00004835
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004836 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004837 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004838
Eli Friedmanb9c71292012-01-03 23:24:20 +00004839 // The number of initializers can be less than the number of
4840 // vector elements. For OpenCL, this can be due to nested vector
4841 // initialization. For GCC compatibility, missing trailing elements
4842 // should be initialized with zeroes.
4843 unsigned CountInits = 0, CountElts = 0;
4844 while (CountElts < NumElements) {
4845 // Handle nested vector initialization.
4846 if (CountInits < NumInits
4847 && E->getInit(CountInits)->getType()->isExtVectorType()) {
4848 APValue v;
4849 if (!EvaluateVector(E->getInit(CountInits), v, Info))
4850 return Error(E);
4851 unsigned vlen = v.getVectorLength();
4852 for (unsigned j = 0; j < vlen; j++)
4853 Elements.push_back(v.getVectorElt(j));
4854 CountElts += vlen;
4855 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004856 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00004857 if (CountInits < NumInits) {
4858 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00004859 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00004860 } else // trailing integer zero.
4861 sInt = Info.Ctx.MakeIntValue(0, EltTy);
4862 Elements.push_back(APValue(sInt));
4863 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004864 } else {
4865 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00004866 if (CountInits < NumInits) {
4867 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00004868 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00004869 } else // trailing float zero.
4870 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
4871 Elements.push_back(APValue(f));
4872 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00004873 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00004874 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004875 }
Richard Smith2d406342011-10-22 21:10:00 +00004876 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004877}
4878
Richard Smith2d406342011-10-22 21:10:00 +00004879bool
Richard Smithfddd3842011-12-30 21:15:51 +00004880VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00004881 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00004882 QualType EltTy = VT->getElementType();
4883 APValue ZeroElement;
4884 if (EltTy->isIntegerType())
4885 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
4886 else
4887 ZeroElement =
4888 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
4889
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004890 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00004891 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004892}
4893
Richard Smith2d406342011-10-22 21:10:00 +00004894bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00004895 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004896 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004897}
4898
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004899//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00004900// Array Evaluation
4901//===----------------------------------------------------------------------===//
4902
4903namespace {
4904 class ArrayExprEvaluator
4905 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00004906 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00004907 APValue &Result;
4908 public:
4909
Richard Smithd62306a2011-11-10 06:34:14 +00004910 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
4911 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00004912
4913 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00004914 assert((V.isArray() || V.isLValue()) &&
4915 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00004916 Result = V;
4917 return true;
4918 }
Richard Smithf3e9e432011-11-07 09:22:26 +00004919
Richard Smithfddd3842011-12-30 21:15:51 +00004920 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004921 const ConstantArrayType *CAT =
4922 Info.Ctx.getAsConstantArrayType(E->getType());
4923 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004924 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004925
4926 Result = APValue(APValue::UninitArray(), 0,
4927 CAT->getSize().getZExtValue());
4928 if (!Result.hasArrayFiller()) return true;
4929
Richard Smithfddd3842011-12-30 21:15:51 +00004930 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00004931 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00004932 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00004933 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00004934 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00004935 }
4936
Richard Smithf3e9e432011-11-07 09:22:26 +00004937 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00004938 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00004939 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
4940 const LValue &Subobject,
4941 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00004942 };
4943} // end anonymous namespace
4944
Richard Smithd62306a2011-11-10 06:34:14 +00004945static bool EvaluateArray(const Expr *E, const LValue &This,
4946 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00004947 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00004948 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00004949}
4950
4951bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
4952 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
4953 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004954 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00004955
Richard Smithca2cfbf2011-12-22 01:07:19 +00004956 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
4957 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00004958 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00004959 LValue LV;
4960 if (!EvaluateLValue(E->getInit(0), LV, Info))
4961 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004962 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00004963 LV.moveInto(Val);
4964 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00004965 }
4966
Richard Smith253c2a32012-01-27 01:14:48 +00004967 bool Success = true;
4968
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004969 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
4970 "zero-initialized array shouldn't have any initialized elts");
4971 APValue Filler;
4972 if (Result.isArray() && Result.hasArrayFiller())
4973 Filler = Result.getArrayFiller();
4974
Richard Smith9543c5e2013-04-22 14:44:29 +00004975 unsigned NumEltsToInit = E->getNumInits();
4976 unsigned NumElts = CAT->getSize().getZExtValue();
4977 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
4978
4979 // If the initializer might depend on the array index, run it for each
4980 // array element. For now, just whitelist non-class value-initialization.
4981 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
4982 NumEltsToInit = NumElts;
4983
4984 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004985
4986 // If the array was previously zero-initialized, preserve the
4987 // zero-initialized values.
4988 if (!Filler.isUninit()) {
4989 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
4990 Result.getArrayInitializedElt(I) = Filler;
4991 if (Result.hasArrayFiller())
4992 Result.getArrayFiller() = Filler;
4993 }
4994
Richard Smithd62306a2011-11-10 06:34:14 +00004995 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00004996 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00004997 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
4998 const Expr *Init =
4999 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00005000 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00005001 Info, Subobject, Init) ||
5002 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00005003 CAT->getElementType(), 1)) {
5004 if (!Info.keepEvaluatingAfterFailure())
5005 return false;
5006 Success = false;
5007 }
Richard Smithd62306a2011-11-10 06:34:14 +00005008 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005009
Richard Smith9543c5e2013-04-22 14:44:29 +00005010 if (!Result.hasArrayFiller())
5011 return Success;
5012
5013 // If we get here, we have a trivial filler, which we can just evaluate
5014 // once and splat over the rest of the array elements.
5015 assert(FillerExpr && "no array filler for incomplete init list");
5016 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5017 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00005018}
5019
Richard Smith027bf112011-11-17 22:56:20 +00005020bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005021 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5022}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005023
Richard Smith9543c5e2013-04-22 14:44:29 +00005024bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5025 const LValue &Subobject,
5026 APValue *Value,
5027 QualType Type) {
5028 bool HadZeroInit = !Value->isUninit();
5029
5030 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5031 unsigned N = CAT->getSize().getZExtValue();
5032
5033 // Preserve the array filler if we had prior zero-initialization.
5034 APValue Filler =
5035 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5036 : APValue();
5037
5038 *Value = APValue(APValue::UninitArray(), N, N);
5039
5040 if (HadZeroInit)
5041 for (unsigned I = 0; I != N; ++I)
5042 Value->getArrayInitializedElt(I) = Filler;
5043
5044 // Initialize the elements.
5045 LValue ArrayElt = Subobject;
5046 ArrayElt.addArray(Info, E, CAT);
5047 for (unsigned I = 0; I != N; ++I)
5048 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5049 CAT->getElementType()) ||
5050 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5051 CAT->getElementType(), 1))
5052 return false;
5053
5054 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005055 }
Richard Smith027bf112011-11-17 22:56:20 +00005056
Richard Smith9543c5e2013-04-22 14:44:29 +00005057 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00005058 return Error(E);
5059
Richard Smith027bf112011-11-17 22:56:20 +00005060 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00005061
Richard Smithfddd3842011-12-30 21:15:51 +00005062 bool ZeroInit = E->requiresZeroInitialization();
5063 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005064 if (HadZeroInit)
5065 return true;
5066
Richard Smithfddd3842011-12-30 21:15:51 +00005067 if (ZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005068 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005069 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005070 }
5071
Richard Smithcc36f692011-12-22 02:22:31 +00005072 const CXXRecordDecl *RD = FD->getParent();
5073 if (RD->isUnion())
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005074 *Value = APValue((FieldDecl*)0);
Richard Smithcc36f692011-12-22 02:22:31 +00005075 else
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005076 *Value =
Richard Smithcc36f692011-12-22 02:22:31 +00005077 APValue(APValue::UninitStruct(), RD->getNumBases(),
5078 std::distance(RD->field_begin(), RD->field_end()));
5079 return true;
5080 }
5081
Richard Smith027bf112011-11-17 22:56:20 +00005082 const FunctionDecl *Definition = 0;
5083 FD->getBody(Definition);
5084
Richard Smith357362d2011-12-13 06:39:58 +00005085 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5086 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005087
Richard Smith9eae7232012-01-12 18:54:33 +00005088 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005089 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005090 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005091 return false;
5092 }
5093
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005094 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005095 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00005096 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005097 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00005098}
5099
Richard Smithf3e9e432011-11-07 09:22:26 +00005100//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005101// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005102//
5103// As a GNU extension, we support casting pointers to sufficiently-wide integer
5104// types and back in constant folding. Integer values are thus represented
5105// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00005106//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005107
5108namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005109class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00005110 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith2e312c82012-03-03 22:46:17 +00005111 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005112public:
Richard Smith2e312c82012-03-03 22:46:17 +00005113 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005114 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005115
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005116 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005117 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005118 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005119 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005120 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005121 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005122 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005123 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005124 return true;
5125 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005126 bool Success(const llvm::APSInt &SI, const Expr *E) {
5127 return Success(SI, E, Result);
5128 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005129
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005130 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005131 assert(E->getType()->isIntegralOrEnumerationType() &&
5132 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005133 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005134 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005135 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005136 Result.getInt().setIsUnsigned(
5137 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005138 return true;
5139 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005140 bool Success(const llvm::APInt &I, const Expr *E) {
5141 return Success(I, E, Result);
5142 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005143
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005144 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005145 assert(E->getType()->isIntegralOrEnumerationType() &&
5146 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005147 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005148 return true;
5149 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005150 bool Success(uint64_t Value, const Expr *E) {
5151 return Success(Value, E, Result);
5152 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005153
Ken Dyckdbc01912011-03-11 02:13:43 +00005154 bool Success(CharUnits Size, const Expr *E) {
5155 return Success(Size.getQuantity(), E);
5156 }
5157
Richard Smith2e312c82012-03-03 22:46:17 +00005158 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005159 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00005160 Result = V;
5161 return true;
5162 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005163 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00005164 }
Mike Stump11289f42009-09-09 15:08:12 +00005165
Richard Smithfddd3842011-12-30 21:15:51 +00005166 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00005167
Peter Collingbournee9200682011-05-13 03:29:01 +00005168 //===--------------------------------------------------------------------===//
5169 // Visitor Methods
5170 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005171
Chris Lattner7174bf32008-07-12 00:38:25 +00005172 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005173 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005174 }
5175 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005176 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005177 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005178
5179 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5180 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005181 if (CheckReferencedDecl(E, E->getDecl()))
5182 return true;
5183
5184 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005185 }
5186 bool VisitMemberExpr(const MemberExpr *E) {
5187 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00005188 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005189 return true;
5190 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005191
5192 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005193 }
5194
Peter Collingbournee9200682011-05-13 03:29:01 +00005195 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005196 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00005197 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005198 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00005199
Peter Collingbournee9200682011-05-13 03:29:01 +00005200 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005201 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00005202
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005203 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005204 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005205 }
Mike Stump11289f42009-09-09 15:08:12 +00005206
Ted Kremeneke65b0862012-03-06 20:05:56 +00005207 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5208 return Success(E->getValue(), E);
5209 }
5210
Richard Smith4ce706a2011-10-11 21:43:33 +00005211 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00005212 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005213 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005214 }
5215
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005216 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005217 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005218 }
5219
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005220 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
5221 return Success(E->getValue(), E);
5222 }
5223
Douglas Gregor29c42f22012-02-24 07:38:34 +00005224 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5225 return Success(E->getValue(), E);
5226 }
5227
John Wiegley6242b6a2011-04-28 00:16:57 +00005228 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5229 return Success(E->getValue(), E);
5230 }
5231
John Wiegleyf9f65842011-04-25 06:54:41 +00005232 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5233 return Success(E->getValue(), E);
5234 }
5235
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005236 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005237 bool VisitUnaryImag(const UnaryOperator *E);
5238
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005239 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005240 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00005241
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005242private:
Ken Dyck160146e2010-01-27 17:10:57 +00005243 CharUnits GetAlignOfExpr(const Expr *E);
5244 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00005245 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00005246 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005247 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00005248};
Chris Lattner05706e882008-07-11 18:11:29 +00005249} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005250
Richard Smith11562c52011-10-28 17:51:58 +00005251/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
5252/// produce either the integer value or a pointer.
5253///
5254/// GCC has a heinous extension which folds casts between pointer types and
5255/// pointer-sized integral types. We support this by allowing the evaluation of
5256/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
5257/// Some simple arithmetic on such values is supported (they are treated much
5258/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00005259static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00005260 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005261 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005262 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00005263}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005264
Richard Smithf57d8cb2011-12-09 22:58:01 +00005265static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00005266 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005267 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00005268 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005269 if (!Val.isInt()) {
5270 // FIXME: It would be better to produce the diagnostic for casting
5271 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00005272 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005273 return false;
5274 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005275 Result = Val.getInt();
5276 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005277}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005278
Richard Smithf57d8cb2011-12-09 22:58:01 +00005279/// Check whether the given declaration can be directly converted to an integral
5280/// rvalue. If not, no diagnostic is produced; there are other things we can
5281/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005282bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00005283 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005284 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005285 // Check for signedness/width mismatches between E type and ECD value.
5286 bool SameSign = (ECD->getInitVal().isSigned()
5287 == E->getType()->isSignedIntegerOrEnumerationType());
5288 bool SameWidth = (ECD->getInitVal().getBitWidth()
5289 == Info.Ctx.getIntWidth(E->getType()));
5290 if (SameSign && SameWidth)
5291 return Success(ECD->getInitVal(), E);
5292 else {
5293 // Get rid of mismatch (otherwise Success assertions will fail)
5294 // by computing a new value matching the type of E.
5295 llvm::APSInt Val = ECD->getInitVal();
5296 if (!SameSign)
5297 Val.setIsSigned(!ECD->getInitVal().isSigned());
5298 if (!SameWidth)
5299 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
5300 return Success(Val, E);
5301 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005302 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005303 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00005304}
5305
Chris Lattner86ee2862008-10-06 06:40:35 +00005306/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
5307/// as GCC.
5308static int EvaluateBuiltinClassifyType(const CallExpr *E) {
5309 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005310 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00005311 enum gcc_type_class {
5312 no_type_class = -1,
5313 void_type_class, integer_type_class, char_type_class,
5314 enumeral_type_class, boolean_type_class,
5315 pointer_type_class, reference_type_class, offset_type_class,
5316 real_type_class, complex_type_class,
5317 function_type_class, method_type_class,
5318 record_type_class, union_type_class,
5319 array_type_class, string_type_class,
5320 lang_type_class
5321 };
Mike Stump11289f42009-09-09 15:08:12 +00005322
5323 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00005324 // ideal, however it is what gcc does.
5325 if (E->getNumArgs() == 0)
5326 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00005327
Chris Lattner86ee2862008-10-06 06:40:35 +00005328 QualType ArgTy = E->getArg(0)->getType();
5329 if (ArgTy->isVoidType())
5330 return void_type_class;
5331 else if (ArgTy->isEnumeralType())
5332 return enumeral_type_class;
5333 else if (ArgTy->isBooleanType())
5334 return boolean_type_class;
5335 else if (ArgTy->isCharType())
5336 return string_type_class; // gcc doesn't appear to use char_type_class
5337 else if (ArgTy->isIntegerType())
5338 return integer_type_class;
5339 else if (ArgTy->isPointerType())
5340 return pointer_type_class;
5341 else if (ArgTy->isReferenceType())
5342 return reference_type_class;
5343 else if (ArgTy->isRealType())
5344 return real_type_class;
5345 else if (ArgTy->isComplexType())
5346 return complex_type_class;
5347 else if (ArgTy->isFunctionType())
5348 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00005349 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00005350 return record_type_class;
5351 else if (ArgTy->isUnionType())
5352 return union_type_class;
5353 else if (ArgTy->isArrayType())
5354 return array_type_class;
5355 else if (ArgTy->isUnionType())
5356 return union_type_class;
5357 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00005358 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00005359}
5360
Richard Smith5fab0c92011-12-28 19:48:30 +00005361/// EvaluateBuiltinConstantPForLValue - Determine the result of
5362/// __builtin_constant_p when applied to the given lvalue.
5363///
5364/// An lvalue is only "constant" if it is a pointer or reference to the first
5365/// character of a string literal.
5366template<typename LValue>
5367static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00005368 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00005369 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
5370}
5371
5372/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
5373/// GCC as we can manage.
5374static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
5375 QualType ArgType = Arg->getType();
5376
5377 // __builtin_constant_p always has one operand. The rules which gcc follows
5378 // are not precisely documented, but are as follows:
5379 //
5380 // - If the operand is of integral, floating, complex or enumeration type,
5381 // and can be folded to a known value of that type, it returns 1.
5382 // - If the operand and can be folded to a pointer to the first character
5383 // of a string literal (or such a pointer cast to an integral type), it
5384 // returns 1.
5385 //
5386 // Otherwise, it returns 0.
5387 //
5388 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
5389 // its support for this does not currently work.
5390 if (ArgType->isIntegralOrEnumerationType()) {
5391 Expr::EvalResult Result;
5392 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
5393 return false;
5394
5395 APValue &V = Result.Val;
5396 if (V.getKind() == APValue::Int)
5397 return true;
5398
5399 return EvaluateBuiltinConstantPForLValue(V);
5400 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
5401 return Arg->isEvaluatable(Ctx);
5402 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
5403 LValue LV;
5404 Expr::EvalStatus Status;
5405 EvalInfo Info(Ctx, Status);
5406 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
5407 : EvaluatePointer(Arg, LV, Info)) &&
5408 !Status.HasSideEffects)
5409 return EvaluateBuiltinConstantPForLValue(LV);
5410 }
5411
5412 // Anything else isn't considered to be sufficiently constant.
5413 return false;
5414}
5415
John McCall95007602010-05-10 23:27:23 +00005416/// Retrieves the "underlying object type" of the given expression,
5417/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00005418QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
5419 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
5420 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00005421 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00005422 } else if (const Expr *E = B.get<const Expr*>()) {
5423 if (isa<CompoundLiteralExpr>(E))
5424 return E->getType();
John McCall95007602010-05-10 23:27:23 +00005425 }
5426
5427 return QualType();
5428}
5429
Peter Collingbournee9200682011-05-13 03:29:01 +00005430bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00005431 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00005432
5433 {
5434 // The operand of __builtin_object_size is never evaluated for side-effects.
5435 // If there are any, but we can determine the pointed-to object anyway, then
5436 // ignore the side-effects.
5437 SpeculativeEvaluationRAII SpeculativeEval(Info);
5438 if (!EvaluatePointer(E->getArg(0), Base, Info))
5439 return false;
5440 }
John McCall95007602010-05-10 23:27:23 +00005441
5442 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00005443 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00005444
Richard Smithce40ad62011-11-12 22:28:03 +00005445 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00005446 if (T.isNull() ||
5447 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00005448 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00005449 T->isVariablyModifiedType() ||
5450 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005451 return Error(E);
John McCall95007602010-05-10 23:27:23 +00005452
5453 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
5454 CharUnits Offset = Base.getLValueOffset();
5455
5456 if (!Offset.isNegative() && Offset <= Size)
5457 Size -= Offset;
5458 else
5459 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00005460 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00005461}
5462
Peter Collingbournee9200682011-05-13 03:29:01 +00005463bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith01ba47d2012-04-13 00:45:38 +00005464 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005465 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00005466 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005467
5468 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00005469 if (TryEvaluateBuiltinObjectSize(E))
5470 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00005471
Richard Smith0421ce72012-08-07 04:16:51 +00005472 // If evaluating the argument has side-effects, we can't determine the size
5473 // of the object, and so we lower it to unknown now. CodeGen relies on us to
5474 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005475 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00005476 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00005477 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00005478 return Success(0, E);
5479 }
Mike Stump876387b2009-10-27 22:09:17 +00005480
Richard Smith01ade172012-05-23 04:13:20 +00005481 // Expression had no side effects, but we couldn't statically determine the
5482 // size of the referenced object.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005483 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005484 }
5485
Benjamin Kramera801f4a2012-10-06 14:42:22 +00005486 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00005487 case Builtin::BI__builtin_bswap32:
5488 case Builtin::BI__builtin_bswap64: {
5489 APSInt Val;
5490 if (!EvaluateInteger(E->getArg(0), Val, Info))
5491 return false;
5492
5493 return Success(Val.byteSwap(), E);
5494 }
5495
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005496 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005497 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00005498
Richard Smith5fab0c92011-12-28 19:48:30 +00005499 case Builtin::BI__builtin_constant_p:
5500 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smith10c7c902011-12-09 02:04:48 +00005501
Chris Lattnerd545ad12009-09-23 06:06:36 +00005502 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00005503 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00005504 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00005505 return Success(Operand, E);
5506 }
Eli Friedmand5c93992010-02-13 00:10:10 +00005507
5508 case Builtin::BI__builtin_expect:
5509 return Visit(E->getArg(0));
Richard Smith9cf080f2012-01-18 03:06:12 +00005510
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005511 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00005512 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005513 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00005514 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00005515 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
5516 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00005517 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00005518 // Fall through.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005519 case Builtin::BI__builtin_strlen:
5520 // As an extension, we support strlen() and __builtin_strlen() as constant
5521 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00005522 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005523 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
5524 // The string literal may have embedded null characters. Find the first
5525 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005526 StringRef Str = S->getString();
5527 StringRef::size_type Pos = Str.find(0);
5528 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005529 Str = Str.substr(0, Pos);
5530
5531 return Success(Str.size(), E);
5532 }
5533
Richard Smithf57d8cb2011-12-09 22:58:01 +00005534 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005535
Richard Smith01ba47d2012-04-13 00:45:38 +00005536 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00005537 case Builtin::BI__atomic_is_lock_free:
5538 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00005539 APSInt SizeVal;
5540 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
5541 return false;
5542
5543 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
5544 // of two less than the maximum inline atomic width, we know it is
5545 // lock-free. If the size isn't a power of two, or greater than the
5546 // maximum alignment where we promote atomics, we know it is not lock-free
5547 // (at least not in the sense of atomic_is_lock_free). Otherwise,
5548 // the answer can only be determined at runtime; for example, 16-byte
5549 // atomics have lock-free implementations on some, but not all,
5550 // x86-64 processors.
5551
5552 // Check power-of-two.
5553 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00005554 if (Size.isPowerOfTwo()) {
5555 // Check against inlining width.
5556 unsigned InlineWidthBits =
5557 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
5558 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
5559 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
5560 Size == CharUnits::One() ||
5561 E->getArg(1)->isNullPointerConstant(Info.Ctx,
5562 Expr::NPC_NeverValueDependent))
5563 // OK, we will inline appropriately-aligned operations of this size,
5564 // and _Atomic(T) is appropriately-aligned.
5565 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005566
Richard Smith01ba47d2012-04-13 00:45:38 +00005567 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
5568 castAs<PointerType>()->getPointeeType();
5569 if (!PointeeType->isIncompleteType() &&
5570 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
5571 // OK, we will inline operations on this object.
5572 return Success(1, E);
5573 }
5574 }
5575 }
Eli Friedmana4c26022011-10-17 21:44:23 +00005576
Richard Smith01ba47d2012-04-13 00:45:38 +00005577 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
5578 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005579 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005580 }
Chris Lattner7174bf32008-07-12 00:38:25 +00005581}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005582
Richard Smith8b3497e2011-10-31 01:37:14 +00005583static bool HasSameBase(const LValue &A, const LValue &B) {
5584 if (!A.getLValueBase())
5585 return !B.getLValueBase();
5586 if (!B.getLValueBase())
5587 return false;
5588
Richard Smithce40ad62011-11-12 22:28:03 +00005589 if (A.getLValueBase().getOpaqueValue() !=
5590 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00005591 const Decl *ADecl = GetLValueBaseDecl(A);
5592 if (!ADecl)
5593 return false;
5594 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00005595 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00005596 return false;
5597 }
5598
5599 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00005600 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00005601}
5602
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005603namespace {
Richard Smith11562c52011-10-28 17:51:58 +00005604
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005605/// \brief Data recursive integer evaluator of certain binary operators.
5606///
5607/// We use a data recursive algorithm for binary operators so that we are able
5608/// to handle extreme cases of chained binary operators without causing stack
5609/// overflow.
5610class DataRecursiveIntBinOpEvaluator {
5611 struct EvalResult {
5612 APValue Val;
5613 bool Failed;
5614
5615 EvalResult() : Failed(false) { }
5616
5617 void swap(EvalResult &RHS) {
5618 Val.swap(RHS.Val);
5619 Failed = RHS.Failed;
5620 RHS.Failed = false;
5621 }
5622 };
5623
5624 struct Job {
5625 const Expr *E;
5626 EvalResult LHSResult; // meaningful only for binary operator expression.
5627 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
5628
5629 Job() : StoredInfo(0) { }
5630 void startSpeculativeEval(EvalInfo &Info) {
5631 OldEvalStatus = Info.EvalStatus;
5632 Info.EvalStatus.Diag = 0;
5633 StoredInfo = &Info;
5634 }
5635 ~Job() {
5636 if (StoredInfo) {
5637 StoredInfo->EvalStatus = OldEvalStatus;
5638 }
5639 }
5640 private:
5641 EvalInfo *StoredInfo; // non-null if status changed.
5642 Expr::EvalStatus OldEvalStatus;
5643 };
5644
5645 SmallVector<Job, 16> Queue;
5646
5647 IntExprEvaluator &IntEval;
5648 EvalInfo &Info;
5649 APValue &FinalResult;
5650
5651public:
5652 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
5653 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
5654
5655 /// \brief True if \param E is a binary operator that we are going to handle
5656 /// data recursively.
5657 /// We handle binary operators that are comma, logical, or that have operands
5658 /// with integral or enumeration type.
5659 static bool shouldEnqueue(const BinaryOperator *E) {
5660 return E->getOpcode() == BO_Comma ||
5661 E->isLogicalOp() ||
5662 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5663 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00005664 }
5665
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005666 bool Traverse(const BinaryOperator *E) {
5667 enqueue(E);
5668 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00005669 while (!Queue.empty())
5670 process(PrevResult);
5671
5672 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005673
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005674 FinalResult.swap(PrevResult.Val);
5675 return true;
5676 }
5677
5678private:
5679 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
5680 return IntEval.Success(Value, E, Result);
5681 }
5682 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
5683 return IntEval.Success(Value, E, Result);
5684 }
5685 bool Error(const Expr *E) {
5686 return IntEval.Error(E);
5687 }
5688 bool Error(const Expr *E, diag::kind D) {
5689 return IntEval.Error(E, D);
5690 }
5691
5692 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
5693 return Info.CCEDiag(E, D);
5694 }
5695
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005696 // \brief Returns true if visiting the RHS is necessary, false otherwise.
5697 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005698 bool &SuppressRHSDiags);
5699
5700 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
5701 const BinaryOperator *E, APValue &Result);
5702
5703 void EvaluateExpr(const Expr *E, EvalResult &Result) {
5704 Result.Failed = !Evaluate(Result.Val, Info, E);
5705 if (Result.Failed)
5706 Result.Val = APValue();
5707 }
5708
Richard Trieuba4d0872012-03-21 23:30:30 +00005709 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005710
5711 void enqueue(const Expr *E) {
5712 E = E->IgnoreParens();
5713 Queue.resize(Queue.size()+1);
5714 Queue.back().E = E;
5715 Queue.back().Kind = Job::AnyExprKind;
5716 }
5717};
5718
5719}
5720
5721bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005722 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005723 bool &SuppressRHSDiags) {
5724 if (E->getOpcode() == BO_Comma) {
5725 // Ignore LHS but note if we could not evaluate it.
5726 if (LHSResult.Failed)
5727 Info.EvalStatus.HasSideEffects = true;
5728 return true;
5729 }
5730
5731 if (E->isLogicalOp()) {
5732 bool lhsResult;
5733 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005734 // We were able to evaluate the LHS, see if we can get away with not
5735 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005736 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005737 Success(lhsResult, E, LHSResult.Val);
5738 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005739 }
5740 } else {
5741 // Since we weren't able to evaluate the left hand side, it
5742 // must have had side effects.
5743 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005744
5745 // We can't evaluate the LHS; however, sometimes the result
5746 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
5747 // Don't ignore RHS and suppress diagnostics from this arm.
5748 SuppressRHSDiags = true;
5749 }
5750
5751 return true;
5752 }
5753
5754 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5755 E->getRHS()->getType()->isIntegralOrEnumerationType());
5756
5757 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005758 return false; // Ignore RHS;
5759
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005760 return true;
5761}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005762
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005763bool DataRecursiveIntBinOpEvaluator::
5764 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
5765 const BinaryOperator *E, APValue &Result) {
5766 if (E->getOpcode() == BO_Comma) {
5767 if (RHSResult.Failed)
5768 return false;
5769 Result = RHSResult.Val;
5770 return true;
5771 }
5772
5773 if (E->isLogicalOp()) {
5774 bool lhsResult, rhsResult;
5775 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
5776 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
5777
5778 if (LHSIsOK) {
5779 if (RHSIsOK) {
5780 if (E->getOpcode() == BO_LOr)
5781 return Success(lhsResult || rhsResult, E, Result);
5782 else
5783 return Success(lhsResult && rhsResult, E, Result);
5784 }
5785 } else {
5786 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005787 // We can't evaluate the LHS; however, sometimes the result
5788 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
5789 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005790 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005791 }
5792 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005793
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005794 return false;
5795 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005796
5797 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5798 E->getRHS()->getType()->isIntegralOrEnumerationType());
5799
5800 if (LHSResult.Failed || RHSResult.Failed)
5801 return false;
5802
5803 const APValue &LHSVal = LHSResult.Val;
5804 const APValue &RHSVal = RHSResult.Val;
5805
5806 // Handle cases like (unsigned long)&a + 4.
5807 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
5808 Result = LHSVal;
5809 CharUnits AdditionalOffset = CharUnits::fromQuantity(
5810 RHSVal.getInt().getZExtValue());
5811 if (E->getOpcode() == BO_Add)
5812 Result.getLValueOffset() += AdditionalOffset;
5813 else
5814 Result.getLValueOffset() -= AdditionalOffset;
5815 return true;
5816 }
5817
5818 // Handle cases like 4 + (unsigned long)&a
5819 if (E->getOpcode() == BO_Add &&
5820 RHSVal.isLValue() && LHSVal.isInt()) {
5821 Result = RHSVal;
5822 Result.getLValueOffset() += CharUnits::fromQuantity(
5823 LHSVal.getInt().getZExtValue());
5824 return true;
5825 }
5826
5827 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
5828 // Handle (intptr_t)&&A - (intptr_t)&&B.
5829 if (!LHSVal.getLValueOffset().isZero() ||
5830 !RHSVal.getLValueOffset().isZero())
5831 return false;
5832 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
5833 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
5834 if (!LHSExpr || !RHSExpr)
5835 return false;
5836 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
5837 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
5838 if (!LHSAddrExpr || !RHSAddrExpr)
5839 return false;
5840 // Make sure both labels come from the same function.
5841 if (LHSAddrExpr->getLabel()->getDeclContext() !=
5842 RHSAddrExpr->getLabel()->getDeclContext())
5843 return false;
5844 Result = APValue(LHSAddrExpr, RHSAddrExpr);
5845 return true;
5846 }
Richard Smith43e77732013-05-07 04:50:00 +00005847
5848 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005849 if (!LHSVal.isInt() || !RHSVal.isInt())
5850 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00005851
5852 // Set up the width and signedness manually, in case it can't be deduced
5853 // from the operation we're performing.
5854 // FIXME: Don't do this in the cases where we can deduce it.
5855 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
5856 E->getType()->isUnsignedIntegerOrEnumerationType());
5857 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
5858 RHSVal.getInt(), Value))
5859 return false;
5860 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005861}
5862
Richard Trieuba4d0872012-03-21 23:30:30 +00005863void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005864 Job &job = Queue.back();
5865
5866 switch (job.Kind) {
5867 case Job::AnyExprKind: {
5868 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
5869 if (shouldEnqueue(Bop)) {
5870 job.Kind = Job::BinOpKind;
5871 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00005872 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005873 }
5874 }
5875
5876 EvaluateExpr(job.E, Result);
5877 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005878 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005879 }
5880
5881 case Job::BinOpKind: {
5882 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005883 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005884 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005885 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005886 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005887 }
5888 if (SuppressRHSDiags)
5889 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005890 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005891 job.Kind = Job::BinOpVisitedLHSKind;
5892 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00005893 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005894 }
5895
5896 case Job::BinOpVisitedLHSKind: {
5897 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
5898 EvalResult RHS;
5899 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00005900 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005901 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005902 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005903 }
5904 }
5905
5906 llvm_unreachable("Invalid Job::Kind!");
5907}
5908
5909bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5910 if (E->isAssignmentOp())
5911 return Error(E);
5912
5913 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
5914 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00005915
Anders Carlssonacc79812008-11-16 07:17:21 +00005916 QualType LHSTy = E->getLHS()->getType();
5917 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005918
5919 if (LHSTy->isAnyComplexType()) {
5920 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00005921 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005922
Richard Smith253c2a32012-01-27 01:14:48 +00005923 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
5924 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005925 return false;
5926
Richard Smith253c2a32012-01-27 01:14:48 +00005927 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005928 return false;
5929
5930 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00005931 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005932 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00005933 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005934 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
5935
John McCalle3027922010-08-25 11:45:40 +00005936 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005937 return Success((CR_r == APFloat::cmpEqual &&
5938 CR_i == APFloat::cmpEqual), E);
5939 else {
John McCalle3027922010-08-25 11:45:40 +00005940 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005941 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00005942 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00005943 CR_r == APFloat::cmpLessThan ||
5944 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00005945 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00005946 CR_i == APFloat::cmpLessThan ||
5947 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005948 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005949 } else {
John McCalle3027922010-08-25 11:45:40 +00005950 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005951 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
5952 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
5953 else {
John McCalle3027922010-08-25 11:45:40 +00005954 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005955 "Invalid compex comparison.");
5956 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
5957 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
5958 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005959 }
5960 }
Mike Stump11289f42009-09-09 15:08:12 +00005961
Anders Carlssonacc79812008-11-16 07:17:21 +00005962 if (LHSTy->isRealFloatingType() &&
5963 RHSTy->isRealFloatingType()) {
5964 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00005965
Richard Smith253c2a32012-01-27 01:14:48 +00005966 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
5967 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00005968 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005969
Richard Smith253c2a32012-01-27 01:14:48 +00005970 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00005971 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005972
Anders Carlssonacc79812008-11-16 07:17:21 +00005973 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00005974
Anders Carlssonacc79812008-11-16 07:17:21 +00005975 switch (E->getOpcode()) {
5976 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005977 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00005978 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005979 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00005980 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005981 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00005982 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005983 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00005984 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00005985 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005986 E);
John McCalle3027922010-08-25 11:45:40 +00005987 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005988 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00005989 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00005990 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00005991 || CR == APFloat::cmpLessThan
5992 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00005993 }
Anders Carlssonacc79812008-11-16 07:17:21 +00005994 }
Mike Stump11289f42009-09-09 15:08:12 +00005995
Eli Friedmana38da572009-04-28 19:17:36 +00005996 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00005997 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00005998 LValue LHSValue, RHSValue;
5999
6000 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6001 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006002 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006003
Richard Smith253c2a32012-01-27 01:14:48 +00006004 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006005 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006006
Richard Smith8b3497e2011-10-31 01:37:14 +00006007 // Reject differing bases from the normal codepath; we special-case
6008 // comparisons to null.
6009 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006010 if (E->getOpcode() == BO_Sub) {
6011 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006012 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6013 return false;
6014 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00006015 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006016 if (!LHSExpr || !RHSExpr)
6017 return false;
6018 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6019 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6020 if (!LHSAddrExpr || !RHSAddrExpr)
6021 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006022 // Make sure both labels come from the same function.
6023 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6024 RHSAddrExpr->getLabel()->getDeclContext())
6025 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006026 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006027 return true;
6028 }
Richard Smith83c68212011-10-31 05:11:32 +00006029 // Inequalities and subtractions between unrelated pointers have
6030 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00006031 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006032 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006033 // A constant address may compare equal to the address of a symbol.
6034 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00006035 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006036 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6037 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006038 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006039 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00006040 // distinct addresses. In clang, the result of such a comparison is
6041 // unspecified, so it is not a constant expression. However, we do know
6042 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00006043 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6044 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006045 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006046 // We can't tell whether weak symbols will end up pointing to the same
6047 // object.
6048 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006049 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006050 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00006051 // (Note that clang defaults to -fmerge-all-constants, which can
6052 // lead to inconsistent results for comparisons involving the address
6053 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00006054 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00006055 }
Eli Friedman64004332009-03-23 04:38:34 +00006056
Richard Smith1b470412012-02-01 08:10:20 +00006057 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
6058 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
6059
Richard Smith84f6dcf2012-02-02 01:16:57 +00006060 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
6061 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
6062
John McCalle3027922010-08-25 11:45:40 +00006063 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00006064 // C++11 [expr.add]p6:
6065 // Unless both pointers point to elements of the same array object, or
6066 // one past the last element of the array object, the behavior is
6067 // undefined.
6068 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6069 !AreElementsOfSameArray(getType(LHSValue.Base),
6070 LHSDesignator, RHSDesignator))
6071 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
6072
Chris Lattner882bdf22010-04-20 17:13:14 +00006073 QualType Type = E->getLHS()->getType();
6074 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006075
Richard Smithd62306a2011-11-10 06:34:14 +00006076 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00006077 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00006078 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006079
Richard Smith1b470412012-02-01 08:10:20 +00006080 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
6081 // and produce incorrect results when it overflows. Such behavior
6082 // appears to be non-conforming, but is common, so perhaps we should
6083 // assume the standard intended for such cases to be undefined behavior
6084 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00006085
Richard Smith1b470412012-02-01 08:10:20 +00006086 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
6087 // overflow in the final conversion to ptrdiff_t.
6088 APSInt LHS(
6089 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
6090 APSInt RHS(
6091 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
6092 APSInt ElemSize(
6093 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
6094 APSInt TrueResult = (LHS - RHS) / ElemSize;
6095 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
6096
6097 if (Result.extend(65) != TrueResult)
6098 HandleOverflow(Info, E, TrueResult, E->getType());
6099 return Success(Result, E);
6100 }
Richard Smithde21b242012-01-31 06:41:30 +00006101
6102 // C++11 [expr.rel]p3:
6103 // Pointers to void (after pointer conversions) can be compared, with a
6104 // result defined as follows: If both pointers represent the same
6105 // address or are both the null pointer value, the result is true if the
6106 // operator is <= or >= and false otherwise; otherwise the result is
6107 // unspecified.
6108 // We interpret this as applying to pointers to *cv* void.
6109 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00006110 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00006111 CCEDiag(E, diag::note_constexpr_void_comparison);
6112
Richard Smith84f6dcf2012-02-02 01:16:57 +00006113 // C++11 [expr.rel]p2:
6114 // - If two pointers point to non-static data members of the same object,
6115 // or to subobjects or array elements fo such members, recursively, the
6116 // pointer to the later declared member compares greater provided the
6117 // two members have the same access control and provided their class is
6118 // not a union.
6119 // [...]
6120 // - Otherwise pointer comparisons are unspecified.
6121 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6122 E->isRelationalOp()) {
6123 bool WasArrayIndex;
6124 unsigned Mismatch =
6125 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
6126 RHSDesignator, WasArrayIndex);
6127 // At the point where the designators diverge, the comparison has a
6128 // specified value if:
6129 // - we are comparing array indices
6130 // - we are comparing fields of a union, or fields with the same access
6131 // Otherwise, the result is unspecified and thus the comparison is not a
6132 // constant expression.
6133 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
6134 Mismatch < RHSDesignator.Entries.size()) {
6135 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
6136 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
6137 if (!LF && !RF)
6138 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
6139 else if (!LF)
6140 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6141 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
6142 << RF->getParent() << RF;
6143 else if (!RF)
6144 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6145 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
6146 << LF->getParent() << LF;
6147 else if (!LF->getParent()->isUnion() &&
6148 LF->getAccess() != RF->getAccess())
6149 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
6150 << LF << LF->getAccess() << RF << RF->getAccess()
6151 << LF->getParent();
6152 }
6153 }
6154
Eli Friedman6c31cb42012-04-16 04:30:08 +00006155 // The comparison here must be unsigned, and performed with the same
6156 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00006157 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
6158 uint64_t CompareLHS = LHSOffset.getQuantity();
6159 uint64_t CompareRHS = RHSOffset.getQuantity();
6160 assert(PtrSize <= 64 && "Unexpected pointer width");
6161 uint64_t Mask = ~0ULL >> (64 - PtrSize);
6162 CompareLHS &= Mask;
6163 CompareRHS &= Mask;
6164
Eli Friedman2f5b7c52012-04-16 19:23:57 +00006165 // If there is a base and this is a relational operator, we can only
6166 // compare pointers within the object in question; otherwise, the result
6167 // depends on where the object is located in memory.
6168 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
6169 QualType BaseTy = getType(LHSValue.Base);
6170 if (BaseTy->isIncompleteType())
6171 return Error(E);
6172 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
6173 uint64_t OffsetLimit = Size.getQuantity();
6174 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
6175 return Error(E);
6176 }
6177
Richard Smith8b3497e2011-10-31 01:37:14 +00006178 switch (E->getOpcode()) {
6179 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00006180 case BO_LT: return Success(CompareLHS < CompareRHS, E);
6181 case BO_GT: return Success(CompareLHS > CompareRHS, E);
6182 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
6183 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
6184 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
6185 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00006186 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006187 }
6188 }
Richard Smith7bb00672012-02-01 01:42:44 +00006189
6190 if (LHSTy->isMemberPointerType()) {
6191 assert(E->isEqualityOp() && "unexpected member pointer operation");
6192 assert(RHSTy->isMemberPointerType() && "invalid comparison");
6193
6194 MemberPtr LHSValue, RHSValue;
6195
6196 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
6197 if (!LHSOK && Info.keepEvaluatingAfterFailure())
6198 return false;
6199
6200 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6201 return false;
6202
6203 // C++11 [expr.eq]p2:
6204 // If both operands are null, they compare equal. Otherwise if only one is
6205 // null, they compare unequal.
6206 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
6207 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
6208 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6209 }
6210
6211 // Otherwise if either is a pointer to a virtual member function, the
6212 // result is unspecified.
6213 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
6214 if (MD->isVirtual())
6215 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6216 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
6217 if (MD->isVirtual())
6218 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6219
6220 // Otherwise they compare equal if and only if they would refer to the
6221 // same member of the same most derived object or the same subobject if
6222 // they were dereferenced with a hypothetical object of the associated
6223 // class type.
6224 bool Equal = LHSValue == RHSValue;
6225 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6226 }
6227
Richard Smithab44d9b2012-02-14 22:35:28 +00006228 if (LHSTy->isNullPtrType()) {
6229 assert(E->isComparisonOp() && "unexpected nullptr operation");
6230 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
6231 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
6232 // are compared, the result is true of the operator is <=, >= or ==, and
6233 // false otherwise.
6234 BinaryOperator::Opcode Opcode = E->getOpcode();
6235 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
6236 }
6237
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006238 assert((!LHSTy->isIntegralOrEnumerationType() ||
6239 !RHSTy->isIntegralOrEnumerationType()) &&
6240 "DataRecursiveIntBinOpEvaluator should have handled integral types");
6241 // We can't continue from here for non-integral types.
6242 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00006243}
6244
Ken Dyck160146e2010-01-27 17:10:57 +00006245CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00006246 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
6247 // result shall be the alignment of the referenced type."
6248 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6249 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00006250
6251 // __alignof is defined to return the preferred alignment.
6252 return Info.Ctx.toCharUnitsFromBits(
6253 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00006254}
6255
Ken Dyck160146e2010-01-27 17:10:57 +00006256CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00006257 E = E->IgnoreParens();
6258
John McCall768439e2013-05-06 07:40:34 +00006259 // The kinds of expressions that we have special-case logic here for
6260 // should be kept up to date with the special checks for those
6261 // expressions in Sema.
6262
Chris Lattner68061312009-01-24 21:53:27 +00006263 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00006264 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00006265 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006266 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6267 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00006268
Chris Lattner68061312009-01-24 21:53:27 +00006269 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006270 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6271 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00006272
Chris Lattner24aeeab2009-01-24 21:09:06 +00006273 return GetAlignOfType(E->getType());
6274}
6275
6276
Peter Collingbournee190dee2011-03-11 19:24:49 +00006277/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
6278/// a result as the expression's type.
6279bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
6280 const UnaryExprOrTypeTraitExpr *E) {
6281 switch(E->getKind()) {
6282 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00006283 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00006284 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006285 else
Ken Dyckdbc01912011-03-11 02:13:43 +00006286 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006287 }
Eli Friedman64004332009-03-23 04:38:34 +00006288
Peter Collingbournee190dee2011-03-11 19:24:49 +00006289 case UETT_VecStep: {
6290 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00006291
Peter Collingbournee190dee2011-03-11 19:24:49 +00006292 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00006293 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00006294
Peter Collingbournee190dee2011-03-11 19:24:49 +00006295 // The vec_step built-in functions that take a 3-component
6296 // vector return 4. (OpenCL 1.1 spec 6.11.12)
6297 if (n == 3)
6298 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00006299
Peter Collingbournee190dee2011-03-11 19:24:49 +00006300 return Success(n, E);
6301 } else
6302 return Success(1, E);
6303 }
6304
6305 case UETT_SizeOf: {
6306 QualType SrcTy = E->getTypeOfArgument();
6307 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
6308 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00006309 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
6310 SrcTy = Ref->getPointeeType();
6311
Richard Smithd62306a2011-11-10 06:34:14 +00006312 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00006313 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00006314 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006315 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006316 }
6317 }
6318
6319 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006320}
6321
Peter Collingbournee9200682011-05-13 03:29:01 +00006322bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00006323 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00006324 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00006325 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006326 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00006327 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00006328 for (unsigned i = 0; i != n; ++i) {
6329 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
6330 switch (ON.getKind()) {
6331 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00006332 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00006333 APSInt IdxResult;
6334 if (!EvaluateInteger(Idx, IdxResult, Info))
6335 return false;
6336 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
6337 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006338 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006339 CurrentType = AT->getElementType();
6340 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
6341 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00006342 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00006343 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006344
Douglas Gregor882211c2010-04-28 22:16:22 +00006345 case OffsetOfExpr::OffsetOfNode::Field: {
6346 FieldDecl *MemberDecl = ON.getField();
6347 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006348 if (!RT)
6349 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006350 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006351 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00006352 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00006353 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00006354 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00006355 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00006356 CurrentType = MemberDecl->getType().getNonReferenceType();
6357 break;
6358 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006359
Douglas Gregor882211c2010-04-28 22:16:22 +00006360 case OffsetOfExpr::OffsetOfNode::Identifier:
6361 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00006362
Douglas Gregord1702062010-04-29 00:18:15 +00006363 case OffsetOfExpr::OffsetOfNode::Base: {
6364 CXXBaseSpecifier *BaseSpec = ON.getBase();
6365 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006366 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006367
6368 // Find the layout of the class whose base we are looking into.
6369 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006370 if (!RT)
6371 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006372 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006373 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00006374 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
6375
6376 // Find the base class itself.
6377 CurrentType = BaseSpec->getType();
6378 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
6379 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006380 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006381
6382 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00006383 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00006384 break;
6385 }
Douglas Gregor882211c2010-04-28 22:16:22 +00006386 }
6387 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006388 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006389}
6390
Chris Lattnere13042c2008-07-11 19:10:17 +00006391bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006392 switch (E->getOpcode()) {
6393 default:
6394 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
6395 // See C99 6.6p3.
6396 return Error(E);
6397 case UO_Extension:
6398 // FIXME: Should extension allow i-c-e extension expressions in its scope?
6399 // If so, we could clear the diagnostic ID.
6400 return Visit(E->getSubExpr());
6401 case UO_Plus:
6402 // The result is just the value.
6403 return Visit(E->getSubExpr());
6404 case UO_Minus: {
6405 if (!Visit(E->getSubExpr()))
6406 return false;
6407 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00006408 const APSInt &Value = Result.getInt();
6409 if (Value.isSigned() && Value.isMinSignedValue())
6410 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
6411 E->getType());
6412 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006413 }
6414 case UO_Not: {
6415 if (!Visit(E->getSubExpr()))
6416 return false;
6417 if (!Result.isInt()) return Error(E);
6418 return Success(~Result.getInt(), E);
6419 }
6420 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00006421 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00006422 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00006423 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006424 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006425 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006426 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006427}
Mike Stump11289f42009-09-09 15:08:12 +00006428
Chris Lattner477c4be2008-07-12 01:15:53 +00006429/// HandleCast - This is used to evaluate implicit or explicit casts where the
6430/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00006431bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
6432 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006433 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00006434 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006435
Eli Friedmanc757de22011-03-25 00:43:55 +00006436 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00006437 case CK_BaseToDerived:
6438 case CK_DerivedToBase:
6439 case CK_UncheckedDerivedToBase:
6440 case CK_Dynamic:
6441 case CK_ToUnion:
6442 case CK_ArrayToPointerDecay:
6443 case CK_FunctionToPointerDecay:
6444 case CK_NullToPointer:
6445 case CK_NullToMemberPointer:
6446 case CK_BaseToDerivedMemberPointer:
6447 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00006448 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00006449 case CK_ConstructorConversion:
6450 case CK_IntegralToPointer:
6451 case CK_ToVoid:
6452 case CK_VectorSplat:
6453 case CK_IntegralToFloating:
6454 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00006455 case CK_CPointerToObjCPointerCast:
6456 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006457 case CK_AnyPointerToBlockPointerCast:
6458 case CK_ObjCObjectLValueCast:
6459 case CK_FloatingRealToComplex:
6460 case CK_FloatingComplexToReal:
6461 case CK_FloatingComplexCast:
6462 case CK_FloatingComplexToIntegralComplex:
6463 case CK_IntegralRealToComplex:
6464 case CK_IntegralComplexCast:
6465 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00006466 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006467 case CK_ZeroToOCLEvent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006468 llvm_unreachable("invalid cast kind for integral value");
6469
Eli Friedman9faf2f92011-03-25 19:07:11 +00006470 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006471 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006472 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00006473 case CK_ARCProduceObject:
6474 case CK_ARCConsumeObject:
6475 case CK_ARCReclaimReturnedObject:
6476 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00006477 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006478 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006479
Richard Smith4ef685b2012-01-17 21:17:26 +00006480 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00006481 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006482 case CK_AtomicToNonAtomic:
6483 case CK_NonAtomicToAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00006484 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00006485 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006486
6487 case CK_MemberPointerToBoolean:
6488 case CK_PointerToBoolean:
6489 case CK_IntegralToBoolean:
6490 case CK_FloatingToBoolean:
6491 case CK_FloatingComplexToBoolean:
6492 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006493 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00006494 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00006495 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006496 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006497 }
6498
Eli Friedmanc757de22011-03-25 00:43:55 +00006499 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00006500 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00006501 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00006502
Eli Friedman742421e2009-02-20 01:15:07 +00006503 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006504 // Allow casts of address-of-label differences if they are no-ops
6505 // or narrowing. (The narrowing case isn't actually guaranteed to
6506 // be constant-evaluatable except in some narrow cases which are hard
6507 // to detect here. We let it through on the assumption the user knows
6508 // what they are doing.)
6509 if (Result.isAddrLabelDiff())
6510 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00006511 // Only allow casts of lvalues if they are lossless.
6512 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
6513 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006514
Richard Smith911e1422012-01-30 22:27:01 +00006515 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
6516 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00006517 }
Mike Stump11289f42009-09-09 15:08:12 +00006518
Eli Friedmanc757de22011-03-25 00:43:55 +00006519 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00006520 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6521
John McCall45d55e42010-05-07 21:00:08 +00006522 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00006523 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00006524 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00006525
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006526 if (LV.getLValueBase()) {
6527 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00006528 // FIXME: Allow a larger integer size than the pointer size, and allow
6529 // narrowing back down to pointer width in subsequent integral casts.
6530 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006531 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006532 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006533
Richard Smithcf74da72011-11-16 07:18:12 +00006534 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00006535 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006536 return true;
6537 }
6538
Ken Dyck02990832010-01-15 12:37:54 +00006539 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
6540 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00006541 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006542 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006543
Eli Friedmanc757de22011-03-25 00:43:55 +00006544 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00006545 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006546 if (!EvaluateComplex(SubExpr, C, Info))
6547 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00006548 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006549 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00006550
Eli Friedmanc757de22011-03-25 00:43:55 +00006551 case CK_FloatingToIntegral: {
6552 APFloat F(0.0);
6553 if (!EvaluateFloat(SubExpr, F, Info))
6554 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00006555
Richard Smith357362d2011-12-13 06:39:58 +00006556 APSInt Value;
6557 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
6558 return false;
6559 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006560 }
6561 }
Mike Stump11289f42009-09-09 15:08:12 +00006562
Eli Friedmanc757de22011-03-25 00:43:55 +00006563 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00006564}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006565
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006566bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6567 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00006568 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006569 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
6570 return false;
6571 if (!LV.isComplexInt())
6572 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006573 return Success(LV.getComplexIntReal(), E);
6574 }
6575
6576 return Visit(E->getSubExpr());
6577}
6578
Eli Friedman4e7a2412009-02-27 04:45:43 +00006579bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006580 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00006581 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006582 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
6583 return false;
6584 if (!LV.isComplexInt())
6585 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006586 return Success(LV.getComplexIntImag(), E);
6587 }
6588
Richard Smith4a678122011-10-24 18:44:57 +00006589 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00006590 return Success(0, E);
6591}
6592
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006593bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
6594 return Success(E->getPackLength(), E);
6595}
6596
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006597bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
6598 return Success(E->getValue(), E);
6599}
6600
Chris Lattner05706e882008-07-11 18:11:29 +00006601//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00006602// Float Evaluation
6603//===----------------------------------------------------------------------===//
6604
6605namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006606class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00006607 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00006608 APFloat &Result;
6609public:
6610 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006611 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00006612
Richard Smith2e312c82012-03-03 22:46:17 +00006613 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006614 Result = V.getFloat();
6615 return true;
6616 }
Eli Friedman24c01542008-08-22 00:06:13 +00006617
Richard Smithfddd3842011-12-30 21:15:51 +00006618 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00006619 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
6620 return true;
6621 }
6622
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006623 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00006624
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006625 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00006626 bool VisitBinaryOperator(const BinaryOperator *E);
6627 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006628 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00006629
John McCallb1fb0d32010-05-07 22:08:54 +00006630 bool VisitUnaryReal(const UnaryOperator *E);
6631 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00006632
Richard Smithfddd3842011-12-30 21:15:51 +00006633 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00006634};
6635} // end anonymous namespace
6636
6637static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006638 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006639 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00006640}
6641
Jay Foad39c79802011-01-12 09:06:06 +00006642static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00006643 QualType ResultTy,
6644 const Expr *Arg,
6645 bool SNaN,
6646 llvm::APFloat &Result) {
6647 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
6648 if (!S) return false;
6649
6650 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
6651
6652 llvm::APInt fill;
6653
6654 // Treat empty strings as if they were zero.
6655 if (S->getString().empty())
6656 fill = llvm::APInt(32, 0);
6657 else if (S->getString().getAsInteger(0, fill))
6658 return false;
6659
6660 if (SNaN)
6661 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
6662 else
6663 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
6664 return true;
6665}
6666
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006667bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006668 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006669 default:
6670 return ExprEvaluatorBaseTy::VisitCallExpr(E);
6671
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006672 case Builtin::BI__builtin_huge_val:
6673 case Builtin::BI__builtin_huge_valf:
6674 case Builtin::BI__builtin_huge_vall:
6675 case Builtin::BI__builtin_inf:
6676 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00006677 case Builtin::BI__builtin_infl: {
6678 const llvm::fltSemantics &Sem =
6679 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00006680 Result = llvm::APFloat::getInf(Sem);
6681 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00006682 }
Mike Stump11289f42009-09-09 15:08:12 +00006683
John McCall16291492010-02-28 13:00:19 +00006684 case Builtin::BI__builtin_nans:
6685 case Builtin::BI__builtin_nansf:
6686 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006687 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6688 true, Result))
6689 return Error(E);
6690 return true;
John McCall16291492010-02-28 13:00:19 +00006691
Chris Lattner0b7282e2008-10-06 06:31:58 +00006692 case Builtin::BI__builtin_nan:
6693 case Builtin::BI__builtin_nanf:
6694 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00006695 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00006696 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00006697 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6698 false, Result))
6699 return Error(E);
6700 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006701
6702 case Builtin::BI__builtin_fabs:
6703 case Builtin::BI__builtin_fabsf:
6704 case Builtin::BI__builtin_fabsl:
6705 if (!EvaluateFloat(E->getArg(0), Result, Info))
6706 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006707
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006708 if (Result.isNegative())
6709 Result.changeSign();
6710 return true;
6711
Mike Stump11289f42009-09-09 15:08:12 +00006712 case Builtin::BI__builtin_copysign:
6713 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006714 case Builtin::BI__builtin_copysignl: {
6715 APFloat RHS(0.);
6716 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
6717 !EvaluateFloat(E->getArg(1), RHS, Info))
6718 return false;
6719 Result.copySign(RHS);
6720 return true;
6721 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006722 }
6723}
6724
John McCallb1fb0d32010-05-07 22:08:54 +00006725bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00006726 if (E->getSubExpr()->getType()->isAnyComplexType()) {
6727 ComplexValue CV;
6728 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
6729 return false;
6730 Result = CV.FloatReal;
6731 return true;
6732 }
6733
6734 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00006735}
6736
6737bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00006738 if (E->getSubExpr()->getType()->isAnyComplexType()) {
6739 ComplexValue CV;
6740 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
6741 return false;
6742 Result = CV.FloatImag;
6743 return true;
6744 }
6745
Richard Smith4a678122011-10-24 18:44:57 +00006746 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00006747 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
6748 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00006749 return true;
6750}
6751
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006752bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006753 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006754 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006755 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00006756 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00006757 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00006758 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
6759 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006760 Result.changeSign();
6761 return true;
6762 }
6763}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006764
Eli Friedman24c01542008-08-22 00:06:13 +00006765bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006766 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
6767 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00006768
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006769 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00006770 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
6771 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00006772 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00006773 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
6774 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00006775}
6776
6777bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
6778 Result = E->getValue();
6779 return true;
6780}
6781
Peter Collingbournee9200682011-05-13 03:29:01 +00006782bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
6783 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00006784
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006785 switch (E->getCastKind()) {
6786 default:
Richard Smith11562c52011-10-28 17:51:58 +00006787 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006788
6789 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006790 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00006791 return EvaluateInteger(SubExpr, IntResult, Info) &&
6792 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
6793 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006794 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006795
6796 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006797 if (!Visit(SubExpr))
6798 return false;
Richard Smith357362d2011-12-13 06:39:58 +00006799 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
6800 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006801 }
John McCalld7646252010-11-14 08:17:51 +00006802
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006803 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00006804 ComplexValue V;
6805 if (!EvaluateComplex(SubExpr, V, Info))
6806 return false;
6807 Result = V.getComplexFloatReal();
6808 return true;
6809 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006810 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006811}
6812
Eli Friedman24c01542008-08-22 00:06:13 +00006813//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006814// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00006815//===----------------------------------------------------------------------===//
6816
6817namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006818class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00006819 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00006820 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00006821
Anders Carlsson537969c2008-11-16 20:27:53 +00006822public:
John McCall93d91dc2010-05-07 17:22:02 +00006823 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006824 : ExprEvaluatorBaseTy(info), Result(Result) {}
6825
Richard Smith2e312c82012-03-03 22:46:17 +00006826 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006827 Result.setFrom(V);
6828 return true;
6829 }
Mike Stump11289f42009-09-09 15:08:12 +00006830
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006831 bool ZeroInitialization(const Expr *E);
6832
Anders Carlsson537969c2008-11-16 20:27:53 +00006833 //===--------------------------------------------------------------------===//
6834 // Visitor Methods
6835 //===--------------------------------------------------------------------===//
6836
Peter Collingbournee9200682011-05-13 03:29:01 +00006837 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006838 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00006839 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006840 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006841 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00006842};
6843} // end anonymous namespace
6844
John McCall93d91dc2010-05-07 17:22:02 +00006845static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
6846 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006847 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006848 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00006849}
6850
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006851bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00006852 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006853 if (ElemTy->isRealFloatingType()) {
6854 Result.makeComplexFloat();
6855 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
6856 Result.FloatReal = Zero;
6857 Result.FloatImag = Zero;
6858 } else {
6859 Result.makeComplexInt();
6860 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
6861 Result.IntReal = Zero;
6862 Result.IntImag = Zero;
6863 }
6864 return true;
6865}
6866
Peter Collingbournee9200682011-05-13 03:29:01 +00006867bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
6868 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006869
6870 if (SubExpr->getType()->isRealFloatingType()) {
6871 Result.makeComplexFloat();
6872 APFloat &Imag = Result.FloatImag;
6873 if (!EvaluateFloat(SubExpr, Imag, Info))
6874 return false;
6875
6876 Result.FloatReal = APFloat(Imag.getSemantics());
6877 return true;
6878 } else {
6879 assert(SubExpr->getType()->isIntegerType() &&
6880 "Unexpected imaginary literal.");
6881
6882 Result.makeComplexInt();
6883 APSInt &Imag = Result.IntImag;
6884 if (!EvaluateInteger(SubExpr, Imag, Info))
6885 return false;
6886
6887 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
6888 return true;
6889 }
6890}
6891
Peter Collingbournee9200682011-05-13 03:29:01 +00006892bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006893
John McCallfcef3cf2010-12-14 17:51:41 +00006894 switch (E->getCastKind()) {
6895 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006896 case CK_BaseToDerived:
6897 case CK_DerivedToBase:
6898 case CK_UncheckedDerivedToBase:
6899 case CK_Dynamic:
6900 case CK_ToUnion:
6901 case CK_ArrayToPointerDecay:
6902 case CK_FunctionToPointerDecay:
6903 case CK_NullToPointer:
6904 case CK_NullToMemberPointer:
6905 case CK_BaseToDerivedMemberPointer:
6906 case CK_DerivedToBaseMemberPointer:
6907 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00006908 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00006909 case CK_ConstructorConversion:
6910 case CK_IntegralToPointer:
6911 case CK_PointerToIntegral:
6912 case CK_PointerToBoolean:
6913 case CK_ToVoid:
6914 case CK_VectorSplat:
6915 case CK_IntegralCast:
6916 case CK_IntegralToBoolean:
6917 case CK_IntegralToFloating:
6918 case CK_FloatingToIntegral:
6919 case CK_FloatingToBoolean:
6920 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00006921 case CK_CPointerToObjCPointerCast:
6922 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006923 case CK_AnyPointerToBlockPointerCast:
6924 case CK_ObjCObjectLValueCast:
6925 case CK_FloatingComplexToReal:
6926 case CK_FloatingComplexToBoolean:
6927 case CK_IntegralComplexToReal:
6928 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00006929 case CK_ARCProduceObject:
6930 case CK_ARCConsumeObject:
6931 case CK_ARCReclaimReturnedObject:
6932 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00006933 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00006934 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006935 case CK_ZeroToOCLEvent:
John McCallfcef3cf2010-12-14 17:51:41 +00006936 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00006937
John McCallfcef3cf2010-12-14 17:51:41 +00006938 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006939 case CK_AtomicToNonAtomic:
6940 case CK_NonAtomicToAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00006941 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00006942 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00006943
6944 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006945 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006946 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006947 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00006948
6949 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006950 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00006951 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006952 return false;
6953
John McCallfcef3cf2010-12-14 17:51:41 +00006954 Result.makeComplexFloat();
6955 Result.FloatImag = APFloat(Real.getSemantics());
6956 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006957 }
6958
John McCallfcef3cf2010-12-14 17:51:41 +00006959 case CK_FloatingComplexCast: {
6960 if (!Visit(E->getSubExpr()))
6961 return false;
6962
6963 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6964 QualType From
6965 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6966
Richard Smith357362d2011-12-13 06:39:58 +00006967 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
6968 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006969 }
6970
6971 case CK_FloatingComplexToIntegralComplex: {
6972 if (!Visit(E->getSubExpr()))
6973 return false;
6974
6975 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6976 QualType From
6977 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6978 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00006979 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
6980 To, Result.IntReal) &&
6981 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
6982 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006983 }
6984
6985 case CK_IntegralRealToComplex: {
6986 APSInt &Real = Result.IntReal;
6987 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
6988 return false;
6989
6990 Result.makeComplexInt();
6991 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
6992 return true;
6993 }
6994
6995 case CK_IntegralComplexCast: {
6996 if (!Visit(E->getSubExpr()))
6997 return false;
6998
6999 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7000 QualType From
7001 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7002
Richard Smith911e1422012-01-30 22:27:01 +00007003 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7004 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007005 return true;
7006 }
7007
7008 case CK_IntegralComplexToFloatingComplex: {
7009 if (!Visit(E->getSubExpr()))
7010 return false;
7011
Ted Kremenek28831752012-08-23 20:46:57 +00007012 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007013 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00007014 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007015 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00007016 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7017 To, Result.FloatReal) &&
7018 HandleIntToFloatCast(Info, E, From, Result.IntImag,
7019 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007020 }
7021 }
7022
7023 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007024}
7025
John McCall93d91dc2010-05-07 17:22:02 +00007026bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007027 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00007028 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7029
Richard Smith253c2a32012-01-27 01:14:48 +00007030 bool LHSOK = Visit(E->getLHS());
7031 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00007032 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007033
John McCall93d91dc2010-05-07 17:22:02 +00007034 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00007035 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00007036 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007037
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007038 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
7039 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007040 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007041 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007042 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007043 if (Result.isComplexFloat()) {
7044 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
7045 APFloat::rmNearestTiesToEven);
7046 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
7047 APFloat::rmNearestTiesToEven);
7048 } else {
7049 Result.getComplexIntReal() += RHS.getComplexIntReal();
7050 Result.getComplexIntImag() += RHS.getComplexIntImag();
7051 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007052 break;
John McCalle3027922010-08-25 11:45:40 +00007053 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007054 if (Result.isComplexFloat()) {
7055 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
7056 APFloat::rmNearestTiesToEven);
7057 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
7058 APFloat::rmNearestTiesToEven);
7059 } else {
7060 Result.getComplexIntReal() -= RHS.getComplexIntReal();
7061 Result.getComplexIntImag() -= RHS.getComplexIntImag();
7062 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007063 break;
John McCalle3027922010-08-25 11:45:40 +00007064 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007065 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00007066 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007067 APFloat &LHS_r = LHS.getComplexFloatReal();
7068 APFloat &LHS_i = LHS.getComplexFloatImag();
7069 APFloat &RHS_r = RHS.getComplexFloatReal();
7070 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00007071
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007072 APFloat Tmp = LHS_r;
7073 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7074 Result.getComplexFloatReal() = Tmp;
7075 Tmp = LHS_i;
7076 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7077 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
7078
7079 Tmp = LHS_r;
7080 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7081 Result.getComplexFloatImag() = Tmp;
7082 Tmp = LHS_i;
7083 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7084 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
7085 } else {
John McCall93d91dc2010-05-07 17:22:02 +00007086 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00007087 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007088 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
7089 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00007090 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007091 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
7092 LHS.getComplexIntImag() * RHS.getComplexIntReal());
7093 }
7094 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007095 case BO_Div:
7096 if (Result.isComplexFloat()) {
7097 ComplexValue LHS = Result;
7098 APFloat &LHS_r = LHS.getComplexFloatReal();
7099 APFloat &LHS_i = LHS.getComplexFloatImag();
7100 APFloat &RHS_r = RHS.getComplexFloatReal();
7101 APFloat &RHS_i = RHS.getComplexFloatImag();
7102 APFloat &Res_r = Result.getComplexFloatReal();
7103 APFloat &Res_i = Result.getComplexFloatImag();
7104
7105 APFloat Den = RHS_r;
7106 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7107 APFloat Tmp = RHS_i;
7108 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7109 Den.add(Tmp, APFloat::rmNearestTiesToEven);
7110
7111 Res_r = LHS_r;
7112 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7113 Tmp = LHS_i;
7114 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7115 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
7116 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
7117
7118 Res_i = LHS_i;
7119 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7120 Tmp = LHS_r;
7121 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7122 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
7123 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
7124 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007125 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
7126 return Error(E, diag::note_expr_divide_by_zero);
7127
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007128 ComplexValue LHS = Result;
7129 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
7130 RHS.getComplexIntImag() * RHS.getComplexIntImag();
7131 Result.getComplexIntReal() =
7132 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
7133 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
7134 Result.getComplexIntImag() =
7135 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
7136 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
7137 }
7138 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007139 }
7140
John McCall93d91dc2010-05-07 17:22:02 +00007141 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007142}
7143
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007144bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7145 // Get the operand value into 'Result'.
7146 if (!Visit(E->getSubExpr()))
7147 return false;
7148
7149 switch (E->getOpcode()) {
7150 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007151 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007152 case UO_Extension:
7153 return true;
7154 case UO_Plus:
7155 // The result is always just the subexpr.
7156 return true;
7157 case UO_Minus:
7158 if (Result.isComplexFloat()) {
7159 Result.getComplexFloatReal().changeSign();
7160 Result.getComplexFloatImag().changeSign();
7161 }
7162 else {
7163 Result.getComplexIntReal() = -Result.getComplexIntReal();
7164 Result.getComplexIntImag() = -Result.getComplexIntImag();
7165 }
7166 return true;
7167 case UO_Not:
7168 if (Result.isComplexFloat())
7169 Result.getComplexFloatImag().changeSign();
7170 else
7171 Result.getComplexIntImag() = -Result.getComplexIntImag();
7172 return true;
7173 }
7174}
7175
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007176bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7177 if (E->getNumInits() == 2) {
7178 if (E->getType()->isComplexType()) {
7179 Result.makeComplexFloat();
7180 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
7181 return false;
7182 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
7183 return false;
7184 } else {
7185 Result.makeComplexInt();
7186 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
7187 return false;
7188 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
7189 return false;
7190 }
7191 return true;
7192 }
7193 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
7194}
7195
Anders Carlsson537969c2008-11-16 20:27:53 +00007196//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00007197// Void expression evaluation, primarily for a cast to void on the LHS of a
7198// comma operator
7199//===----------------------------------------------------------------------===//
7200
7201namespace {
7202class VoidExprEvaluator
7203 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
7204public:
7205 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
7206
Richard Smith2e312c82012-03-03 22:46:17 +00007207 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00007208
7209 bool VisitCastExpr(const CastExpr *E) {
7210 switch (E->getCastKind()) {
7211 default:
7212 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7213 case CK_ToVoid:
7214 VisitIgnoredValue(E->getSubExpr());
7215 return true;
7216 }
7217 }
7218};
7219} // end anonymous namespace
7220
7221static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
7222 assert(E->isRValue() && E->getType()->isVoidType());
7223 return VoidExprEvaluator(Info).Visit(E);
7224}
7225
7226//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00007227// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00007228//===----------------------------------------------------------------------===//
7229
Richard Smith2e312c82012-03-03 22:46:17 +00007230static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007231 // In C, function designators are not lvalues, but we evaluate them as if they
7232 // are.
7233 if (E->isGLValue() || E->getType()->isFunctionType()) {
7234 LValue LV;
7235 if (!EvaluateLValue(E, LV, Info))
7236 return false;
7237 LV.moveInto(Result);
7238 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007239 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007240 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00007241 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007242 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007243 return false;
John McCall45d55e42010-05-07 21:00:08 +00007244 } else if (E->getType()->hasPointerRepresentation()) {
7245 LValue LV;
7246 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007247 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007248 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00007249 } else if (E->getType()->isRealFloatingType()) {
7250 llvm::APFloat F(0.0);
7251 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007252 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007253 Result = APValue(F);
John McCall45d55e42010-05-07 21:00:08 +00007254 } else if (E->getType()->isAnyComplexType()) {
7255 ComplexValue C;
7256 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007257 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007258 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00007259 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00007260 MemberPtr P;
7261 if (!EvaluateMemberPointer(E, P, Info))
7262 return false;
7263 P.moveInto(Result);
7264 return true;
Richard Smithfddd3842011-12-30 21:15:51 +00007265 } else if (E->getType()->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007266 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007267 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00007268 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00007269 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007270 Result = Info.CurrentCall->Temporaries[E];
Richard Smithfddd3842011-12-30 21:15:51 +00007271 } else if (E->getType()->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007272 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007273 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00007274 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
7275 return false;
7276 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00007277 } else if (E->getType()->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007278 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007279 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00007280 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00007281 if (!EvaluateVoid(E, Info))
7282 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007283 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007284 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00007285 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007286 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007287 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00007288 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007289 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007290
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00007291 return true;
7292}
7293
Richard Smithb228a862012-02-15 02:18:13 +00007294/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
7295/// cases, the in-place evaluation is essential, since later initializers for
7296/// an object can indirectly refer to subobjects which were initialized earlier.
7297static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00007298 const Expr *E, bool AllowNonLiteralTypes) {
7299 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00007300 return false;
7301
7302 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00007303 // Evaluate arrays and record types in-place, so that later initializers can
7304 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00007305 if (E->getType()->isArrayType())
7306 return EvaluateArray(E, This, Result, Info);
7307 else if (E->getType()->isRecordType())
7308 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00007309 }
7310
7311 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00007312 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00007313}
7314
Richard Smithf57d8cb2011-12-09 22:58:01 +00007315/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
7316/// lvalue-to-rvalue cast if it is an lvalue.
7317static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00007318 if (!CheckLiteralType(Info, E))
7319 return false;
7320
Richard Smith2e312c82012-03-03 22:46:17 +00007321 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007322 return false;
7323
7324 if (E->isGLValue()) {
7325 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00007326 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00007327 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007328 return false;
7329 }
7330
Richard Smith2e312c82012-03-03 22:46:17 +00007331 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00007332 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007333}
Richard Smith11562c52011-10-28 17:51:58 +00007334
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007335static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
7336 const ASTContext &Ctx, bool &IsConst) {
7337 // Fast-path evaluations of integer literals, since we sometimes see files
7338 // containing vast quantities of these.
7339 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
7340 Result.Val = APValue(APSInt(L->getValue(),
7341 L->getType()->isUnsignedIntegerType()));
7342 IsConst = true;
7343 return true;
7344 }
7345
7346 // FIXME: Evaluating values of large array and record types can cause
7347 // performance problems. Only do so in C++11 for now.
7348 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
7349 Exp->getType()->isRecordType()) &&
7350 !Ctx.getLangOpts().CPlusPlus11) {
7351 IsConst = false;
7352 return true;
7353 }
7354 return false;
7355}
7356
7357
Richard Smith7b553f12011-10-29 00:50:52 +00007358/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00007359/// any crazy technique (that has nothing to do with language standards) that
7360/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00007361/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
7362/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00007363bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007364 bool IsConst;
7365 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
7366 return IsConst;
7367
Richard Smithf57d8cb2011-12-09 22:58:01 +00007368 EvalInfo Info(Ctx, Result);
7369 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00007370}
7371
Jay Foad39c79802011-01-12 09:06:06 +00007372bool Expr::EvaluateAsBooleanCondition(bool &Result,
7373 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00007374 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00007375 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00007376 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00007377}
7378
Richard Smith5fab0c92011-12-28 19:48:30 +00007379bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
7380 SideEffectsKind AllowSideEffects) const {
7381 if (!getType()->isIntegralOrEnumerationType())
7382 return false;
7383
Richard Smith11562c52011-10-28 17:51:58 +00007384 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00007385 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
7386 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00007387 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007388
Richard Smith11562c52011-10-28 17:51:58 +00007389 Result = ExprResult.Val.getInt();
7390 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00007391}
7392
Jay Foad39c79802011-01-12 09:06:06 +00007393bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00007394 EvalInfo Info(Ctx, Result);
7395
John McCall45d55e42010-05-07 21:00:08 +00007396 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007397 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
7398 !CheckLValueConstantExpression(Info, getExprLoc(),
7399 Ctx.getLValueReferenceType(getType()), LV))
7400 return false;
7401
Richard Smith2e312c82012-03-03 22:46:17 +00007402 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00007403 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00007404}
7405
Richard Smithd0b4dd62011-12-19 06:19:21 +00007406bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
7407 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007408 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00007409 // FIXME: Evaluating initializers for large array and record types can cause
7410 // performance problems. Only do so in C++11 for now.
7411 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007412 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00007413 return false;
7414
Richard Smithd0b4dd62011-12-19 06:19:21 +00007415 Expr::EvalStatus EStatus;
7416 EStatus.Diag = &Notes;
7417
7418 EvalInfo InitInfo(Ctx, EStatus);
7419 InitInfo.setEvaluatingDecl(VD, Value);
7420
7421 LValue LVal;
7422 LVal.set(VD);
7423
Richard Smithfddd3842011-12-30 21:15:51 +00007424 // C++11 [basic.start.init]p2:
7425 // Variables with static storage duration or thread storage duration shall be
7426 // zero-initialized before any other initialization takes place.
7427 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007428 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00007429 !VD->getType()->isReferenceType()) {
7430 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00007431 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00007432 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00007433 return false;
7434 }
7435
Richard Smith7525ff62013-05-09 07:14:00 +00007436 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
7437 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00007438 EStatus.HasSideEffects)
7439 return false;
7440
7441 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
7442 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00007443}
7444
Richard Smith7b553f12011-10-29 00:50:52 +00007445/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
7446/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00007447bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00007448 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00007449 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00007450}
Anders Carlsson59689ed2008-11-22 21:04:56 +00007451
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007452APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007453 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007454 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007455 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00007456 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00007457 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00007458 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007459 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00007460
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007461 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00007462}
John McCall864e3962010-05-07 05:32:02 +00007463
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007464void Expr::EvaluateForOverflow(const ASTContext &Ctx,
7465 SmallVectorImpl<PartialDiagnosticAt> *Diags) const {
7466 bool IsConst;
7467 EvalResult EvalResult;
7468 EvalResult.Diag = Diags;
7469 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
7470 EvalInfo Info(Ctx, EvalResult, true);
7471 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
7472 }
7473}
7474
Abramo Bagnaraf8199452010-05-14 17:07:14 +00007475 bool Expr::EvalResult::isGlobalLValue() const {
7476 assert(Val.isLValue());
7477 return IsGlobalLValue(Val.getLValueBase());
7478 }
7479
7480
John McCall864e3962010-05-07 05:32:02 +00007481/// isIntegerConstantExpr - this recursive routine will test if an expression is
7482/// an integer constant expression.
7483
7484/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
7485/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00007486
7487// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00007488// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
7489// and a (possibly null) SourceLocation indicating the location of the problem.
7490//
John McCall864e3962010-05-07 05:32:02 +00007491// Note that to reduce code duplication, this helper does no evaluation
7492// itself; the caller checks whether the expression is evaluatable, and
7493// in the rare cases where CheckICE actually cares about the evaluated
7494// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00007495
Dan Gohman28ade552010-07-26 21:25:24 +00007496namespace {
7497
Richard Smith9e575da2012-12-28 13:25:52 +00007498enum ICEKind {
7499 /// This expression is an ICE.
7500 IK_ICE,
7501 /// This expression is not an ICE, but if it isn't evaluated, it's
7502 /// a legal subexpression for an ICE. This return value is used to handle
7503 /// the comma operator in C99 mode, and non-constant subexpressions.
7504 IK_ICEIfUnevaluated,
7505 /// This expression is not an ICE, and is not a legal subexpression for one.
7506 IK_NotICE
7507};
7508
John McCall864e3962010-05-07 05:32:02 +00007509struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00007510 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00007511 SourceLocation Loc;
7512
Richard Smith9e575da2012-12-28 13:25:52 +00007513 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00007514};
7515
Dan Gohman28ade552010-07-26 21:25:24 +00007516}
7517
Richard Smith9e575da2012-12-28 13:25:52 +00007518static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
7519
7520static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00007521
7522static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
7523 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00007524 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00007525 !EVResult.Val.isInt())
7526 return ICEDiag(IK_NotICE, E->getLocStart());
7527
John McCall864e3962010-05-07 05:32:02 +00007528 return NoDiag();
7529}
7530
7531static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
7532 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00007533 if (!E->getType()->isIntegralOrEnumerationType())
7534 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007535
7536 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00007537#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00007538#define STMT(Node, Base) case Expr::Node##Class:
7539#define EXPR(Node, Base)
7540#include "clang/AST/StmtNodes.inc"
7541 case Expr::PredefinedExprClass:
7542 case Expr::FloatingLiteralClass:
7543 case Expr::ImaginaryLiteralClass:
7544 case Expr::StringLiteralClass:
7545 case Expr::ArraySubscriptExprClass:
7546 case Expr::MemberExprClass:
7547 case Expr::CompoundAssignOperatorClass:
7548 case Expr::CompoundLiteralExprClass:
7549 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00007550 case Expr::DesignatedInitExprClass:
7551 case Expr::ImplicitValueInitExprClass:
7552 case Expr::ParenListExprClass:
7553 case Expr::VAArgExprClass:
7554 case Expr::AddrLabelExprClass:
7555 case Expr::StmtExprClass:
7556 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00007557 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00007558 case Expr::CXXDynamicCastExprClass:
7559 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00007560 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00007561 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00007562 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00007563 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00007564 case Expr::CXXThisExprClass:
7565 case Expr::CXXThrowExprClass:
7566 case Expr::CXXNewExprClass:
7567 case Expr::CXXDeleteExprClass:
7568 case Expr::CXXPseudoDestructorExprClass:
7569 case Expr::UnresolvedLookupExprClass:
7570 case Expr::DependentScopeDeclRefExprClass:
7571 case Expr::CXXConstructExprClass:
7572 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00007573 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00007574 case Expr::CXXTemporaryObjectExprClass:
7575 case Expr::CXXUnresolvedConstructExprClass:
7576 case Expr::CXXDependentScopeMemberExprClass:
7577 case Expr::UnresolvedMemberExprClass:
7578 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00007579 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007580 case Expr::ObjCArrayLiteralClass:
7581 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00007582 case Expr::ObjCEncodeExprClass:
7583 case Expr::ObjCMessageExprClass:
7584 case Expr::ObjCSelectorExprClass:
7585 case Expr::ObjCProtocolExprClass:
7586 case Expr::ObjCIvarRefExprClass:
7587 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007588 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00007589 case Expr::ObjCIsaExprClass:
7590 case Expr::ShuffleVectorExprClass:
7591 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00007592 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00007593 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00007594 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00007595 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00007596 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00007597 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00007598 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00007599 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00007600 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00007601 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00007602 case Expr::InitListExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00007603 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00007604 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00007605
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007606 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00007607 case Expr::GNUNullExprClass:
7608 // GCC considers the GNU __null value to be an integral constant expression.
7609 return NoDiag();
7610
John McCall7c454bb2011-07-15 05:09:51 +00007611 case Expr::SubstNonTypeTemplateParmExprClass:
7612 return
7613 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
7614
John McCall864e3962010-05-07 05:32:02 +00007615 case Expr::ParenExprClass:
7616 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00007617 case Expr::GenericSelectionExprClass:
7618 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007619 case Expr::IntegerLiteralClass:
7620 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007621 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00007622 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00007623 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00007624 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00007625 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00007626 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00007627 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00007628 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007629 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00007630 return NoDiag();
7631 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00007632 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00007633 // C99 6.6/3 allows function calls within unevaluated subexpressions of
7634 // constant expressions, but they can never be ICEs because an ICE cannot
7635 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00007636 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00007637 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00007638 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007639 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007640 }
Richard Smith6365c912012-02-24 22:12:32 +00007641 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00007642 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
7643 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00007644 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00007645 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00007646 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00007647 // Parameter variables are never constants. Without this check,
7648 // getAnyInitializer() can find a default argument, which leads
7649 // to chaos.
7650 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00007651 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00007652
7653 // C++ 7.1.5.1p2
7654 // A variable of non-volatile const-qualified integral or enumeration
7655 // type initialized by an ICE can be used in ICEs.
7656 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00007657 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00007658 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00007659
Richard Smithd0b4dd62011-12-19 06:19:21 +00007660 const VarDecl *VD;
7661 // Look for a declaration of this variable that has an initializer, and
7662 // check whether it is an ICE.
7663 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
7664 return NoDiag();
7665 else
Richard Smith9e575da2012-12-28 13:25:52 +00007666 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00007667 }
7668 }
Richard Smith9e575da2012-12-28 13:25:52 +00007669 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00007670 }
John McCall864e3962010-05-07 05:32:02 +00007671 case Expr::UnaryOperatorClass: {
7672 const UnaryOperator *Exp = cast<UnaryOperator>(E);
7673 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007674 case UO_PostInc:
7675 case UO_PostDec:
7676 case UO_PreInc:
7677 case UO_PreDec:
7678 case UO_AddrOf:
7679 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00007680 // C99 6.6/3 allows increment and decrement within unevaluated
7681 // subexpressions of constant expressions, but they can never be ICEs
7682 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00007683 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00007684 case UO_Extension:
7685 case UO_LNot:
7686 case UO_Plus:
7687 case UO_Minus:
7688 case UO_Not:
7689 case UO_Real:
7690 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00007691 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007692 }
Richard Smith9e575da2012-12-28 13:25:52 +00007693
John McCall864e3962010-05-07 05:32:02 +00007694 // OffsetOf falls through here.
7695 }
7696 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00007697 // Note that per C99, offsetof must be an ICE. And AFAIK, using
7698 // EvaluateAsRValue matches the proposed gcc behavior for cases like
7699 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
7700 // compliance: we should warn earlier for offsetof expressions with
7701 // array subscripts that aren't ICEs, and if the array subscripts
7702 // are ICEs, the value of the offsetof must be an integer constant.
7703 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00007704 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00007705 case Expr::UnaryExprOrTypeTraitExprClass: {
7706 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
7707 if ((Exp->getKind() == UETT_SizeOf) &&
7708 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00007709 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007710 return NoDiag();
7711 }
7712 case Expr::BinaryOperatorClass: {
7713 const BinaryOperator *Exp = cast<BinaryOperator>(E);
7714 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007715 case BO_PtrMemD:
7716 case BO_PtrMemI:
7717 case BO_Assign:
7718 case BO_MulAssign:
7719 case BO_DivAssign:
7720 case BO_RemAssign:
7721 case BO_AddAssign:
7722 case BO_SubAssign:
7723 case BO_ShlAssign:
7724 case BO_ShrAssign:
7725 case BO_AndAssign:
7726 case BO_XorAssign:
7727 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00007728 // C99 6.6/3 allows assignments within unevaluated subexpressions of
7729 // constant expressions, but they can never be ICEs because an ICE cannot
7730 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00007731 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007732
John McCalle3027922010-08-25 11:45:40 +00007733 case BO_Mul:
7734 case BO_Div:
7735 case BO_Rem:
7736 case BO_Add:
7737 case BO_Sub:
7738 case BO_Shl:
7739 case BO_Shr:
7740 case BO_LT:
7741 case BO_GT:
7742 case BO_LE:
7743 case BO_GE:
7744 case BO_EQ:
7745 case BO_NE:
7746 case BO_And:
7747 case BO_Xor:
7748 case BO_Or:
7749 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00007750 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
7751 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00007752 if (Exp->getOpcode() == BO_Div ||
7753 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00007754 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00007755 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00007756 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00007757 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00007758 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00007759 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007760 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00007761 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00007762 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00007763 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007764 }
7765 }
7766 }
John McCalle3027922010-08-25 11:45:40 +00007767 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007768 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00007769 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
7770 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00007771 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
7772 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007773 } else {
7774 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00007775 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007776 }
7777 }
Richard Smith9e575da2012-12-28 13:25:52 +00007778 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00007779 }
John McCalle3027922010-08-25 11:45:40 +00007780 case BO_LAnd:
7781 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00007782 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
7783 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007784 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00007785 // Rare case where the RHS has a comma "side-effect"; we need
7786 // to actually check the condition to see whether the side
7787 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00007788 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00007789 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00007790 return RHSResult;
7791 return NoDiag();
7792 }
7793
Richard Smith9e575da2012-12-28 13:25:52 +00007794 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00007795 }
7796 }
7797 }
7798 case Expr::ImplicitCastExprClass:
7799 case Expr::CStyleCastExprClass:
7800 case Expr::CXXFunctionalCastExprClass:
7801 case Expr::CXXStaticCastExprClass:
7802 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00007803 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007804 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00007805 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00007806 if (isa<ExplicitCastExpr>(E)) {
7807 if (const FloatingLiteral *FL
7808 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
7809 unsigned DestWidth = Ctx.getIntWidth(E->getType());
7810 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
7811 APSInt IgnoredVal(DestWidth, !DestSigned);
7812 bool Ignored;
7813 // If the value does not fit in the destination type, the behavior is
7814 // undefined, so we are not required to treat it as a constant
7815 // expression.
7816 if (FL->getValue().convertToInteger(IgnoredVal,
7817 llvm::APFloat::rmTowardZero,
7818 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00007819 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00007820 return NoDiag();
7821 }
7822 }
Eli Friedman76d4e432011-09-29 21:49:34 +00007823 switch (cast<CastExpr>(E)->getCastKind()) {
7824 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007825 case CK_AtomicToNonAtomic:
7826 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00007827 case CK_NoOp:
7828 case CK_IntegralToBoolean:
7829 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00007830 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00007831 default:
Richard Smith9e575da2012-12-28 13:25:52 +00007832 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00007833 }
John McCall864e3962010-05-07 05:32:02 +00007834 }
John McCallc07a0c72011-02-17 10:25:35 +00007835 case Expr::BinaryConditionalOperatorClass: {
7836 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
7837 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007838 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00007839 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007840 if (FalseResult.Kind == IK_NotICE) return FalseResult;
7841 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
7842 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00007843 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00007844 return FalseResult;
7845 }
John McCall864e3962010-05-07 05:32:02 +00007846 case Expr::ConditionalOperatorClass: {
7847 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
7848 // If the condition (ignoring parens) is a __builtin_constant_p call,
7849 // then only the true side is actually considered in an integer constant
7850 // expression, and it is fully evaluated. This is an important GNU
7851 // extension. See GCC PR38377 for discussion.
7852 if (const CallExpr *CallCE
7853 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00007854 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
7855 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00007856 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007857 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007858 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007859
Richard Smithf57d8cb2011-12-09 22:58:01 +00007860 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
7861 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007862
Richard Smith9e575da2012-12-28 13:25:52 +00007863 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007864 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007865 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007866 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007867 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00007868 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007869 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00007870 return NoDiag();
7871 // Rare case where the diagnostics depend on which side is evaluated
7872 // Note that if we get here, CondResult is 0, and at least one of
7873 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00007874 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00007875 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00007876 return TrueResult;
7877 }
7878 case Expr::CXXDefaultArgExprClass:
7879 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00007880 case Expr::CXXDefaultInitExprClass:
7881 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007882 case Expr::ChooseExprClass: {
7883 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
7884 }
7885 }
7886
David Blaikiee4d798f2012-01-20 21:50:17 +00007887 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00007888}
7889
Richard Smithf57d8cb2011-12-09 22:58:01 +00007890/// Evaluate an expression as a C++11 integral constant expression.
7891static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
7892 const Expr *E,
7893 llvm::APSInt *Value,
7894 SourceLocation *Loc) {
7895 if (!E->getType()->isIntegralOrEnumerationType()) {
7896 if (Loc) *Loc = E->getExprLoc();
7897 return false;
7898 }
7899
Richard Smith66e05fe2012-01-18 05:21:49 +00007900 APValue Result;
7901 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00007902 return false;
7903
Richard Smith66e05fe2012-01-18 05:21:49 +00007904 assert(Result.isInt() && "pointer cast to int is not an ICE");
7905 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00007906 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007907}
7908
Richard Smith92b1ce02011-12-12 09:28:41 +00007909bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007910 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007911 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
7912
Richard Smith9e575da2012-12-28 13:25:52 +00007913 ICEDiag D = CheckICE(this, Ctx);
7914 if (D.Kind != IK_ICE) {
7915 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00007916 return false;
7917 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007918 return true;
7919}
7920
7921bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
7922 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007923 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007924 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
7925
7926 if (!isIntegerConstantExpr(Ctx, Loc))
7927 return false;
7928 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00007929 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00007930 return true;
7931}
Richard Smith66e05fe2012-01-18 05:21:49 +00007932
Richard Smith98a0a492012-02-14 21:38:30 +00007933bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00007934 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00007935}
7936
Richard Smith66e05fe2012-01-18 05:21:49 +00007937bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
7938 SourceLocation *Loc) const {
7939 // We support this checking in C++98 mode in order to diagnose compatibility
7940 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007941 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00007942
Richard Smith98a0a492012-02-14 21:38:30 +00007943 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00007944 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007945 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00007946 Status.Diag = &Diags;
7947 EvalInfo Info(Ctx, Status);
7948
7949 APValue Scratch;
7950 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
7951
7952 if (!Diags.empty()) {
7953 IsConstExpr = false;
7954 if (Loc) *Loc = Diags[0].first;
7955 } else if (!IsConstExpr) {
7956 // FIXME: This shouldn't happen.
7957 if (Loc) *Loc = getExprLoc();
7958 }
7959
7960 return IsConstExpr;
7961}
Richard Smith253c2a32012-01-27 01:14:48 +00007962
7963bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007964 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00007965 PartialDiagnosticAt> &Diags) {
7966 // FIXME: It would be useful to check constexpr function templates, but at the
7967 // moment the constant expression evaluator cannot cope with the non-rigorous
7968 // ASTs which we build for dependent expressions.
7969 if (FD->isDependentContext())
7970 return true;
7971
7972 Expr::EvalStatus Status;
7973 Status.Diag = &Diags;
7974
7975 EvalInfo Info(FD->getASTContext(), Status);
7976 Info.CheckingPotentialConstantExpression = true;
7977
7978 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7979 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
7980
Richard Smith7525ff62013-05-09 07:14:00 +00007981 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00007982 // is a temporary being used as the 'this' pointer.
7983 LValue This;
7984 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00007985 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00007986
Richard Smith253c2a32012-01-27 01:14:48 +00007987 ArrayRef<const Expr*> Args;
7988
7989 SourceLocation Loc = FD->getLocation();
7990
Richard Smith2e312c82012-03-03 22:46:17 +00007991 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00007992 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
7993 // Evaluate the call as a constant initializer, to allow the construction
7994 // of objects of non-literal types.
7995 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00007996 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00007997 } else
Richard Smith253c2a32012-01-27 01:14:48 +00007998 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
7999 Args, FD->getBody(), Info, Scratch);
8000
8001 return Diags.empty();
8002}