blob: ade258b96d4db673d62836392c8c5f755ab6d02d [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);
Richard Smitha23ab512013-05-23 00:30:41 +0000918static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000919
920//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000921// Misc utilities
922//===----------------------------------------------------------------------===//
923
Richard Smithd9f663b2013-04-22 15:31:51 +0000924/// Evaluate an expression to see if it had side-effects, and discard its
925/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +0000926/// \return \c true if the caller should keep evaluating.
927static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000928 APValue Scratch;
Richard Smith4e18ca52013-05-06 05:56:11 +0000929 if (!Evaluate(Scratch, Info, E)) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000930 Info.EvalStatus.HasSideEffects = true;
Richard Smith4e18ca52013-05-06 05:56:11 +0000931 return Info.keepEvaluatingAfterFailure();
932 }
933 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +0000934}
935
Richard Smith861b5b52013-05-07 23:34:45 +0000936/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
937/// return its existing value.
938static int64_t getExtValue(const APSInt &Value) {
939 return Value.isSigned() ? Value.getSExtValue()
940 : static_cast<int64_t>(Value.getZExtValue());
941}
942
Richard Smithd62306a2011-11-10 06:34:14 +0000943/// Should this call expression be treated as a string literal?
944static bool IsStringLiteralCall(const CallExpr *E) {
945 unsigned Builtin = E->isBuiltinCall();
946 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
947 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
948}
949
Richard Smithce40ad62011-11-12 22:28:03 +0000950static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +0000951 // C++11 [expr.const]p3 An address constant expression is a prvalue core
952 // constant expression of pointer type that evaluates to...
953
954 // ... a null pointer value, or a prvalue core constant expression of type
955 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +0000956 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +0000957
Richard Smithce40ad62011-11-12 22:28:03 +0000958 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
959 // ... the address of an object with static storage duration,
960 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
961 return VD->hasGlobalStorage();
962 // ... the address of a function,
963 return isa<FunctionDecl>(D);
964 }
965
966 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +0000967 switch (E->getStmtClass()) {
968 default:
969 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +0000970 case Expr::CompoundLiteralExprClass: {
971 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
972 return CLE->isFileScope() && CLE->isLValue();
973 }
Richard Smithd62306a2011-11-10 06:34:14 +0000974 // A string literal has static storage duration.
975 case Expr::StringLiteralClass:
976 case Expr::PredefinedExprClass:
977 case Expr::ObjCStringLiteralClass:
978 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +0000979 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +0000980 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +0000981 return true;
982 case Expr::CallExprClass:
983 return IsStringLiteralCall(cast<CallExpr>(E));
984 // For GCC compatibility, &&label has static storage duration.
985 case Expr::AddrLabelExprClass:
986 return true;
987 // A Block literal expression may be used as the initialization value for
988 // Block variables at global or local static scope.
989 case Expr::BlockExprClass:
990 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +0000991 case Expr::ImplicitValueInitExprClass:
992 // FIXME:
993 // We can never form an lvalue with an implicit value initialization as its
994 // base through expression evaluation, so these only appear in one case: the
995 // implicit variable declaration we invent when checking whether a constexpr
996 // constructor can produce a constant expression. We must assume that such
997 // an expression might be a global lvalue.
998 return true;
Richard Smithd62306a2011-11-10 06:34:14 +0000999 }
John McCall95007602010-05-10 23:27:23 +00001000}
1001
Richard Smithb228a862012-02-15 02:18:13 +00001002static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1003 assert(Base && "no location for a null lvalue");
1004 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1005 if (VD)
1006 Info.Note(VD->getLocation(), diag::note_declared_at);
1007 else
Ted Kremenek28831752012-08-23 20:46:57 +00001008 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001009 diag::note_constexpr_temporary_here);
1010}
1011
Richard Smith80815602011-11-07 05:07:52 +00001012/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001013/// value for an address or reference constant expression. Return true if we
1014/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001015static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1016 QualType Type, const LValue &LVal) {
1017 bool IsReferenceType = Type->isReferenceType();
1018
Richard Smith357362d2011-12-13 06:39:58 +00001019 APValue::LValueBase Base = LVal.getLValueBase();
1020 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1021
Richard Smith0dea49e2012-02-18 04:58:18 +00001022 // Check that the object is a global. Note that the fake 'this' object we
1023 // manufacture when checking potential constant expressions is conservatively
1024 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001025 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001026 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001027 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001028 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1029 << IsReferenceType << !Designator.Entries.empty()
1030 << !!VD << VD;
1031 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001032 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001033 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001034 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001035 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001036 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001037 }
Richard Smithb228a862012-02-15 02:18:13 +00001038 assert((Info.CheckingPotentialConstantExpression ||
1039 LVal.getLValueCallIndex() == 0) &&
1040 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001041
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001042 // Check if this is a thread-local variable.
1043 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1044 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
Richard Smithfd3834f2013-04-13 02:43:54 +00001045 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001046 return false;
1047 }
1048 }
1049
Richard Smitha8105bc2012-01-06 16:39:00 +00001050 // Allow address constant expressions to be past-the-end pointers. This is
1051 // an extension: the standard requires them to point to an object.
1052 if (!IsReferenceType)
1053 return true;
1054
1055 // A reference constant expression must refer to an object.
1056 if (!Base) {
1057 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001058 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001059 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001060 }
1061
Richard Smith357362d2011-12-13 06:39:58 +00001062 // Does this refer one past the end of some object?
Richard Smitha8105bc2012-01-06 16:39:00 +00001063 if (Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001064 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001065 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001066 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001067 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001068 }
1069
Richard Smith80815602011-11-07 05:07:52 +00001070 return true;
1071}
1072
Richard Smithfddd3842011-12-30 21:15:51 +00001073/// Check that this core constant expression is of literal type, and if not,
1074/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001075static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1076 const LValue *This = 0) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001077 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001078 return true;
1079
Richard Smith7525ff62013-05-09 07:14:00 +00001080 // C++1y: A constant initializer for an object o [...] may also invoke
1081 // constexpr constructors for o and its subobjects even if those objects
1082 // are of non-literal class types.
1083 if (Info.getLangOpts().CPlusPlus1y && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001084 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001085 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
David Blaikie7d170102013-05-15 07:37:26 +00001812 LLVM_EXPLICIT operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00001813};
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 Smith0838f3a2013-05-14 05:18:44 +00003164 // Bail out with no diagnostic if the function declaration itself is invalid.
3165 // We will have produced a relevant diagnostic while parsing it.
3166 if (Declaration->isInvalidDecl())
3167 return false;
3168
Richard Smith357362d2011-12-13 06:39:58 +00003169 // Can we evaluate this function call?
3170 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3171 return true;
3172
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003173 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003174 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003175 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3176 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003177 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3178 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3179 << DiagDecl;
3180 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3181 } else {
3182 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3183 }
3184 return false;
3185}
3186
Richard Smithd62306a2011-11-10 06:34:14 +00003187namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003188typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003189}
3190
3191/// EvaluateArgs - Evaluate the arguments to a function call.
3192static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3193 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003194 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003195 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003196 I != E; ++I) {
3197 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3198 // If we're checking for a potential constant expression, evaluate all
3199 // initializers even if some of them fail.
3200 if (!Info.keepEvaluatingAfterFailure())
3201 return false;
3202 Success = false;
3203 }
3204 }
3205 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003206}
3207
Richard Smith254a73d2011-10-28 22:34:42 +00003208/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003209static bool HandleFunctionCall(SourceLocation CallLoc,
3210 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003211 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00003212 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003213 ArgVector ArgValues(Args.size());
3214 if (!EvaluateArgs(Args, ArgValues, Info))
3215 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003216
Richard Smith253c2a32012-01-27 01:14:48 +00003217 if (!Info.CheckCallLimit(CallLoc))
3218 return false;
3219
3220 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003221
3222 // For a trivial copy or move assignment, perform an APValue copy. This is
3223 // essential for unions, where the operations performed by the assignment
3224 // operator cannot be represented as statements.
3225 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3226 if (MD && MD->isDefaulted() && MD->isTrivial()) {
3227 assert(This &&
3228 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3229 LValue RHS;
3230 RHS.setFrom(Info.Ctx, ArgValues[0]);
3231 APValue RHSValue;
3232 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3233 RHS, RHSValue))
3234 return false;
3235 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3236 RHSValue))
3237 return false;
3238 This->moveInto(Result);
3239 return true;
3240 }
3241
Richard Smithd9f663b2013-04-22 15:31:51 +00003242 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003243 if (ESR == ESR_Succeeded) {
3244 if (Callee->getResultType()->isVoidType())
3245 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003246 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003247 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003248 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003249}
3250
Richard Smithd62306a2011-11-10 06:34:14 +00003251/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003252static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003253 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003254 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003255 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003256 ArgVector ArgValues(Args.size());
3257 if (!EvaluateArgs(Args, ArgValues, Info))
3258 return false;
3259
Richard Smith253c2a32012-01-27 01:14:48 +00003260 if (!Info.CheckCallLimit(CallLoc))
3261 return false;
3262
Richard Smith3607ffe2012-02-13 03:54:03 +00003263 const CXXRecordDecl *RD = Definition->getParent();
3264 if (RD->getNumVBases()) {
3265 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3266 return false;
3267 }
3268
Richard Smith253c2a32012-01-27 01:14:48 +00003269 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003270
3271 // If it's a delegating constructor, just delegate.
3272 if (Definition->isDelegatingConstructor()) {
3273 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smithd9f663b2013-04-22 15:31:51 +00003274 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3275 return false;
3276 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003277 }
3278
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003279 // For a trivial copy or move constructor, perform an APValue copy. This is
3280 // essential for unions, where the operations performed by the constructor
3281 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003282 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00003283 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3284 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003285 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003286 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003287 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003288 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003289 }
3290
3291 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003292 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003293 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3294 std::distance(RD->field_begin(), RD->field_end()));
3295
John McCalld7bca762012-05-01 00:38:49 +00003296 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003297 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3298
Richard Smith253c2a32012-01-27 01:14:48 +00003299 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003300 unsigned BasesSeen = 0;
3301#ifndef NDEBUG
3302 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3303#endif
3304 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
3305 E = Definition->init_end(); I != E; ++I) {
Richard Smith253c2a32012-01-27 01:14:48 +00003306 LValue Subobject = This;
3307 APValue *Value = &Result;
3308
3309 // Determine the subobject to initialize.
Richard Smithd62306a2011-11-10 06:34:14 +00003310 if ((*I)->isBaseInitializer()) {
3311 QualType BaseType((*I)->getBaseClass(), 0);
3312#ifndef NDEBUG
3313 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003314 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003315 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3316 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3317 "base class initializers not in expected order");
3318 ++BaseIt;
3319#endif
John McCalld7bca762012-05-01 00:38:49 +00003320 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
3321 BaseType->getAsCXXRecordDecl(), &Layout))
3322 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003323 Value = &Result.getStructBase(BasesSeen++);
Richard Smithd62306a2011-11-10 06:34:14 +00003324 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCalld7bca762012-05-01 00:38:49 +00003325 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
3326 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003327 if (RD->isUnion()) {
3328 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003329 Value = &Result.getUnionValue();
3330 } else {
3331 Value = &Result.getStructField(FD->getFieldIndex());
3332 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00003333 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003334 // Walk the indirect field decl's chain to find the object to initialize,
3335 // and make sure we've initialized every step along it.
3336 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
3337 CE = IFD->chain_end();
3338 C != CE; ++C) {
3339 FieldDecl *FD = cast<FieldDecl>(*C);
3340 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3341 // Switch the union field if it differs. This happens if we had
3342 // preceding zero-initialization, and we're now initializing a union
3343 // subobject other than the first.
3344 // FIXME: In this case, the values of the other subobjects are
3345 // specified, since zero-initialization sets all padding bits to zero.
3346 if (Value->isUninit() ||
3347 (Value->isUnion() && Value->getUnionField() != FD)) {
3348 if (CD->isUnion())
3349 *Value = APValue(FD);
3350 else
3351 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
3352 std::distance(CD->field_begin(), CD->field_end()));
3353 }
John McCalld7bca762012-05-01 00:38:49 +00003354 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
3355 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003356 if (CD->isUnion())
3357 Value = &Value->getUnionValue();
3358 else
3359 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00003360 }
Richard Smithd62306a2011-11-10 06:34:14 +00003361 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003362 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00003363 }
Richard Smith253c2a32012-01-27 01:14:48 +00003364
Richard Smith7525ff62013-05-09 07:14:00 +00003365 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit())) {
Richard Smith253c2a32012-01-27 01:14:48 +00003366 // If we're checking for a potential constant expression, evaluate all
3367 // initializers even if some of them fail.
3368 if (!Info.keepEvaluatingAfterFailure())
3369 return false;
3370 Success = false;
3371 }
Richard Smithd62306a2011-11-10 06:34:14 +00003372 }
3373
Richard Smithd9f663b2013-04-22 15:31:51 +00003374 return Success &&
3375 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003376}
3377
Eli Friedman9a156e52008-11-12 09:44:48 +00003378//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00003379// Generic Evaluation
3380//===----------------------------------------------------------------------===//
3381namespace {
3382
Richard Smithf57d8cb2011-12-09 22:58:01 +00003383// FIXME: RetTy is always bool. Remove it.
3384template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00003385class ExprEvaluatorBase
3386 : public ConstStmtVisitor<Derived, RetTy> {
3387private:
Richard Smith2e312c82012-03-03 22:46:17 +00003388 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003389 return static_cast<Derived*>(this)->Success(V, E);
3390 }
Richard Smithfddd3842011-12-30 21:15:51 +00003391 RetTy DerivedZeroInitialization(const Expr *E) {
3392 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003393 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003394
Richard Smith17100ba2012-02-16 02:46:34 +00003395 // Check whether a conditional operator with a non-constant condition is a
3396 // potential constant expression. If neither arm is a potential constant
3397 // expression, then the conditional operator is not either.
3398 template<typename ConditionalOperator>
3399 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
3400 assert(Info.CheckingPotentialConstantExpression);
3401
3402 // Speculatively evaluate both arms.
3403 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003404 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00003405 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3406
3407 StmtVisitorTy::Visit(E->getFalseExpr());
3408 if (Diag.empty())
3409 return;
3410
3411 Diag.clear();
3412 StmtVisitorTy::Visit(E->getTrueExpr());
3413 if (Diag.empty())
3414 return;
3415 }
3416
3417 Error(E, diag::note_constexpr_conditional_never_const);
3418 }
3419
3420
3421 template<typename ConditionalOperator>
3422 bool HandleConditionalOperator(const ConditionalOperator *E) {
3423 bool BoolResult;
3424 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
3425 if (Info.CheckingPotentialConstantExpression)
3426 CheckPotentialConstantConditional(E);
3427 return false;
3428 }
3429
3430 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3431 return StmtVisitorTy::Visit(EvalExpr);
3432 }
3433
Peter Collingbournee9200682011-05-13 03:29:01 +00003434protected:
3435 EvalInfo &Info;
3436 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
3437 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3438
Richard Smith92b1ce02011-12-12 09:28:41 +00003439 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003440 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003441 }
3442
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003443 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
3444
3445public:
3446 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3447
3448 EvalInfo &getEvalInfo() { return Info; }
3449
Richard Smithf57d8cb2011-12-09 22:58:01 +00003450 /// Report an evaluation error. This should only be called when an error is
3451 /// first discovered. When propagating an error, just return false.
3452 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003453 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003454 return false;
3455 }
3456 bool Error(const Expr *E) {
3457 return Error(E, diag::note_invalid_subexpr_in_const_expr);
3458 }
3459
Peter Collingbournee9200682011-05-13 03:29:01 +00003460 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00003461 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00003462 }
3463 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003464 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003465 }
3466
3467 RetTy VisitParenExpr(const ParenExpr *E)
3468 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3469 RetTy VisitUnaryExtension(const UnaryOperator *E)
3470 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3471 RetTy VisitUnaryPlus(const UnaryOperator *E)
3472 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3473 RetTy VisitChooseExpr(const ChooseExpr *E)
3474 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
3475 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
3476 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00003477 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
3478 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00003479 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
3480 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith852c9db2013-04-20 22:23:05 +00003481 RetTy VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
3482 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00003483 // We cannot create any objects for which cleanups are required, so there is
3484 // nothing to do here; all cleanups must come from unevaluated subexpressions.
3485 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
3486 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003487
Richard Smith6d6ecc32011-12-12 12:46:16 +00003488 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
3489 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3490 return static_cast<Derived*>(this)->VisitCastExpr(E);
3491 }
3492 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
3493 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3494 return static_cast<Derived*>(this)->VisitCastExpr(E);
3495 }
3496
Richard Smith027bf112011-11-17 22:56:20 +00003497 RetTy VisitBinaryOperator(const BinaryOperator *E) {
3498 switch (E->getOpcode()) {
3499 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003500 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003501
3502 case BO_Comma:
3503 VisitIgnoredValue(E->getLHS());
3504 return StmtVisitorTy::Visit(E->getRHS());
3505
3506 case BO_PtrMemD:
3507 case BO_PtrMemI: {
3508 LValue Obj;
3509 if (!HandleMemberPointerAccess(Info, E, Obj))
3510 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003511 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00003512 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00003513 return false;
3514 return DerivedSuccess(Result, E);
3515 }
3516 }
3517 }
3518
Peter Collingbournee9200682011-05-13 03:29:01 +00003519 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003520 // Evaluate and cache the common expression. We treat it as a temporary,
3521 // even though it's not quite the same thing.
3522 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
3523 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003524 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00003525
Richard Smith17100ba2012-02-16 02:46:34 +00003526 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003527 }
3528
3529 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003530 bool IsBcpCall = false;
3531 // If the condition (ignoring parens) is a __builtin_constant_p call,
3532 // the result is a constant expression if it can be folded without
3533 // side-effects. This is an important GNU extension. See GCC PR38377
3534 // for discussion.
3535 if (const CallExpr *CallCE =
3536 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
3537 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
3538 IsBcpCall = true;
3539
3540 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3541 // constant expression; we can't check whether it's potentially foldable.
3542 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
3543 return false;
3544
3545 FoldConstant Fold(Info);
3546
Richard Smith17100ba2012-02-16 02:46:34 +00003547 if (!HandleConditionalOperator(E))
Richard Smith84f6dcf2012-02-02 01:16:57 +00003548 return false;
3549
3550 if (IsBcpCall)
3551 Fold.Fold(Info);
3552
3553 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00003554 }
3555
3556 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003557 APValue &Value = Info.CurrentCall->Temporaries[E];
3558 if (Value.isUninit()) {
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003559 const Expr *Source = E->getSourceExpr();
3560 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003561 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003562 if (Source == E) { // sanity checking.
3563 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00003564 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003565 }
3566 return StmtVisitorTy::Visit(Source);
3567 }
Richard Smith26d4cc12012-06-26 08:12:11 +00003568 return DerivedSuccess(Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003569 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003570
Richard Smith254a73d2011-10-28 22:34:42 +00003571 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003572 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00003573 QualType CalleeType = Callee->getType();
3574
Richard Smith254a73d2011-10-28 22:34:42 +00003575 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00003576 LValue *This = 0, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003577 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00003578 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00003579
Richard Smithe97cbd72011-11-11 04:05:33 +00003580 // Extract function decl and 'this' pointer from the callee.
3581 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003582 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00003583 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3584 // Explicit bound member calls, such as x.f() or p->g();
3585 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003586 return false;
3587 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00003588 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00003589 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00003590 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
3591 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00003592 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
3593 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00003594 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00003595 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003596 return Error(Callee);
3597
3598 FD = dyn_cast<FunctionDecl>(Member);
3599 if (!FD)
3600 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003601 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003602 LValue Call;
3603 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003604 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00003605
Richard Smitha8105bc2012-01-06 16:39:00 +00003606 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003607 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00003608 FD = dyn_cast_or_null<FunctionDecl>(
3609 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00003610 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003611 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003612
3613 // Overloaded operator calls to member functions are represented as normal
3614 // calls with '*this' as the first argument.
3615 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
3616 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003617 // FIXME: When selecting an implicit conversion for an overloaded
3618 // operator delete, we sometimes try to evaluate calls to conversion
3619 // operators without a 'this' parameter!
3620 if (Args.empty())
3621 return Error(E);
3622
Richard Smithe97cbd72011-11-11 04:05:33 +00003623 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
3624 return false;
3625 This = &ThisVal;
3626 Args = Args.slice(1);
3627 }
3628
3629 // Don't call function pointers which have been cast to some other type.
3630 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003631 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00003632 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003633 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00003634
Richard Smith47b34932012-02-01 02:39:43 +00003635 if (This && !This->checkSubobject(Info, E, CSK_This))
3636 return false;
3637
Richard Smith3607ffe2012-02-13 03:54:03 +00003638 // DR1358 allows virtual constexpr functions in some cases. Don't allow
3639 // calls to such functions in constant expressions.
3640 if (This && !HasQualifier &&
3641 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
3642 return Error(E, diag::note_constexpr_virtual_call);
3643
Richard Smith357362d2011-12-13 06:39:58 +00003644 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00003645 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00003646 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00003647
Richard Smith357362d2011-12-13 06:39:58 +00003648 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00003649 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
3650 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003651 return false;
3652
Richard Smithb228a862012-02-15 02:18:13 +00003653 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00003654 }
3655
Richard Smith11562c52011-10-28 17:51:58 +00003656 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
3657 return StmtVisitorTy::Visit(E->getInitializer());
3658 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003659 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00003660 if (E->getNumInits() == 0)
3661 return DerivedZeroInitialization(E);
3662 if (E->getNumInits() == 1)
3663 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00003664 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003665 }
3666 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003667 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003668 }
3669 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003670 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003671 }
Richard Smith027bf112011-11-17 22:56:20 +00003672 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003673 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00003674 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003675
Richard Smithd62306a2011-11-10 06:34:14 +00003676 /// A member expression where the object is a prvalue is itself a prvalue.
3677 RetTy VisitMemberExpr(const MemberExpr *E) {
3678 assert(!E->isArrow() && "missing call to bound member function?");
3679
Richard Smith2e312c82012-03-03 22:46:17 +00003680 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00003681 if (!Evaluate(Val, Info, E->getBase()))
3682 return false;
3683
3684 QualType BaseTy = E->getBase()->getType();
3685
3686 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003687 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003688 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00003689 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00003690 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3691
Richard Smith3229b742013-05-05 21:17:10 +00003692 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00003693 SubobjectDesignator Designator(BaseTy);
3694 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00003695
Richard Smith3229b742013-05-05 21:17:10 +00003696 APValue Result;
3697 return extractSubobject(Info, E, Obj, Designator, Result) &&
3698 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00003699 }
3700
Richard Smith11562c52011-10-28 17:51:58 +00003701 RetTy VisitCastExpr(const CastExpr *E) {
3702 switch (E->getCastKind()) {
3703 default:
3704 break;
3705
Richard Smitha23ab512013-05-23 00:30:41 +00003706 case CK_AtomicToNonAtomic: {
3707 APValue AtomicVal;
3708 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
3709 return false;
3710 return DerivedSuccess(AtomicVal, E);
3711 }
3712
Richard Smith11562c52011-10-28 17:51:58 +00003713 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00003714 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00003715 return StmtVisitorTy::Visit(E->getSubExpr());
3716
3717 case CK_LValueToRValue: {
3718 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003719 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
3720 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003721 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00003722 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00003723 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00003724 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003725 return false;
3726 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00003727 }
3728 }
3729
Richard Smithf57d8cb2011-12-09 22:58:01 +00003730 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003731 }
3732
Richard Smith243ef902013-05-05 23:31:59 +00003733 RetTy VisitUnaryPostInc(const UnaryOperator *UO) {
3734 return VisitUnaryPostIncDec(UO);
3735 }
3736 RetTy VisitUnaryPostDec(const UnaryOperator *UO) {
3737 return VisitUnaryPostIncDec(UO);
3738 }
3739 RetTy VisitUnaryPostIncDec(const UnaryOperator *UO) {
3740 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
3741 return Error(UO);
3742
3743 LValue LVal;
3744 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
3745 return false;
3746 APValue RVal;
3747 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
3748 UO->isIncrementOp(), &RVal))
3749 return false;
3750 return DerivedSuccess(RVal, UO);
3751 }
3752
Richard Smith4a678122011-10-24 18:44:57 +00003753 /// Visit a value which is evaluated, but whose value is ignored.
3754 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003755 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00003756 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003757};
3758
3759}
3760
3761//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003762// Common base class for lvalue and temporary evaluation.
3763//===----------------------------------------------------------------------===//
3764namespace {
3765template<class Derived>
3766class LValueExprEvaluatorBase
3767 : public ExprEvaluatorBase<Derived, bool> {
3768protected:
3769 LValue &Result;
3770 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
3771 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
3772
3773 bool Success(APValue::LValueBase B) {
3774 Result.set(B);
3775 return true;
3776 }
3777
3778public:
3779 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
3780 ExprEvaluatorBaseTy(Info), Result(Result) {}
3781
Richard Smith2e312c82012-03-03 22:46:17 +00003782 bool Success(const APValue &V, const Expr *E) {
3783 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00003784 return true;
3785 }
Richard Smith027bf112011-11-17 22:56:20 +00003786
Richard Smith027bf112011-11-17 22:56:20 +00003787 bool VisitMemberExpr(const MemberExpr *E) {
3788 // Handle non-static data members.
3789 QualType BaseTy;
3790 if (E->isArrow()) {
3791 if (!EvaluatePointer(E->getBase(), Result, this->Info))
3792 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00003793 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00003794 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00003795 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00003796 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
3797 return false;
3798 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003799 } else {
3800 if (!this->Visit(E->getBase()))
3801 return false;
3802 BaseTy = E->getBase()->getType();
3803 }
Richard Smith027bf112011-11-17 22:56:20 +00003804
Richard Smith1b78b3d2012-01-25 22:15:11 +00003805 const ValueDecl *MD = E->getMemberDecl();
3806 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
3807 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
3808 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3809 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00003810 if (!HandleLValueMember(this->Info, E, Result, FD))
3811 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003812 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00003813 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
3814 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003815 } else
3816 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003817
Richard Smith1b78b3d2012-01-25 22:15:11 +00003818 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00003819 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00003820 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00003821 RefValue))
3822 return false;
3823 return Success(RefValue, E);
3824 }
3825 return true;
3826 }
3827
3828 bool VisitBinaryOperator(const BinaryOperator *E) {
3829 switch (E->getOpcode()) {
3830 default:
3831 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
3832
3833 case BO_PtrMemD:
3834 case BO_PtrMemI:
3835 return HandleMemberPointerAccess(this->Info, E, Result);
3836 }
3837 }
3838
3839 bool VisitCastExpr(const CastExpr *E) {
3840 switch (E->getCastKind()) {
3841 default:
3842 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3843
3844 case CK_DerivedToBase:
3845 case CK_UncheckedDerivedToBase: {
3846 if (!this->Visit(E->getSubExpr()))
3847 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003848
3849 // Now figure out the necessary offset to add to the base LV to get from
3850 // the derived class to the base class.
3851 QualType Type = E->getSubExpr()->getType();
3852
3853 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3854 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003855 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smith027bf112011-11-17 22:56:20 +00003856 *PathI))
3857 return false;
3858 Type = (*PathI)->getType();
3859 }
3860
3861 return true;
3862 }
3863 }
3864 }
3865};
3866}
3867
3868//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00003869// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003870//
3871// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
3872// function designators (in C), decl references to void objects (in C), and
3873// temporaries (if building with -Wno-address-of-temporary).
3874//
3875// LValue evaluation produces values comprising a base expression of one of the
3876// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00003877// - Declarations
3878// * VarDecl
3879// * FunctionDecl
3880// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00003881// * CompoundLiteralExpr in C
3882// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00003883// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00003884// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00003885// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00003886// * ObjCEncodeExpr
3887// * AddrLabelExpr
3888// * BlockExpr
3889// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00003890// - Locals and temporaries
Richard Smithb228a862012-02-15 02:18:13 +00003891// * Any Expr, with a CallIndex indicating the function in which the temporary
3892// was evaluated.
Richard Smithce40ad62011-11-12 22:28:03 +00003893// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00003894//===----------------------------------------------------------------------===//
3895namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003896class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00003897 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00003898public:
Richard Smith027bf112011-11-17 22:56:20 +00003899 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
3900 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00003901
Richard Smith11562c52011-10-28 17:51:58 +00003902 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00003903 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00003904
Peter Collingbournee9200682011-05-13 03:29:01 +00003905 bool VisitDeclRefExpr(const DeclRefExpr *E);
3906 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003907 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003908 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
3909 bool VisitMemberExpr(const MemberExpr *E);
3910 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
3911 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00003912 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00003913 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003914 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
3915 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00003916 bool VisitUnaryReal(const UnaryOperator *E);
3917 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00003918 bool VisitUnaryPreInc(const UnaryOperator *UO) {
3919 return VisitUnaryPreIncDec(UO);
3920 }
3921 bool VisitUnaryPreDec(const UnaryOperator *UO) {
3922 return VisitUnaryPreIncDec(UO);
3923 }
Richard Smith3229b742013-05-05 21:17:10 +00003924 bool VisitBinAssign(const BinaryOperator *BO);
3925 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00003926
Peter Collingbournee9200682011-05-13 03:29:01 +00003927 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00003928 switch (E->getCastKind()) {
3929 default:
Richard Smith027bf112011-11-17 22:56:20 +00003930 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00003931
Eli Friedmance3e02a2011-10-11 00:13:24 +00003932 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00003933 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00003934 if (!Visit(E->getSubExpr()))
3935 return false;
3936 Result.Designator.setInvalid();
3937 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00003938
Richard Smith027bf112011-11-17 22:56:20 +00003939 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00003940 if (!Visit(E->getSubExpr()))
3941 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003942 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00003943 }
3944 }
Eli Friedman9a156e52008-11-12 09:44:48 +00003945};
3946} // end anonymous namespace
3947
Richard Smith11562c52011-10-28 17:51:58 +00003948/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smith9f8400e2013-05-01 19:00:39 +00003949/// expressions which are not glvalues, in two cases:
3950/// * function designators in C, and
3951/// * "extern void" objects
3952static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
3953 assert(E->isGLValue() || E->getType()->isFunctionType() ||
3954 E->getType()->isVoidType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003955 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003956}
3957
Peter Collingbournee9200682011-05-13 03:29:01 +00003958bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00003959 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
3960 return Success(FD);
3961 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00003962 return VisitVarDecl(E, VD);
3963 return Error(E);
3964}
Richard Smith733237d2011-10-24 23:14:33 +00003965
Richard Smith11562c52011-10-28 17:51:58 +00003966bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith3229b742013-05-05 21:17:10 +00003967 CallStackFrame *Frame = 0;
3968 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
3969 Frame = Info.CurrentCall;
3970
Richard Smithfec09922011-11-01 16:57:24 +00003971 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00003972 if (Frame) {
3973 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00003974 return true;
3975 }
Richard Smithce40ad62011-11-12 22:28:03 +00003976 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00003977 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00003978
Richard Smith3229b742013-05-05 21:17:10 +00003979 APValue *V;
3980 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003981 return false;
Richard Smith3229b742013-05-05 21:17:10 +00003982 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00003983}
3984
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003985bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
3986 const MaterializeTemporaryExpr *E) {
Jordan Roseb1312a52013-04-11 00:58:58 +00003987 if (E->getType()->isRecordType())
3988 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
Richard Smith027bf112011-11-17 22:56:20 +00003989
Richard Smithb228a862012-02-15 02:18:13 +00003990 Result.set(E, Info.CurrentCall->Index);
Jordan Roseb1312a52013-04-11 00:58:58 +00003991 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
3992 Result, E->GetTemporaryExpr());
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003993}
3994
Peter Collingbournee9200682011-05-13 03:29:01 +00003995bool
3996LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003997 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
3998 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
3999 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004000 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004001}
4002
Richard Smith6e525142011-12-27 12:18:28 +00004003bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004004 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004005 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004006
4007 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4008 << E->getExprOperand()->getType()
4009 << E->getExprOperand()->getSourceRange();
4010 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004011}
4012
Francois Pichet0066db92012-04-16 04:08:35 +00004013bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4014 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004015}
Francois Pichet0066db92012-04-16 04:08:35 +00004016
Peter Collingbournee9200682011-05-13 03:29:01 +00004017bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004018 // Handle static data members.
4019 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4020 VisitIgnoredValue(E->getBase());
4021 return VisitVarDecl(E, VD);
4022 }
4023
Richard Smith254a73d2011-10-28 22:34:42 +00004024 // Handle static member functions.
4025 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4026 if (MD->isStatic()) {
4027 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004028 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004029 }
4030 }
4031
Richard Smithd62306a2011-11-10 06:34:14 +00004032 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004033 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004034}
4035
Peter Collingbournee9200682011-05-13 03:29:01 +00004036bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004037 // FIXME: Deal with vectors as array subscript bases.
4038 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004039 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004040
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004041 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004042 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004043
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004044 APSInt Index;
4045 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004046 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004047
Richard Smith861b5b52013-05-07 23:34:45 +00004048 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4049 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004050}
Eli Friedman9a156e52008-11-12 09:44:48 +00004051
Peter Collingbournee9200682011-05-13 03:29:01 +00004052bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004053 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004054}
4055
Richard Smith66c96992012-02-18 22:04:06 +00004056bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4057 if (!Visit(E->getSubExpr()))
4058 return false;
4059 // __real is a no-op on scalar lvalues.
4060 if (E->getSubExpr()->getType()->isAnyComplexType())
4061 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4062 return true;
4063}
4064
4065bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4066 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4067 "lvalue __imag__ on scalar?");
4068 if (!Visit(E->getSubExpr()))
4069 return false;
4070 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4071 return true;
4072}
4073
Richard Smith243ef902013-05-05 23:31:59 +00004074bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4075 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004076 return Error(UO);
4077
4078 if (!this->Visit(UO->getSubExpr()))
4079 return false;
4080
Richard Smith243ef902013-05-05 23:31:59 +00004081 return handleIncDec(
4082 this->Info, UO, Result, UO->getSubExpr()->getType(),
4083 UO->isIncrementOp(), 0);
Richard Smith3229b742013-05-05 21:17:10 +00004084}
4085
4086bool LValueExprEvaluator::VisitCompoundAssignOperator(
4087 const CompoundAssignOperator *CAO) {
Richard Smith243ef902013-05-05 23:31:59 +00004088 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004089 return Error(CAO);
4090
Richard Smith3229b742013-05-05 21:17:10 +00004091 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004092
4093 // The overall lvalue result is the result of evaluating the LHS.
4094 if (!this->Visit(CAO->getLHS())) {
4095 if (Info.keepEvaluatingAfterFailure())
4096 Evaluate(RHS, this->Info, CAO->getRHS());
4097 return false;
4098 }
4099
Richard Smith3229b742013-05-05 21:17:10 +00004100 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4101 return false;
4102
Richard Smith43e77732013-05-07 04:50:00 +00004103 return handleCompoundAssignment(
4104 this->Info, CAO,
4105 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4106 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004107}
4108
4109bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Richard Smith243ef902013-05-05 23:31:59 +00004110 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4111 return Error(E);
4112
Richard Smith3229b742013-05-05 21:17:10 +00004113 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004114
4115 if (!this->Visit(E->getLHS())) {
4116 if (Info.keepEvaluatingAfterFailure())
4117 Evaluate(NewVal, this->Info, E->getRHS());
4118 return false;
4119 }
4120
Richard Smith3229b742013-05-05 21:17:10 +00004121 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4122 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004123
4124 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004125 NewVal);
4126}
4127
Eli Friedman9a156e52008-11-12 09:44:48 +00004128//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004129// Pointer Evaluation
4130//===----------------------------------------------------------------------===//
4131
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004132namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004133class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004134 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00004135 LValue &Result;
4136
Peter Collingbournee9200682011-05-13 03:29:01 +00004137 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004138 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004139 return true;
4140 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004141public:
Mike Stump11289f42009-09-09 15:08:12 +00004142
John McCall45d55e42010-05-07 21:00:08 +00004143 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004144 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004145
Richard Smith2e312c82012-03-03 22:46:17 +00004146 bool Success(const APValue &V, const Expr *E) {
4147 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004148 return true;
4149 }
Richard Smithfddd3842011-12-30 21:15:51 +00004150 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00004151 return Success((Expr*)0);
4152 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004153
John McCall45d55e42010-05-07 21:00:08 +00004154 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004155 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004156 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004157 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004158 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004159 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00004160 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004161 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004162 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004163 bool VisitCallExpr(const CallExpr *E);
4164 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004165 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004166 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004167 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004168 }
Richard Smithd62306a2011-11-10 06:34:14 +00004169 bool VisitCXXThisExpr(const CXXThisExpr *E) {
4170 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004171 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004172 Result = *Info.CurrentCall->This;
4173 return true;
4174 }
John McCallc07a0c72011-02-17 10:25:35 +00004175
Eli Friedman449fe542009-03-23 04:56:01 +00004176 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004177};
Chris Lattner05706e882008-07-11 18:11:29 +00004178} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004179
John McCall45d55e42010-05-07 21:00:08 +00004180static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004181 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004182 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004183}
4184
John McCall45d55e42010-05-07 21:00:08 +00004185bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004186 if (E->getOpcode() != BO_Add &&
4187 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004188 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004189
Chris Lattner05706e882008-07-11 18:11:29 +00004190 const Expr *PExp = E->getLHS();
4191 const Expr *IExp = E->getRHS();
4192 if (IExp->getType()->isPointerType())
4193 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004194
Richard Smith253c2a32012-01-27 01:14:48 +00004195 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4196 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004197 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004198
John McCall45d55e42010-05-07 21:00:08 +00004199 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004200 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004201 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004202
4203 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004204 if (E->getOpcode() == BO_Sub)
4205 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004206
Ted Kremenek28831752012-08-23 20:46:57 +00004207 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004208 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4209 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004210}
Eli Friedman9a156e52008-11-12 09:44:48 +00004211
John McCall45d55e42010-05-07 21:00:08 +00004212bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4213 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004214}
Mike Stump11289f42009-09-09 15:08:12 +00004215
Peter Collingbournee9200682011-05-13 03:29:01 +00004216bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4217 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004218
Eli Friedman847a2bc2009-12-27 05:43:15 +00004219 switch (E->getCastKind()) {
4220 default:
4221 break;
4222
John McCalle3027922010-08-25 11:45:40 +00004223 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004224 case CK_CPointerToObjCPointerCast:
4225 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004226 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004227 if (!Visit(SubExpr))
4228 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004229 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4230 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4231 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004232 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004233 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004234 if (SubExpr->getType()->isVoidPointerType())
4235 CCEDiag(E, diag::note_constexpr_invalid_cast)
4236 << 3 << SubExpr->getType();
4237 else
4238 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4239 }
Richard Smith96e0c102011-11-04 02:25:55 +00004240 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004241
Anders Carlsson18275092010-10-31 20:41:46 +00004242 case CK_DerivedToBase:
4243 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004244 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004245 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004246 if (!Result.Base && Result.Offset.isZero())
4247 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00004248
Richard Smithd62306a2011-11-10 06:34:14 +00004249 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00004250 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00004251 QualType Type =
4252 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00004253
Richard Smithd62306a2011-11-10 06:34:14 +00004254 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00004255 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004256 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
4257 *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00004258 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004259 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00004260 }
4261
Anders Carlsson18275092010-10-31 20:41:46 +00004262 return true;
4263 }
4264
Richard Smith027bf112011-11-17 22:56:20 +00004265 case CK_BaseToDerived:
4266 if (!Visit(E->getSubExpr()))
4267 return false;
4268 if (!Result.Base && Result.Offset.isZero())
4269 return true;
4270 return HandleBaseToDerivedCast(Info, E, Result);
4271
Richard Smith0b0a0b62011-10-29 20:57:55 +00004272 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004273 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004274 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00004275
John McCalle3027922010-08-25 11:45:40 +00004276 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004277 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4278
Richard Smith2e312c82012-03-03 22:46:17 +00004279 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00004280 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00004281 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00004282
John McCall45d55e42010-05-07 21:00:08 +00004283 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004284 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4285 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00004286 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004287 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00004288 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00004289 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004290 return true;
4291 } else {
4292 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00004293 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00004294 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00004295 }
4296 }
John McCalle3027922010-08-25 11:45:40 +00004297 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00004298 if (SubExpr->isGLValue()) {
4299 if (!EvaluateLValue(SubExpr, Result, Info))
4300 return false;
4301 } else {
Richard Smithb228a862012-02-15 02:18:13 +00004302 Result.set(SubExpr, Info.CurrentCall->Index);
4303 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
4304 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00004305 return false;
4306 }
Richard Smith96e0c102011-11-04 02:25:55 +00004307 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00004308 if (const ConstantArrayType *CAT
4309 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4310 Result.addArray(Info, E, CAT);
4311 else
4312 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00004313 return true;
Richard Smithdd785442011-10-31 20:57:44 +00004314
John McCalle3027922010-08-25 11:45:40 +00004315 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00004316 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004317 }
4318
Richard Smith11562c52011-10-28 17:51:58 +00004319 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00004320}
Chris Lattner05706e882008-07-11 18:11:29 +00004321
Peter Collingbournee9200682011-05-13 03:29:01 +00004322bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004323 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00004324 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00004325
Peter Collingbournee9200682011-05-13 03:29:01 +00004326 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004327}
Chris Lattner05706e882008-07-11 18:11:29 +00004328
4329//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004330// Member Pointer Evaluation
4331//===----------------------------------------------------------------------===//
4332
4333namespace {
4334class MemberPointerExprEvaluator
4335 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
4336 MemberPtr &Result;
4337
4338 bool Success(const ValueDecl *D) {
4339 Result = MemberPtr(D);
4340 return true;
4341 }
4342public:
4343
4344 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
4345 : ExprEvaluatorBaseTy(Info), Result(Result) {}
4346
Richard Smith2e312c82012-03-03 22:46:17 +00004347 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004348 Result.setFrom(V);
4349 return true;
4350 }
Richard Smithfddd3842011-12-30 21:15:51 +00004351 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004352 return Success((const ValueDecl*)0);
4353 }
4354
4355 bool VisitCastExpr(const CastExpr *E);
4356 bool VisitUnaryAddrOf(const UnaryOperator *E);
4357};
4358} // end anonymous namespace
4359
4360static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
4361 EvalInfo &Info) {
4362 assert(E->isRValue() && E->getType()->isMemberPointerType());
4363 return MemberPointerExprEvaluator(Info, Result).Visit(E);
4364}
4365
4366bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
4367 switch (E->getCastKind()) {
4368 default:
4369 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4370
4371 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004372 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004373 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004374
4375 case CK_BaseToDerivedMemberPointer: {
4376 if (!Visit(E->getSubExpr()))
4377 return false;
4378 if (E->path_empty())
4379 return true;
4380 // Base-to-derived member pointer casts store the path in derived-to-base
4381 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
4382 // the wrong end of the derived->base arc, so stagger the path by one class.
4383 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
4384 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
4385 PathI != PathE; ++PathI) {
4386 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4387 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
4388 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004389 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004390 }
4391 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
4392 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004393 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004394 return true;
4395 }
4396
4397 case CK_DerivedToBaseMemberPointer:
4398 if (!Visit(E->getSubExpr()))
4399 return false;
4400 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4401 PathE = E->path_end(); PathI != PathE; ++PathI) {
4402 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4403 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4404 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004405 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004406 }
4407 return true;
4408 }
4409}
4410
4411bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4412 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
4413 // member can be formed.
4414 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
4415}
4416
4417//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00004418// Record Evaluation
4419//===----------------------------------------------------------------------===//
4420
4421namespace {
4422 class RecordExprEvaluator
4423 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
4424 const LValue &This;
4425 APValue &Result;
4426 public:
4427
4428 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
4429 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
4430
Richard Smith2e312c82012-03-03 22:46:17 +00004431 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004432 Result = V;
4433 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00004434 }
Richard Smithfddd3842011-12-30 21:15:51 +00004435 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004436
Richard Smithe97cbd72011-11-11 04:05:33 +00004437 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004438 bool VisitInitListExpr(const InitListExpr *E);
4439 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
4440 };
4441}
4442
Richard Smithfddd3842011-12-30 21:15:51 +00004443/// Perform zero-initialization on an object of non-union class type.
4444/// C++11 [dcl.init]p5:
4445/// To zero-initialize an object or reference of type T means:
4446/// [...]
4447/// -- if T is a (possibly cv-qualified) non-union class type,
4448/// each non-static data member and each base-class subobject is
4449/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00004450static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
4451 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00004452 const LValue &This, APValue &Result) {
4453 assert(!RD->isUnion() && "Expected non-union class type");
4454 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
4455 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
4456 std::distance(RD->field_begin(), RD->field_end()));
4457
John McCalld7bca762012-05-01 00:38:49 +00004458 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004459 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4460
4461 if (CD) {
4462 unsigned Index = 0;
4463 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00004464 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00004465 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4466 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004467 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4468 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004469 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00004470 Result.getStructBase(Index)))
4471 return false;
4472 }
4473 }
4474
Richard Smitha8105bc2012-01-06 16:39:00 +00004475 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
4476 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00004477 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004478 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00004479 continue;
4480
4481 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004482 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004483 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004484
David Blaikie2d7c57e2012-04-30 02:36:29 +00004485 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004486 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00004487 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004488 return false;
4489 }
4490
4491 return true;
4492}
4493
4494bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
4495 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004496 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004497 if (RD->isUnion()) {
4498 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4499 // object's first non-static named data member is zero-initialized
4500 RecordDecl::field_iterator I = RD->field_begin();
4501 if (I == RD->field_end()) {
4502 Result = APValue((const FieldDecl*)0);
4503 return true;
4504 }
4505
4506 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004507 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00004508 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00004509 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00004510 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004511 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004512 }
4513
Richard Smith5d108602012-02-17 00:44:16 +00004514 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004515 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00004516 return false;
4517 }
4518
Richard Smitha8105bc2012-01-06 16:39:00 +00004519 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00004520}
4521
Richard Smithe97cbd72011-11-11 04:05:33 +00004522bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
4523 switch (E->getCastKind()) {
4524 default:
4525 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4526
4527 case CK_ConstructorConversion:
4528 return Visit(E->getSubExpr());
4529
4530 case CK_DerivedToBase:
4531 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00004532 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004533 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00004534 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004535 if (!DerivedObject.isStruct())
4536 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00004537
4538 // Derived-to-base rvalue conversion: just slice off the derived part.
4539 APValue *Value = &DerivedObject;
4540 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
4541 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4542 PathE = E->path_end(); PathI != PathE; ++PathI) {
4543 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
4544 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4545 Value = &Value->getStructBase(getBaseIndex(RD, Base));
4546 RD = Base;
4547 }
4548 Result = *Value;
4549 return true;
4550 }
4551 }
4552}
4553
Richard Smithd62306a2011-11-10 06:34:14 +00004554bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redle6c32e62012-02-19 14:53:49 +00004555 // Cannot constant-evaluate std::initializer_list inits.
4556 if (E->initializesStdInitializerList())
4557 return false;
4558
Richard Smithd62306a2011-11-10 06:34:14 +00004559 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004560 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004561 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4562
4563 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00004564 const FieldDecl *Field = E->getInitializedFieldInUnion();
4565 Result = APValue(Field);
4566 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00004567 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00004568
4569 // If the initializer list for a union does not contain any elements, the
4570 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00004571 // FIXME: The element should be initialized from an initializer list.
4572 // Is this difference ever observable for initializer lists which
4573 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00004574 ImplicitValueInitExpr VIE(Field->getType());
4575 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
4576
Richard Smithd62306a2011-11-10 06:34:14 +00004577 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004578 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
4579 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00004580
4581 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4582 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4583 isa<CXXDefaultInitExpr>(InitExpr));
4584
Richard Smithb228a862012-02-15 02:18:13 +00004585 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00004586 }
4587
4588 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
4589 "initializer list for class with base classes");
4590 Result = APValue(APValue::UninitStruct(), 0,
4591 std::distance(RD->field_begin(), RD->field_end()));
4592 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00004593 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004594 for (RecordDecl::field_iterator Field = RD->field_begin(),
4595 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
4596 // Anonymous bit-fields are not considered members of the class for
4597 // purposes of aggregate initialization.
4598 if (Field->isUnnamedBitfield())
4599 continue;
4600
4601 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00004602
Richard Smith253c2a32012-01-27 01:14:48 +00004603 bool HaveInit = ElementNo < E->getNumInits();
4604
4605 // FIXME: Diagnostics here should point to the end of the initializer
4606 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00004607 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie40ed2972012-06-06 20:45:41 +00004608 Subobject, *Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004609 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004610
4611 // Perform an implicit value-initialization for members beyond the end of
4612 // the initializer list.
4613 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00004614 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00004615
Richard Smith852c9db2013-04-20 22:23:05 +00004616 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4617 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4618 isa<CXXDefaultInitExpr>(Init));
4619
4620 if (!EvaluateInPlace(Result.getStructField(Field->getFieldIndex()), Info,
4621 Subobject, Init)) {
Richard Smith253c2a32012-01-27 01:14:48 +00004622 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00004623 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004624 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00004625 }
4626 }
4627
Richard Smith253c2a32012-01-27 01:14:48 +00004628 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004629}
4630
4631bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
4632 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00004633 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
4634
Richard Smithfddd3842011-12-30 21:15:51 +00004635 bool ZeroInit = E->requiresZeroInitialization();
4636 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00004637 // If we've already performed zero-initialization, we're already done.
4638 if (!Result.isUninit())
4639 return true;
4640
Richard Smithfddd3842011-12-30 21:15:51 +00004641 if (ZeroInit)
4642 return ZeroInitialization(E);
4643
Richard Smithcc36f692011-12-22 02:22:31 +00004644 const CXXRecordDecl *RD = FD->getParent();
4645 if (RD->isUnion())
4646 Result = APValue((FieldDecl*)0);
4647 else
4648 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4649 std::distance(RD->field_begin(), RD->field_end()));
4650 return true;
4651 }
4652
Richard Smithd62306a2011-11-10 06:34:14 +00004653 const FunctionDecl *Definition = 0;
4654 FD->getBody(Definition);
4655
Richard Smith357362d2011-12-13 06:39:58 +00004656 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
4657 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004658
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004659 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00004660 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00004661 if (const MaterializeTemporaryExpr *ME
4662 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
4663 return Visit(ME->GetTemporaryExpr());
4664
Richard Smithfddd3842011-12-30 21:15:51 +00004665 if (ZeroInit && !ZeroInitialization(E))
4666 return false;
4667
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004668 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00004669 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004670 cast<CXXConstructorDecl>(Definition), Info,
4671 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00004672}
4673
4674static bool EvaluateRecord(const Expr *E, const LValue &This,
4675 APValue &Result, EvalInfo &Info) {
4676 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00004677 "can't evaluate expression as a record rvalue");
4678 return RecordExprEvaluator(Info, This, Result).Visit(E);
4679}
4680
4681//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004682// Temporary Evaluation
4683//
4684// Temporaries are represented in the AST as rvalues, but generally behave like
4685// lvalues. The full-object of which the temporary is a subobject is implicitly
4686// materialized so that a reference can bind to it.
4687//===----------------------------------------------------------------------===//
4688namespace {
4689class TemporaryExprEvaluator
4690 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
4691public:
4692 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
4693 LValueExprEvaluatorBaseTy(Info, Result) {}
4694
4695 /// Visit an expression which constructs the value of this temporary.
4696 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004697 Result.set(E, Info.CurrentCall->Index);
4698 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00004699 }
4700
4701 bool VisitCastExpr(const CastExpr *E) {
4702 switch (E->getCastKind()) {
4703 default:
4704 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
4705
4706 case CK_ConstructorConversion:
4707 return VisitConstructExpr(E->getSubExpr());
4708 }
4709 }
4710 bool VisitInitListExpr(const InitListExpr *E) {
4711 return VisitConstructExpr(E);
4712 }
4713 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
4714 return VisitConstructExpr(E);
4715 }
4716 bool VisitCallExpr(const CallExpr *E) {
4717 return VisitConstructExpr(E);
4718 }
4719};
4720} // end anonymous namespace
4721
4722/// Evaluate an expression of record type as a temporary.
4723static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004724 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00004725 return TemporaryExprEvaluator(Info, Result).Visit(E);
4726}
4727
4728//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004729// Vector Evaluation
4730//===----------------------------------------------------------------------===//
4731
4732namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004733 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00004734 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
4735 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004736 public:
Mike Stump11289f42009-09-09 15:08:12 +00004737
Richard Smith2d406342011-10-22 21:10:00 +00004738 VectorExprEvaluator(EvalInfo &info, APValue &Result)
4739 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004740
Richard Smith2d406342011-10-22 21:10:00 +00004741 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
4742 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
4743 // FIXME: remove this APValue copy.
4744 Result = APValue(V.data(), V.size());
4745 return true;
4746 }
Richard Smith2e312c82012-03-03 22:46:17 +00004747 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00004748 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00004749 Result = V;
4750 return true;
4751 }
Richard Smithfddd3842011-12-30 21:15:51 +00004752 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00004753
Richard Smith2d406342011-10-22 21:10:00 +00004754 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00004755 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00004756 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00004757 bool VisitInitListExpr(const InitListExpr *E);
4758 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004759 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00004760 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00004761 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004762 };
4763} // end anonymous namespace
4764
4765static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004766 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00004767 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004768}
4769
Richard Smith2d406342011-10-22 21:10:00 +00004770bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
4771 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00004772 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00004773
Richard Smith161f09a2011-12-06 22:44:34 +00004774 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00004775 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004776
Eli Friedmanc757de22011-03-25 00:43:55 +00004777 switch (E->getCastKind()) {
4778 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00004779 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00004780 if (SETy->isIntegerType()) {
4781 APSInt IntResult;
4782 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004783 return false;
Richard Smith2d406342011-10-22 21:10:00 +00004784 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00004785 } else if (SETy->isRealFloatingType()) {
4786 APFloat F(0.0);
4787 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004788 return false;
Richard Smith2d406342011-10-22 21:10:00 +00004789 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00004790 } else {
Richard Smith2d406342011-10-22 21:10:00 +00004791 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004792 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00004793
4794 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00004795 SmallVector<APValue, 4> Elts(NElts, Val);
4796 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00004797 }
Eli Friedman803acb32011-12-22 03:51:45 +00004798 case CK_BitCast: {
4799 // Evaluate the operand into an APInt we can extract from.
4800 llvm::APInt SValInt;
4801 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
4802 return false;
4803 // Extract the elements
4804 QualType EltTy = VTy->getElementType();
4805 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
4806 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
4807 SmallVector<APValue, 4> Elts;
4808 if (EltTy->isRealFloatingType()) {
4809 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00004810 unsigned FloatEltSize = EltSize;
4811 if (&Sem == &APFloat::x87DoubleExtended)
4812 FloatEltSize = 80;
4813 for (unsigned i = 0; i < NElts; i++) {
4814 llvm::APInt Elt;
4815 if (BigEndian)
4816 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
4817 else
4818 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00004819 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00004820 }
4821 } else if (EltTy->isIntegerType()) {
4822 for (unsigned i = 0; i < NElts; i++) {
4823 llvm::APInt Elt;
4824 if (BigEndian)
4825 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
4826 else
4827 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
4828 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
4829 }
4830 } else {
4831 return Error(E);
4832 }
4833 return Success(Elts, E);
4834 }
Eli Friedmanc757de22011-03-25 00:43:55 +00004835 default:
Richard Smith11562c52011-10-28 17:51:58 +00004836 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004837 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004838}
4839
Richard Smith2d406342011-10-22 21:10:00 +00004840bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004841VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00004842 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004843 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00004844 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00004845
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004846 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004847 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004848
Eli Friedmanb9c71292012-01-03 23:24:20 +00004849 // The number of initializers can be less than the number of
4850 // vector elements. For OpenCL, this can be due to nested vector
4851 // initialization. For GCC compatibility, missing trailing elements
4852 // should be initialized with zeroes.
4853 unsigned CountInits = 0, CountElts = 0;
4854 while (CountElts < NumElements) {
4855 // Handle nested vector initialization.
4856 if (CountInits < NumInits
4857 && E->getInit(CountInits)->getType()->isExtVectorType()) {
4858 APValue v;
4859 if (!EvaluateVector(E->getInit(CountInits), v, Info))
4860 return Error(E);
4861 unsigned vlen = v.getVectorLength();
4862 for (unsigned j = 0; j < vlen; j++)
4863 Elements.push_back(v.getVectorElt(j));
4864 CountElts += vlen;
4865 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004866 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00004867 if (CountInits < NumInits) {
4868 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00004869 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00004870 } else // trailing integer zero.
4871 sInt = Info.Ctx.MakeIntValue(0, EltTy);
4872 Elements.push_back(APValue(sInt));
4873 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004874 } else {
4875 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00004876 if (CountInits < NumInits) {
4877 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00004878 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00004879 } else // trailing float zero.
4880 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
4881 Elements.push_back(APValue(f));
4882 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00004883 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00004884 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004885 }
Richard Smith2d406342011-10-22 21:10:00 +00004886 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004887}
4888
Richard Smith2d406342011-10-22 21:10:00 +00004889bool
Richard Smithfddd3842011-12-30 21:15:51 +00004890VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00004891 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00004892 QualType EltTy = VT->getElementType();
4893 APValue ZeroElement;
4894 if (EltTy->isIntegerType())
4895 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
4896 else
4897 ZeroElement =
4898 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
4899
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004900 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00004901 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004902}
4903
Richard Smith2d406342011-10-22 21:10:00 +00004904bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00004905 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004906 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004907}
4908
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004909//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00004910// Array Evaluation
4911//===----------------------------------------------------------------------===//
4912
4913namespace {
4914 class ArrayExprEvaluator
4915 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00004916 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00004917 APValue &Result;
4918 public:
4919
Richard Smithd62306a2011-11-10 06:34:14 +00004920 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
4921 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00004922
4923 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00004924 assert((V.isArray() || V.isLValue()) &&
4925 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00004926 Result = V;
4927 return true;
4928 }
Richard Smithf3e9e432011-11-07 09:22:26 +00004929
Richard Smithfddd3842011-12-30 21:15:51 +00004930 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004931 const ConstantArrayType *CAT =
4932 Info.Ctx.getAsConstantArrayType(E->getType());
4933 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004934 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004935
4936 Result = APValue(APValue::UninitArray(), 0,
4937 CAT->getSize().getZExtValue());
4938 if (!Result.hasArrayFiller()) return true;
4939
Richard Smithfddd3842011-12-30 21:15:51 +00004940 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00004941 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00004942 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00004943 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00004944 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00004945 }
4946
Richard Smithf3e9e432011-11-07 09:22:26 +00004947 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00004948 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00004949 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
4950 const LValue &Subobject,
4951 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00004952 };
4953} // end anonymous namespace
4954
Richard Smithd62306a2011-11-10 06:34:14 +00004955static bool EvaluateArray(const Expr *E, const LValue &This,
4956 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00004957 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00004958 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00004959}
4960
4961bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
4962 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
4963 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004964 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00004965
Richard Smithca2cfbf2011-12-22 01:07:19 +00004966 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
4967 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00004968 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00004969 LValue LV;
4970 if (!EvaluateLValue(E->getInit(0), LV, Info))
4971 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004972 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00004973 LV.moveInto(Val);
4974 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00004975 }
4976
Richard Smith253c2a32012-01-27 01:14:48 +00004977 bool Success = true;
4978
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004979 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
4980 "zero-initialized array shouldn't have any initialized elts");
4981 APValue Filler;
4982 if (Result.isArray() && Result.hasArrayFiller())
4983 Filler = Result.getArrayFiller();
4984
Richard Smith9543c5e2013-04-22 14:44:29 +00004985 unsigned NumEltsToInit = E->getNumInits();
4986 unsigned NumElts = CAT->getSize().getZExtValue();
4987 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
4988
4989 // If the initializer might depend on the array index, run it for each
4990 // array element. For now, just whitelist non-class value-initialization.
4991 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
4992 NumEltsToInit = NumElts;
4993
4994 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004995
4996 // If the array was previously zero-initialized, preserve the
4997 // zero-initialized values.
4998 if (!Filler.isUninit()) {
4999 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5000 Result.getArrayInitializedElt(I) = Filler;
5001 if (Result.hasArrayFiller())
5002 Result.getArrayFiller() = Filler;
5003 }
5004
Richard Smithd62306a2011-11-10 06:34:14 +00005005 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005006 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00005007 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5008 const Expr *Init =
5009 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00005010 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00005011 Info, Subobject, Init) ||
5012 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00005013 CAT->getElementType(), 1)) {
5014 if (!Info.keepEvaluatingAfterFailure())
5015 return false;
5016 Success = false;
5017 }
Richard Smithd62306a2011-11-10 06:34:14 +00005018 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005019
Richard Smith9543c5e2013-04-22 14:44:29 +00005020 if (!Result.hasArrayFiller())
5021 return Success;
5022
5023 // If we get here, we have a trivial filler, which we can just evaluate
5024 // once and splat over the rest of the array elements.
5025 assert(FillerExpr && "no array filler for incomplete init list");
5026 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5027 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00005028}
5029
Richard Smith027bf112011-11-17 22:56:20 +00005030bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005031 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5032}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005033
Richard Smith9543c5e2013-04-22 14:44:29 +00005034bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5035 const LValue &Subobject,
5036 APValue *Value,
5037 QualType Type) {
5038 bool HadZeroInit = !Value->isUninit();
5039
5040 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5041 unsigned N = CAT->getSize().getZExtValue();
5042
5043 // Preserve the array filler if we had prior zero-initialization.
5044 APValue Filler =
5045 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5046 : APValue();
5047
5048 *Value = APValue(APValue::UninitArray(), N, N);
5049
5050 if (HadZeroInit)
5051 for (unsigned I = 0; I != N; ++I)
5052 Value->getArrayInitializedElt(I) = Filler;
5053
5054 // Initialize the elements.
5055 LValue ArrayElt = Subobject;
5056 ArrayElt.addArray(Info, E, CAT);
5057 for (unsigned I = 0; I != N; ++I)
5058 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5059 CAT->getElementType()) ||
5060 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5061 CAT->getElementType(), 1))
5062 return false;
5063
5064 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005065 }
Richard Smith027bf112011-11-17 22:56:20 +00005066
Richard Smith9543c5e2013-04-22 14:44:29 +00005067 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00005068 return Error(E);
5069
Richard Smith027bf112011-11-17 22:56:20 +00005070 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00005071
Richard Smithfddd3842011-12-30 21:15:51 +00005072 bool ZeroInit = E->requiresZeroInitialization();
5073 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005074 if (HadZeroInit)
5075 return true;
5076
Richard Smithfddd3842011-12-30 21:15:51 +00005077 if (ZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005078 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005079 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005080 }
5081
Richard Smithcc36f692011-12-22 02:22:31 +00005082 const CXXRecordDecl *RD = FD->getParent();
5083 if (RD->isUnion())
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005084 *Value = APValue((FieldDecl*)0);
Richard Smithcc36f692011-12-22 02:22:31 +00005085 else
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005086 *Value =
Richard Smithcc36f692011-12-22 02:22:31 +00005087 APValue(APValue::UninitStruct(), RD->getNumBases(),
5088 std::distance(RD->field_begin(), RD->field_end()));
5089 return true;
5090 }
5091
Richard Smith027bf112011-11-17 22:56:20 +00005092 const FunctionDecl *Definition = 0;
5093 FD->getBody(Definition);
5094
Richard Smith357362d2011-12-13 06:39:58 +00005095 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5096 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005097
Richard Smith9eae7232012-01-12 18:54:33 +00005098 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005099 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005100 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005101 return false;
5102 }
5103
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005104 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005105 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00005106 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005107 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00005108}
5109
Richard Smithf3e9e432011-11-07 09:22:26 +00005110//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005111// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005112//
5113// As a GNU extension, we support casting pointers to sufficiently-wide integer
5114// types and back in constant folding. Integer values are thus represented
5115// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00005116//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005117
5118namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005119class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00005120 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith2e312c82012-03-03 22:46:17 +00005121 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005122public:
Richard Smith2e312c82012-03-03 22:46:17 +00005123 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005124 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005125
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005126 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005127 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005128 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005129 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005130 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005131 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005132 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005133 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005134 return true;
5135 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005136 bool Success(const llvm::APSInt &SI, const Expr *E) {
5137 return Success(SI, E, Result);
5138 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005139
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005140 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005141 assert(E->getType()->isIntegralOrEnumerationType() &&
5142 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005143 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005144 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005145 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005146 Result.getInt().setIsUnsigned(
5147 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005148 return true;
5149 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005150 bool Success(const llvm::APInt &I, const Expr *E) {
5151 return Success(I, E, Result);
5152 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005153
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005154 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005155 assert(E->getType()->isIntegralOrEnumerationType() &&
5156 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005157 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005158 return true;
5159 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005160 bool Success(uint64_t Value, const Expr *E) {
5161 return Success(Value, E, Result);
5162 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005163
Ken Dyckdbc01912011-03-11 02:13:43 +00005164 bool Success(CharUnits Size, const Expr *E) {
5165 return Success(Size.getQuantity(), E);
5166 }
5167
Richard Smith2e312c82012-03-03 22:46:17 +00005168 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005169 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00005170 Result = V;
5171 return true;
5172 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005173 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00005174 }
Mike Stump11289f42009-09-09 15:08:12 +00005175
Richard Smithfddd3842011-12-30 21:15:51 +00005176 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00005177
Peter Collingbournee9200682011-05-13 03:29:01 +00005178 //===--------------------------------------------------------------------===//
5179 // Visitor Methods
5180 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005181
Chris Lattner7174bf32008-07-12 00:38:25 +00005182 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005183 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005184 }
5185 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005186 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005187 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005188
5189 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5190 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005191 if (CheckReferencedDecl(E, E->getDecl()))
5192 return true;
5193
5194 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005195 }
5196 bool VisitMemberExpr(const MemberExpr *E) {
5197 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00005198 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005199 return true;
5200 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005201
5202 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005203 }
5204
Peter Collingbournee9200682011-05-13 03:29:01 +00005205 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005206 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00005207 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005208 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00005209
Peter Collingbournee9200682011-05-13 03:29:01 +00005210 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005211 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00005212
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005213 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005214 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005215 }
Mike Stump11289f42009-09-09 15:08:12 +00005216
Ted Kremeneke65b0862012-03-06 20:05:56 +00005217 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5218 return Success(E->getValue(), E);
5219 }
5220
Richard Smith4ce706a2011-10-11 21:43:33 +00005221 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00005222 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005223 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005224 }
5225
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005226 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005227 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005228 }
5229
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005230 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
5231 return Success(E->getValue(), E);
5232 }
5233
Douglas Gregor29c42f22012-02-24 07:38:34 +00005234 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5235 return Success(E->getValue(), E);
5236 }
5237
John Wiegley6242b6a2011-04-28 00:16:57 +00005238 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5239 return Success(E->getValue(), E);
5240 }
5241
John Wiegleyf9f65842011-04-25 06:54:41 +00005242 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5243 return Success(E->getValue(), E);
5244 }
5245
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005246 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005247 bool VisitUnaryImag(const UnaryOperator *E);
5248
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005249 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005250 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00005251
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005252private:
Ken Dyck160146e2010-01-27 17:10:57 +00005253 CharUnits GetAlignOfExpr(const Expr *E);
5254 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00005255 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00005256 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005257 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00005258};
Chris Lattner05706e882008-07-11 18:11:29 +00005259} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005260
Richard Smith11562c52011-10-28 17:51:58 +00005261/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
5262/// produce either the integer value or a pointer.
5263///
5264/// GCC has a heinous extension which folds casts between pointer types and
5265/// pointer-sized integral types. We support this by allowing the evaluation of
5266/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
5267/// Some simple arithmetic on such values is supported (they are treated much
5268/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00005269static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00005270 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005271 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005272 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00005273}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005274
Richard Smithf57d8cb2011-12-09 22:58:01 +00005275static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00005276 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005277 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00005278 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005279 if (!Val.isInt()) {
5280 // FIXME: It would be better to produce the diagnostic for casting
5281 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00005282 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005283 return false;
5284 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005285 Result = Val.getInt();
5286 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005287}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005288
Richard Smithf57d8cb2011-12-09 22:58:01 +00005289/// Check whether the given declaration can be directly converted to an integral
5290/// rvalue. If not, no diagnostic is produced; there are other things we can
5291/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005292bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00005293 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005294 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005295 // Check for signedness/width mismatches between E type and ECD value.
5296 bool SameSign = (ECD->getInitVal().isSigned()
5297 == E->getType()->isSignedIntegerOrEnumerationType());
5298 bool SameWidth = (ECD->getInitVal().getBitWidth()
5299 == Info.Ctx.getIntWidth(E->getType()));
5300 if (SameSign && SameWidth)
5301 return Success(ECD->getInitVal(), E);
5302 else {
5303 // Get rid of mismatch (otherwise Success assertions will fail)
5304 // by computing a new value matching the type of E.
5305 llvm::APSInt Val = ECD->getInitVal();
5306 if (!SameSign)
5307 Val.setIsSigned(!ECD->getInitVal().isSigned());
5308 if (!SameWidth)
5309 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
5310 return Success(Val, E);
5311 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005312 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005313 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00005314}
5315
Chris Lattner86ee2862008-10-06 06:40:35 +00005316/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
5317/// as GCC.
5318static int EvaluateBuiltinClassifyType(const CallExpr *E) {
5319 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005320 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00005321 enum gcc_type_class {
5322 no_type_class = -1,
5323 void_type_class, integer_type_class, char_type_class,
5324 enumeral_type_class, boolean_type_class,
5325 pointer_type_class, reference_type_class, offset_type_class,
5326 real_type_class, complex_type_class,
5327 function_type_class, method_type_class,
5328 record_type_class, union_type_class,
5329 array_type_class, string_type_class,
5330 lang_type_class
5331 };
Mike Stump11289f42009-09-09 15:08:12 +00005332
5333 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00005334 // ideal, however it is what gcc does.
5335 if (E->getNumArgs() == 0)
5336 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00005337
Chris Lattner86ee2862008-10-06 06:40:35 +00005338 QualType ArgTy = E->getArg(0)->getType();
5339 if (ArgTy->isVoidType())
5340 return void_type_class;
5341 else if (ArgTy->isEnumeralType())
5342 return enumeral_type_class;
5343 else if (ArgTy->isBooleanType())
5344 return boolean_type_class;
5345 else if (ArgTy->isCharType())
5346 return string_type_class; // gcc doesn't appear to use char_type_class
5347 else if (ArgTy->isIntegerType())
5348 return integer_type_class;
5349 else if (ArgTy->isPointerType())
5350 return pointer_type_class;
5351 else if (ArgTy->isReferenceType())
5352 return reference_type_class;
5353 else if (ArgTy->isRealType())
5354 return real_type_class;
5355 else if (ArgTy->isComplexType())
5356 return complex_type_class;
5357 else if (ArgTy->isFunctionType())
5358 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00005359 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00005360 return record_type_class;
5361 else if (ArgTy->isUnionType())
5362 return union_type_class;
5363 else if (ArgTy->isArrayType())
5364 return array_type_class;
5365 else if (ArgTy->isUnionType())
5366 return union_type_class;
5367 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00005368 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00005369}
5370
Richard Smith5fab0c92011-12-28 19:48:30 +00005371/// EvaluateBuiltinConstantPForLValue - Determine the result of
5372/// __builtin_constant_p when applied to the given lvalue.
5373///
5374/// An lvalue is only "constant" if it is a pointer or reference to the first
5375/// character of a string literal.
5376template<typename LValue>
5377static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00005378 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00005379 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
5380}
5381
5382/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
5383/// GCC as we can manage.
5384static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
5385 QualType ArgType = Arg->getType();
5386
5387 // __builtin_constant_p always has one operand. The rules which gcc follows
5388 // are not precisely documented, but are as follows:
5389 //
5390 // - If the operand is of integral, floating, complex or enumeration type,
5391 // and can be folded to a known value of that type, it returns 1.
5392 // - If the operand and can be folded to a pointer to the first character
5393 // of a string literal (or such a pointer cast to an integral type), it
5394 // returns 1.
5395 //
5396 // Otherwise, it returns 0.
5397 //
5398 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
5399 // its support for this does not currently work.
5400 if (ArgType->isIntegralOrEnumerationType()) {
5401 Expr::EvalResult Result;
5402 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
5403 return false;
5404
5405 APValue &V = Result.Val;
5406 if (V.getKind() == APValue::Int)
5407 return true;
5408
5409 return EvaluateBuiltinConstantPForLValue(V);
5410 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
5411 return Arg->isEvaluatable(Ctx);
5412 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
5413 LValue LV;
5414 Expr::EvalStatus Status;
5415 EvalInfo Info(Ctx, Status);
5416 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
5417 : EvaluatePointer(Arg, LV, Info)) &&
5418 !Status.HasSideEffects)
5419 return EvaluateBuiltinConstantPForLValue(LV);
5420 }
5421
5422 // Anything else isn't considered to be sufficiently constant.
5423 return false;
5424}
5425
John McCall95007602010-05-10 23:27:23 +00005426/// Retrieves the "underlying object type" of the given expression,
5427/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00005428QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
5429 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
5430 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00005431 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00005432 } else if (const Expr *E = B.get<const Expr*>()) {
5433 if (isa<CompoundLiteralExpr>(E))
5434 return E->getType();
John McCall95007602010-05-10 23:27:23 +00005435 }
5436
5437 return QualType();
5438}
5439
Peter Collingbournee9200682011-05-13 03:29:01 +00005440bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00005441 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00005442
5443 {
5444 // The operand of __builtin_object_size is never evaluated for side-effects.
5445 // If there are any, but we can determine the pointed-to object anyway, then
5446 // ignore the side-effects.
5447 SpeculativeEvaluationRAII SpeculativeEval(Info);
5448 if (!EvaluatePointer(E->getArg(0), Base, Info))
5449 return false;
5450 }
John McCall95007602010-05-10 23:27:23 +00005451
5452 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00005453 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00005454
Richard Smithce40ad62011-11-12 22:28:03 +00005455 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00005456 if (T.isNull() ||
5457 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00005458 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00005459 T->isVariablyModifiedType() ||
5460 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005461 return Error(E);
John McCall95007602010-05-10 23:27:23 +00005462
5463 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
5464 CharUnits Offset = Base.getLValueOffset();
5465
5466 if (!Offset.isNegative() && Offset <= Size)
5467 Size -= Offset;
5468 else
5469 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00005470 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00005471}
5472
Peter Collingbournee9200682011-05-13 03:29:01 +00005473bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith01ba47d2012-04-13 00:45:38 +00005474 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005475 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00005476 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005477
5478 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00005479 if (TryEvaluateBuiltinObjectSize(E))
5480 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00005481
Richard Smith0421ce72012-08-07 04:16:51 +00005482 // If evaluating the argument has side-effects, we can't determine the size
5483 // of the object, and so we lower it to unknown now. CodeGen relies on us to
5484 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005485 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00005486 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00005487 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00005488 return Success(0, E);
5489 }
Mike Stump876387b2009-10-27 22:09:17 +00005490
Richard Smith01ade172012-05-23 04:13:20 +00005491 // Expression had no side effects, but we couldn't statically determine the
5492 // size of the referenced object.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005493 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005494 }
5495
Benjamin Kramera801f4a2012-10-06 14:42:22 +00005496 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00005497 case Builtin::BI__builtin_bswap32:
5498 case Builtin::BI__builtin_bswap64: {
5499 APSInt Val;
5500 if (!EvaluateInteger(E->getArg(0), Val, Info))
5501 return false;
5502
5503 return Success(Val.byteSwap(), E);
5504 }
5505
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005506 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005507 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00005508
Richard Smith5fab0c92011-12-28 19:48:30 +00005509 case Builtin::BI__builtin_constant_p:
5510 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smith10c7c902011-12-09 02:04:48 +00005511
Chris Lattnerd545ad12009-09-23 06:06:36 +00005512 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00005513 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00005514 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00005515 return Success(Operand, E);
5516 }
Eli Friedmand5c93992010-02-13 00:10:10 +00005517
5518 case Builtin::BI__builtin_expect:
5519 return Visit(E->getArg(0));
Richard Smith9cf080f2012-01-18 03:06:12 +00005520
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005521 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00005522 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005523 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00005524 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00005525 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
5526 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00005527 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00005528 // Fall through.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005529 case Builtin::BI__builtin_strlen:
5530 // As an extension, we support strlen() and __builtin_strlen() as constant
5531 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00005532 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005533 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
5534 // The string literal may have embedded null characters. Find the first
5535 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005536 StringRef Str = S->getString();
5537 StringRef::size_type Pos = Str.find(0);
5538 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005539 Str = Str.substr(0, Pos);
5540
5541 return Success(Str.size(), E);
5542 }
5543
Richard Smithf57d8cb2011-12-09 22:58:01 +00005544 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005545
Richard Smith01ba47d2012-04-13 00:45:38 +00005546 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00005547 case Builtin::BI__atomic_is_lock_free:
5548 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00005549 APSInt SizeVal;
5550 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
5551 return false;
5552
5553 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
5554 // of two less than the maximum inline atomic width, we know it is
5555 // lock-free. If the size isn't a power of two, or greater than the
5556 // maximum alignment where we promote atomics, we know it is not lock-free
5557 // (at least not in the sense of atomic_is_lock_free). Otherwise,
5558 // the answer can only be determined at runtime; for example, 16-byte
5559 // atomics have lock-free implementations on some, but not all,
5560 // x86-64 processors.
5561
5562 // Check power-of-two.
5563 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00005564 if (Size.isPowerOfTwo()) {
5565 // Check against inlining width.
5566 unsigned InlineWidthBits =
5567 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
5568 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
5569 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
5570 Size == CharUnits::One() ||
5571 E->getArg(1)->isNullPointerConstant(Info.Ctx,
5572 Expr::NPC_NeverValueDependent))
5573 // OK, we will inline appropriately-aligned operations of this size,
5574 // and _Atomic(T) is appropriately-aligned.
5575 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005576
Richard Smith01ba47d2012-04-13 00:45:38 +00005577 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
5578 castAs<PointerType>()->getPointeeType();
5579 if (!PointeeType->isIncompleteType() &&
5580 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
5581 // OK, we will inline operations on this object.
5582 return Success(1, E);
5583 }
5584 }
5585 }
Eli Friedmana4c26022011-10-17 21:44:23 +00005586
Richard Smith01ba47d2012-04-13 00:45:38 +00005587 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
5588 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005589 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005590 }
Chris Lattner7174bf32008-07-12 00:38:25 +00005591}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005592
Richard Smith8b3497e2011-10-31 01:37:14 +00005593static bool HasSameBase(const LValue &A, const LValue &B) {
5594 if (!A.getLValueBase())
5595 return !B.getLValueBase();
5596 if (!B.getLValueBase())
5597 return false;
5598
Richard Smithce40ad62011-11-12 22:28:03 +00005599 if (A.getLValueBase().getOpaqueValue() !=
5600 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00005601 const Decl *ADecl = GetLValueBaseDecl(A);
5602 if (!ADecl)
5603 return false;
5604 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00005605 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00005606 return false;
5607 }
5608
5609 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00005610 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00005611}
5612
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005613namespace {
Richard Smith11562c52011-10-28 17:51:58 +00005614
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005615/// \brief Data recursive integer evaluator of certain binary operators.
5616///
5617/// We use a data recursive algorithm for binary operators so that we are able
5618/// to handle extreme cases of chained binary operators without causing stack
5619/// overflow.
5620class DataRecursiveIntBinOpEvaluator {
5621 struct EvalResult {
5622 APValue Val;
5623 bool Failed;
5624
5625 EvalResult() : Failed(false) { }
5626
5627 void swap(EvalResult &RHS) {
5628 Val.swap(RHS.Val);
5629 Failed = RHS.Failed;
5630 RHS.Failed = false;
5631 }
5632 };
5633
5634 struct Job {
5635 const Expr *E;
5636 EvalResult LHSResult; // meaningful only for binary operator expression.
5637 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
5638
5639 Job() : StoredInfo(0) { }
5640 void startSpeculativeEval(EvalInfo &Info) {
5641 OldEvalStatus = Info.EvalStatus;
5642 Info.EvalStatus.Diag = 0;
5643 StoredInfo = &Info;
5644 }
5645 ~Job() {
5646 if (StoredInfo) {
5647 StoredInfo->EvalStatus = OldEvalStatus;
5648 }
5649 }
5650 private:
5651 EvalInfo *StoredInfo; // non-null if status changed.
5652 Expr::EvalStatus OldEvalStatus;
5653 };
5654
5655 SmallVector<Job, 16> Queue;
5656
5657 IntExprEvaluator &IntEval;
5658 EvalInfo &Info;
5659 APValue &FinalResult;
5660
5661public:
5662 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
5663 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
5664
5665 /// \brief True if \param E is a binary operator that we are going to handle
5666 /// data recursively.
5667 /// We handle binary operators that are comma, logical, or that have operands
5668 /// with integral or enumeration type.
5669 static bool shouldEnqueue(const BinaryOperator *E) {
5670 return E->getOpcode() == BO_Comma ||
5671 E->isLogicalOp() ||
5672 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5673 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00005674 }
5675
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005676 bool Traverse(const BinaryOperator *E) {
5677 enqueue(E);
5678 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00005679 while (!Queue.empty())
5680 process(PrevResult);
5681
5682 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005683
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005684 FinalResult.swap(PrevResult.Val);
5685 return true;
5686 }
5687
5688private:
5689 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
5690 return IntEval.Success(Value, E, Result);
5691 }
5692 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
5693 return IntEval.Success(Value, E, Result);
5694 }
5695 bool Error(const Expr *E) {
5696 return IntEval.Error(E);
5697 }
5698 bool Error(const Expr *E, diag::kind D) {
5699 return IntEval.Error(E, D);
5700 }
5701
5702 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
5703 return Info.CCEDiag(E, D);
5704 }
5705
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005706 // \brief Returns true if visiting the RHS is necessary, false otherwise.
5707 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005708 bool &SuppressRHSDiags);
5709
5710 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
5711 const BinaryOperator *E, APValue &Result);
5712
5713 void EvaluateExpr(const Expr *E, EvalResult &Result) {
5714 Result.Failed = !Evaluate(Result.Val, Info, E);
5715 if (Result.Failed)
5716 Result.Val = APValue();
5717 }
5718
Richard Trieuba4d0872012-03-21 23:30:30 +00005719 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005720
5721 void enqueue(const Expr *E) {
5722 E = E->IgnoreParens();
5723 Queue.resize(Queue.size()+1);
5724 Queue.back().E = E;
5725 Queue.back().Kind = Job::AnyExprKind;
5726 }
5727};
5728
5729}
5730
5731bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005732 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005733 bool &SuppressRHSDiags) {
5734 if (E->getOpcode() == BO_Comma) {
5735 // Ignore LHS but note if we could not evaluate it.
5736 if (LHSResult.Failed)
5737 Info.EvalStatus.HasSideEffects = true;
5738 return true;
5739 }
5740
5741 if (E->isLogicalOp()) {
5742 bool lhsResult;
5743 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005744 // We were able to evaluate the LHS, see if we can get away with not
5745 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005746 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005747 Success(lhsResult, E, LHSResult.Val);
5748 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005749 }
5750 } else {
5751 // Since we weren't able to evaluate the left hand side, it
5752 // must have had side effects.
5753 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005754
5755 // We can't evaluate the LHS; however, sometimes the result
5756 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
5757 // Don't ignore RHS and suppress diagnostics from this arm.
5758 SuppressRHSDiags = true;
5759 }
5760
5761 return true;
5762 }
5763
5764 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5765 E->getRHS()->getType()->isIntegralOrEnumerationType());
5766
5767 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005768 return false; // Ignore RHS;
5769
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005770 return true;
5771}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005772
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005773bool DataRecursiveIntBinOpEvaluator::
5774 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
5775 const BinaryOperator *E, APValue &Result) {
5776 if (E->getOpcode() == BO_Comma) {
5777 if (RHSResult.Failed)
5778 return false;
5779 Result = RHSResult.Val;
5780 return true;
5781 }
5782
5783 if (E->isLogicalOp()) {
5784 bool lhsResult, rhsResult;
5785 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
5786 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
5787
5788 if (LHSIsOK) {
5789 if (RHSIsOK) {
5790 if (E->getOpcode() == BO_LOr)
5791 return Success(lhsResult || rhsResult, E, Result);
5792 else
5793 return Success(lhsResult && rhsResult, E, Result);
5794 }
5795 } else {
5796 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005797 // We can't evaluate the LHS; however, sometimes the result
5798 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
5799 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005800 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005801 }
5802 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005803
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005804 return false;
5805 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005806
5807 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5808 E->getRHS()->getType()->isIntegralOrEnumerationType());
5809
5810 if (LHSResult.Failed || RHSResult.Failed)
5811 return false;
5812
5813 const APValue &LHSVal = LHSResult.Val;
5814 const APValue &RHSVal = RHSResult.Val;
5815
5816 // Handle cases like (unsigned long)&a + 4.
5817 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
5818 Result = LHSVal;
5819 CharUnits AdditionalOffset = CharUnits::fromQuantity(
5820 RHSVal.getInt().getZExtValue());
5821 if (E->getOpcode() == BO_Add)
5822 Result.getLValueOffset() += AdditionalOffset;
5823 else
5824 Result.getLValueOffset() -= AdditionalOffset;
5825 return true;
5826 }
5827
5828 // Handle cases like 4 + (unsigned long)&a
5829 if (E->getOpcode() == BO_Add &&
5830 RHSVal.isLValue() && LHSVal.isInt()) {
5831 Result = RHSVal;
5832 Result.getLValueOffset() += CharUnits::fromQuantity(
5833 LHSVal.getInt().getZExtValue());
5834 return true;
5835 }
5836
5837 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
5838 // Handle (intptr_t)&&A - (intptr_t)&&B.
5839 if (!LHSVal.getLValueOffset().isZero() ||
5840 !RHSVal.getLValueOffset().isZero())
5841 return false;
5842 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
5843 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
5844 if (!LHSExpr || !RHSExpr)
5845 return false;
5846 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
5847 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
5848 if (!LHSAddrExpr || !RHSAddrExpr)
5849 return false;
5850 // Make sure both labels come from the same function.
5851 if (LHSAddrExpr->getLabel()->getDeclContext() !=
5852 RHSAddrExpr->getLabel()->getDeclContext())
5853 return false;
5854 Result = APValue(LHSAddrExpr, RHSAddrExpr);
5855 return true;
5856 }
Richard Smith43e77732013-05-07 04:50:00 +00005857
5858 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005859 if (!LHSVal.isInt() || !RHSVal.isInt())
5860 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00005861
5862 // Set up the width and signedness manually, in case it can't be deduced
5863 // from the operation we're performing.
5864 // FIXME: Don't do this in the cases where we can deduce it.
5865 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
5866 E->getType()->isUnsignedIntegerOrEnumerationType());
5867 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
5868 RHSVal.getInt(), Value))
5869 return false;
5870 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005871}
5872
Richard Trieuba4d0872012-03-21 23:30:30 +00005873void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005874 Job &job = Queue.back();
5875
5876 switch (job.Kind) {
5877 case Job::AnyExprKind: {
5878 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
5879 if (shouldEnqueue(Bop)) {
5880 job.Kind = Job::BinOpKind;
5881 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00005882 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005883 }
5884 }
5885
5886 EvaluateExpr(job.E, Result);
5887 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005888 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005889 }
5890
5891 case Job::BinOpKind: {
5892 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005893 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005894 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005895 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005896 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005897 }
5898 if (SuppressRHSDiags)
5899 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005900 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005901 job.Kind = Job::BinOpVisitedLHSKind;
5902 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00005903 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005904 }
5905
5906 case Job::BinOpVisitedLHSKind: {
5907 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
5908 EvalResult RHS;
5909 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00005910 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005911 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005912 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005913 }
5914 }
5915
5916 llvm_unreachable("Invalid Job::Kind!");
5917}
5918
5919bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5920 if (E->isAssignmentOp())
5921 return Error(E);
5922
5923 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
5924 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00005925
Anders Carlssonacc79812008-11-16 07:17:21 +00005926 QualType LHSTy = E->getLHS()->getType();
5927 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005928
5929 if (LHSTy->isAnyComplexType()) {
5930 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00005931 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005932
Richard Smith253c2a32012-01-27 01:14:48 +00005933 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
5934 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005935 return false;
5936
Richard Smith253c2a32012-01-27 01:14:48 +00005937 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005938 return false;
5939
5940 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00005941 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005942 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00005943 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005944 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
5945
John McCalle3027922010-08-25 11:45:40 +00005946 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005947 return Success((CR_r == APFloat::cmpEqual &&
5948 CR_i == APFloat::cmpEqual), E);
5949 else {
John McCalle3027922010-08-25 11:45:40 +00005950 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005951 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00005952 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00005953 CR_r == APFloat::cmpLessThan ||
5954 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00005955 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00005956 CR_i == APFloat::cmpLessThan ||
5957 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005958 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005959 } else {
John McCalle3027922010-08-25 11:45:40 +00005960 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005961 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
5962 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
5963 else {
John McCalle3027922010-08-25 11:45:40 +00005964 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005965 "Invalid compex comparison.");
5966 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
5967 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
5968 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005969 }
5970 }
Mike Stump11289f42009-09-09 15:08:12 +00005971
Anders Carlssonacc79812008-11-16 07:17:21 +00005972 if (LHSTy->isRealFloatingType() &&
5973 RHSTy->isRealFloatingType()) {
5974 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00005975
Richard Smith253c2a32012-01-27 01:14:48 +00005976 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
5977 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00005978 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005979
Richard Smith253c2a32012-01-27 01:14:48 +00005980 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00005981 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005982
Anders Carlssonacc79812008-11-16 07:17:21 +00005983 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00005984
Anders Carlssonacc79812008-11-16 07:17:21 +00005985 switch (E->getOpcode()) {
5986 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005987 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00005988 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005989 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00005990 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005991 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00005992 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005993 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00005994 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00005995 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005996 E);
John McCalle3027922010-08-25 11:45:40 +00005997 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005998 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00005999 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00006000 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00006001 || CR == APFloat::cmpLessThan
6002 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00006003 }
Anders Carlssonacc79812008-11-16 07:17:21 +00006004 }
Mike Stump11289f42009-09-09 15:08:12 +00006005
Eli Friedmana38da572009-04-28 19:17:36 +00006006 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006007 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00006008 LValue LHSValue, RHSValue;
6009
6010 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6011 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006012 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006013
Richard Smith253c2a32012-01-27 01:14:48 +00006014 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006015 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006016
Richard Smith8b3497e2011-10-31 01:37:14 +00006017 // Reject differing bases from the normal codepath; we special-case
6018 // comparisons to null.
6019 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006020 if (E->getOpcode() == BO_Sub) {
6021 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006022 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6023 return false;
6024 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00006025 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006026 if (!LHSExpr || !RHSExpr)
6027 return false;
6028 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6029 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6030 if (!LHSAddrExpr || !RHSAddrExpr)
6031 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006032 // Make sure both labels come from the same function.
6033 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6034 RHSAddrExpr->getLabel()->getDeclContext())
6035 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006036 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006037 return true;
6038 }
Richard Smith83c68212011-10-31 05:11:32 +00006039 // Inequalities and subtractions between unrelated pointers have
6040 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00006041 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006042 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006043 // A constant address may compare equal to the address of a symbol.
6044 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00006045 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006046 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6047 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006048 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006049 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00006050 // distinct addresses. In clang, the result of such a comparison is
6051 // unspecified, so it is not a constant expression. However, we do know
6052 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00006053 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6054 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006055 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006056 // We can't tell whether weak symbols will end up pointing to the same
6057 // object.
6058 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006059 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006060 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00006061 // (Note that clang defaults to -fmerge-all-constants, which can
6062 // lead to inconsistent results for comparisons involving the address
6063 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00006064 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00006065 }
Eli Friedman64004332009-03-23 04:38:34 +00006066
Richard Smith1b470412012-02-01 08:10:20 +00006067 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
6068 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
6069
Richard Smith84f6dcf2012-02-02 01:16:57 +00006070 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
6071 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
6072
John McCalle3027922010-08-25 11:45:40 +00006073 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00006074 // C++11 [expr.add]p6:
6075 // Unless both pointers point to elements of the same array object, or
6076 // one past the last element of the array object, the behavior is
6077 // undefined.
6078 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6079 !AreElementsOfSameArray(getType(LHSValue.Base),
6080 LHSDesignator, RHSDesignator))
6081 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
6082
Chris Lattner882bdf22010-04-20 17:13:14 +00006083 QualType Type = E->getLHS()->getType();
6084 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006085
Richard Smithd62306a2011-11-10 06:34:14 +00006086 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00006087 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00006088 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006089
Richard Smith1b470412012-02-01 08:10:20 +00006090 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
6091 // and produce incorrect results when it overflows. Such behavior
6092 // appears to be non-conforming, but is common, so perhaps we should
6093 // assume the standard intended for such cases to be undefined behavior
6094 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00006095
Richard Smith1b470412012-02-01 08:10:20 +00006096 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
6097 // overflow in the final conversion to ptrdiff_t.
6098 APSInt LHS(
6099 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
6100 APSInt RHS(
6101 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
6102 APSInt ElemSize(
6103 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
6104 APSInt TrueResult = (LHS - RHS) / ElemSize;
6105 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
6106
6107 if (Result.extend(65) != TrueResult)
6108 HandleOverflow(Info, E, TrueResult, E->getType());
6109 return Success(Result, E);
6110 }
Richard Smithde21b242012-01-31 06:41:30 +00006111
6112 // C++11 [expr.rel]p3:
6113 // Pointers to void (after pointer conversions) can be compared, with a
6114 // result defined as follows: If both pointers represent the same
6115 // address or are both the null pointer value, the result is true if the
6116 // operator is <= or >= and false otherwise; otherwise the result is
6117 // unspecified.
6118 // We interpret this as applying to pointers to *cv* void.
6119 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00006120 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00006121 CCEDiag(E, diag::note_constexpr_void_comparison);
6122
Richard Smith84f6dcf2012-02-02 01:16:57 +00006123 // C++11 [expr.rel]p2:
6124 // - If two pointers point to non-static data members of the same object,
6125 // or to subobjects or array elements fo such members, recursively, the
6126 // pointer to the later declared member compares greater provided the
6127 // two members have the same access control and provided their class is
6128 // not a union.
6129 // [...]
6130 // - Otherwise pointer comparisons are unspecified.
6131 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6132 E->isRelationalOp()) {
6133 bool WasArrayIndex;
6134 unsigned Mismatch =
6135 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
6136 RHSDesignator, WasArrayIndex);
6137 // At the point where the designators diverge, the comparison has a
6138 // specified value if:
6139 // - we are comparing array indices
6140 // - we are comparing fields of a union, or fields with the same access
6141 // Otherwise, the result is unspecified and thus the comparison is not a
6142 // constant expression.
6143 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
6144 Mismatch < RHSDesignator.Entries.size()) {
6145 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
6146 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
6147 if (!LF && !RF)
6148 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
6149 else if (!LF)
6150 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6151 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
6152 << RF->getParent() << RF;
6153 else if (!RF)
6154 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6155 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
6156 << LF->getParent() << LF;
6157 else if (!LF->getParent()->isUnion() &&
6158 LF->getAccess() != RF->getAccess())
6159 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
6160 << LF << LF->getAccess() << RF << RF->getAccess()
6161 << LF->getParent();
6162 }
6163 }
6164
Eli Friedman6c31cb42012-04-16 04:30:08 +00006165 // The comparison here must be unsigned, and performed with the same
6166 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00006167 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
6168 uint64_t CompareLHS = LHSOffset.getQuantity();
6169 uint64_t CompareRHS = RHSOffset.getQuantity();
6170 assert(PtrSize <= 64 && "Unexpected pointer width");
6171 uint64_t Mask = ~0ULL >> (64 - PtrSize);
6172 CompareLHS &= Mask;
6173 CompareRHS &= Mask;
6174
Eli Friedman2f5b7c52012-04-16 19:23:57 +00006175 // If there is a base and this is a relational operator, we can only
6176 // compare pointers within the object in question; otherwise, the result
6177 // depends on where the object is located in memory.
6178 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
6179 QualType BaseTy = getType(LHSValue.Base);
6180 if (BaseTy->isIncompleteType())
6181 return Error(E);
6182 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
6183 uint64_t OffsetLimit = Size.getQuantity();
6184 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
6185 return Error(E);
6186 }
6187
Richard Smith8b3497e2011-10-31 01:37:14 +00006188 switch (E->getOpcode()) {
6189 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00006190 case BO_LT: return Success(CompareLHS < CompareRHS, E);
6191 case BO_GT: return Success(CompareLHS > CompareRHS, E);
6192 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
6193 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
6194 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
6195 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00006196 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006197 }
6198 }
Richard Smith7bb00672012-02-01 01:42:44 +00006199
6200 if (LHSTy->isMemberPointerType()) {
6201 assert(E->isEqualityOp() && "unexpected member pointer operation");
6202 assert(RHSTy->isMemberPointerType() && "invalid comparison");
6203
6204 MemberPtr LHSValue, RHSValue;
6205
6206 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
6207 if (!LHSOK && Info.keepEvaluatingAfterFailure())
6208 return false;
6209
6210 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6211 return false;
6212
6213 // C++11 [expr.eq]p2:
6214 // If both operands are null, they compare equal. Otherwise if only one is
6215 // null, they compare unequal.
6216 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
6217 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
6218 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6219 }
6220
6221 // Otherwise if either is a pointer to a virtual member function, the
6222 // result is unspecified.
6223 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
6224 if (MD->isVirtual())
6225 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6226 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
6227 if (MD->isVirtual())
6228 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6229
6230 // Otherwise they compare equal if and only if they would refer to the
6231 // same member of the same most derived object or the same subobject if
6232 // they were dereferenced with a hypothetical object of the associated
6233 // class type.
6234 bool Equal = LHSValue == RHSValue;
6235 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6236 }
6237
Richard Smithab44d9b2012-02-14 22:35:28 +00006238 if (LHSTy->isNullPtrType()) {
6239 assert(E->isComparisonOp() && "unexpected nullptr operation");
6240 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
6241 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
6242 // are compared, the result is true of the operator is <=, >= or ==, and
6243 // false otherwise.
6244 BinaryOperator::Opcode Opcode = E->getOpcode();
6245 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
6246 }
6247
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006248 assert((!LHSTy->isIntegralOrEnumerationType() ||
6249 !RHSTy->isIntegralOrEnumerationType()) &&
6250 "DataRecursiveIntBinOpEvaluator should have handled integral types");
6251 // We can't continue from here for non-integral types.
6252 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00006253}
6254
Ken Dyck160146e2010-01-27 17:10:57 +00006255CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00006256 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
6257 // result shall be the alignment of the referenced type."
6258 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6259 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00006260
6261 // __alignof is defined to return the preferred alignment.
6262 return Info.Ctx.toCharUnitsFromBits(
6263 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00006264}
6265
Ken Dyck160146e2010-01-27 17:10:57 +00006266CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00006267 E = E->IgnoreParens();
6268
John McCall768439e2013-05-06 07:40:34 +00006269 // The kinds of expressions that we have special-case logic here for
6270 // should be kept up to date with the special checks for those
6271 // expressions in Sema.
6272
Chris Lattner68061312009-01-24 21:53:27 +00006273 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00006274 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00006275 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006276 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6277 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00006278
Chris Lattner68061312009-01-24 21:53:27 +00006279 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006280 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6281 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00006282
Chris Lattner24aeeab2009-01-24 21:09:06 +00006283 return GetAlignOfType(E->getType());
6284}
6285
6286
Peter Collingbournee190dee2011-03-11 19:24:49 +00006287/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
6288/// a result as the expression's type.
6289bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
6290 const UnaryExprOrTypeTraitExpr *E) {
6291 switch(E->getKind()) {
6292 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00006293 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00006294 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006295 else
Ken Dyckdbc01912011-03-11 02:13:43 +00006296 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006297 }
Eli Friedman64004332009-03-23 04:38:34 +00006298
Peter Collingbournee190dee2011-03-11 19:24:49 +00006299 case UETT_VecStep: {
6300 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00006301
Peter Collingbournee190dee2011-03-11 19:24:49 +00006302 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00006303 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00006304
Peter Collingbournee190dee2011-03-11 19:24:49 +00006305 // The vec_step built-in functions that take a 3-component
6306 // vector return 4. (OpenCL 1.1 spec 6.11.12)
6307 if (n == 3)
6308 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00006309
Peter Collingbournee190dee2011-03-11 19:24:49 +00006310 return Success(n, E);
6311 } else
6312 return Success(1, E);
6313 }
6314
6315 case UETT_SizeOf: {
6316 QualType SrcTy = E->getTypeOfArgument();
6317 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
6318 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00006319 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
6320 SrcTy = Ref->getPointeeType();
6321
Richard Smithd62306a2011-11-10 06:34:14 +00006322 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00006323 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00006324 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006325 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006326 }
6327 }
6328
6329 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006330}
6331
Peter Collingbournee9200682011-05-13 03:29:01 +00006332bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00006333 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00006334 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00006335 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006336 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00006337 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00006338 for (unsigned i = 0; i != n; ++i) {
6339 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
6340 switch (ON.getKind()) {
6341 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00006342 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00006343 APSInt IdxResult;
6344 if (!EvaluateInteger(Idx, IdxResult, Info))
6345 return false;
6346 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
6347 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006348 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006349 CurrentType = AT->getElementType();
6350 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
6351 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00006352 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00006353 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006354
Douglas Gregor882211c2010-04-28 22:16:22 +00006355 case OffsetOfExpr::OffsetOfNode::Field: {
6356 FieldDecl *MemberDecl = ON.getField();
6357 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006358 if (!RT)
6359 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006360 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006361 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00006362 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00006363 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00006364 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00006365 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00006366 CurrentType = MemberDecl->getType().getNonReferenceType();
6367 break;
6368 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006369
Douglas Gregor882211c2010-04-28 22:16:22 +00006370 case OffsetOfExpr::OffsetOfNode::Identifier:
6371 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00006372
Douglas Gregord1702062010-04-29 00:18:15 +00006373 case OffsetOfExpr::OffsetOfNode::Base: {
6374 CXXBaseSpecifier *BaseSpec = ON.getBase();
6375 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006376 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006377
6378 // Find the layout of the class whose base we are looking into.
6379 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006380 if (!RT)
6381 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006382 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006383 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00006384 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
6385
6386 // Find the base class itself.
6387 CurrentType = BaseSpec->getType();
6388 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
6389 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006390 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006391
6392 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00006393 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00006394 break;
6395 }
Douglas Gregor882211c2010-04-28 22:16:22 +00006396 }
6397 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006398 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006399}
6400
Chris Lattnere13042c2008-07-11 19:10:17 +00006401bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006402 switch (E->getOpcode()) {
6403 default:
6404 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
6405 // See C99 6.6p3.
6406 return Error(E);
6407 case UO_Extension:
6408 // FIXME: Should extension allow i-c-e extension expressions in its scope?
6409 // If so, we could clear the diagnostic ID.
6410 return Visit(E->getSubExpr());
6411 case UO_Plus:
6412 // The result is just the value.
6413 return Visit(E->getSubExpr());
6414 case UO_Minus: {
6415 if (!Visit(E->getSubExpr()))
6416 return false;
6417 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00006418 const APSInt &Value = Result.getInt();
6419 if (Value.isSigned() && Value.isMinSignedValue())
6420 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
6421 E->getType());
6422 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006423 }
6424 case UO_Not: {
6425 if (!Visit(E->getSubExpr()))
6426 return false;
6427 if (!Result.isInt()) return Error(E);
6428 return Success(~Result.getInt(), E);
6429 }
6430 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00006431 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00006432 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00006433 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006434 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006435 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006436 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006437}
Mike Stump11289f42009-09-09 15:08:12 +00006438
Chris Lattner477c4be2008-07-12 01:15:53 +00006439/// HandleCast - This is used to evaluate implicit or explicit casts where the
6440/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00006441bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
6442 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006443 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00006444 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006445
Eli Friedmanc757de22011-03-25 00:43:55 +00006446 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00006447 case CK_BaseToDerived:
6448 case CK_DerivedToBase:
6449 case CK_UncheckedDerivedToBase:
6450 case CK_Dynamic:
6451 case CK_ToUnion:
6452 case CK_ArrayToPointerDecay:
6453 case CK_FunctionToPointerDecay:
6454 case CK_NullToPointer:
6455 case CK_NullToMemberPointer:
6456 case CK_BaseToDerivedMemberPointer:
6457 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00006458 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00006459 case CK_ConstructorConversion:
6460 case CK_IntegralToPointer:
6461 case CK_ToVoid:
6462 case CK_VectorSplat:
6463 case CK_IntegralToFloating:
6464 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00006465 case CK_CPointerToObjCPointerCast:
6466 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006467 case CK_AnyPointerToBlockPointerCast:
6468 case CK_ObjCObjectLValueCast:
6469 case CK_FloatingRealToComplex:
6470 case CK_FloatingComplexToReal:
6471 case CK_FloatingComplexCast:
6472 case CK_FloatingComplexToIntegralComplex:
6473 case CK_IntegralRealToComplex:
6474 case CK_IntegralComplexCast:
6475 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00006476 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006477 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00006478 case CK_NonAtomicToAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00006479 llvm_unreachable("invalid cast kind for integral value");
6480
Eli Friedman9faf2f92011-03-25 19:07:11 +00006481 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006482 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006483 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00006484 case CK_ARCProduceObject:
6485 case CK_ARCConsumeObject:
6486 case CK_ARCReclaimReturnedObject:
6487 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00006488 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006489 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006490
Richard Smith4ef685b2012-01-17 21:17:26 +00006491 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00006492 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006493 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00006494 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00006495 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006496
6497 case CK_MemberPointerToBoolean:
6498 case CK_PointerToBoolean:
6499 case CK_IntegralToBoolean:
6500 case CK_FloatingToBoolean:
6501 case CK_FloatingComplexToBoolean:
6502 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006503 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00006504 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00006505 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006506 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006507 }
6508
Eli Friedmanc757de22011-03-25 00:43:55 +00006509 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00006510 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00006511 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00006512
Eli Friedman742421e2009-02-20 01:15:07 +00006513 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006514 // Allow casts of address-of-label differences if they are no-ops
6515 // or narrowing. (The narrowing case isn't actually guaranteed to
6516 // be constant-evaluatable except in some narrow cases which are hard
6517 // to detect here. We let it through on the assumption the user knows
6518 // what they are doing.)
6519 if (Result.isAddrLabelDiff())
6520 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00006521 // Only allow casts of lvalues if they are lossless.
6522 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
6523 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006524
Richard Smith911e1422012-01-30 22:27:01 +00006525 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
6526 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00006527 }
Mike Stump11289f42009-09-09 15:08:12 +00006528
Eli Friedmanc757de22011-03-25 00:43:55 +00006529 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00006530 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6531
John McCall45d55e42010-05-07 21:00:08 +00006532 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00006533 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00006534 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00006535
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006536 if (LV.getLValueBase()) {
6537 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00006538 // FIXME: Allow a larger integer size than the pointer size, and allow
6539 // narrowing back down to pointer width in subsequent integral casts.
6540 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006541 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006542 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006543
Richard Smithcf74da72011-11-16 07:18:12 +00006544 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00006545 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006546 return true;
6547 }
6548
Ken Dyck02990832010-01-15 12:37:54 +00006549 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
6550 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00006551 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006552 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006553
Eli Friedmanc757de22011-03-25 00:43:55 +00006554 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00006555 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006556 if (!EvaluateComplex(SubExpr, C, Info))
6557 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00006558 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006559 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00006560
Eli Friedmanc757de22011-03-25 00:43:55 +00006561 case CK_FloatingToIntegral: {
6562 APFloat F(0.0);
6563 if (!EvaluateFloat(SubExpr, F, Info))
6564 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00006565
Richard Smith357362d2011-12-13 06:39:58 +00006566 APSInt Value;
6567 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
6568 return false;
6569 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006570 }
6571 }
Mike Stump11289f42009-09-09 15:08:12 +00006572
Eli Friedmanc757de22011-03-25 00:43:55 +00006573 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00006574}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006575
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006576bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6577 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00006578 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006579 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
6580 return false;
6581 if (!LV.isComplexInt())
6582 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006583 return Success(LV.getComplexIntReal(), E);
6584 }
6585
6586 return Visit(E->getSubExpr());
6587}
6588
Eli Friedman4e7a2412009-02-27 04:45:43 +00006589bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006590 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00006591 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006592 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
6593 return false;
6594 if (!LV.isComplexInt())
6595 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006596 return Success(LV.getComplexIntImag(), E);
6597 }
6598
Richard Smith4a678122011-10-24 18:44:57 +00006599 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00006600 return Success(0, E);
6601}
6602
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006603bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
6604 return Success(E->getPackLength(), E);
6605}
6606
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006607bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
6608 return Success(E->getValue(), E);
6609}
6610
Chris Lattner05706e882008-07-11 18:11:29 +00006611//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00006612// Float Evaluation
6613//===----------------------------------------------------------------------===//
6614
6615namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006616class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00006617 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00006618 APFloat &Result;
6619public:
6620 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006621 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00006622
Richard Smith2e312c82012-03-03 22:46:17 +00006623 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006624 Result = V.getFloat();
6625 return true;
6626 }
Eli Friedman24c01542008-08-22 00:06:13 +00006627
Richard Smithfddd3842011-12-30 21:15:51 +00006628 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00006629 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
6630 return true;
6631 }
6632
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006633 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00006634
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006635 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00006636 bool VisitBinaryOperator(const BinaryOperator *E);
6637 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006638 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00006639
John McCallb1fb0d32010-05-07 22:08:54 +00006640 bool VisitUnaryReal(const UnaryOperator *E);
6641 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00006642
Richard Smithfddd3842011-12-30 21:15:51 +00006643 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00006644};
6645} // end anonymous namespace
6646
6647static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006648 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006649 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00006650}
6651
Jay Foad39c79802011-01-12 09:06:06 +00006652static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00006653 QualType ResultTy,
6654 const Expr *Arg,
6655 bool SNaN,
6656 llvm::APFloat &Result) {
6657 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
6658 if (!S) return false;
6659
6660 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
6661
6662 llvm::APInt fill;
6663
6664 // Treat empty strings as if they were zero.
6665 if (S->getString().empty())
6666 fill = llvm::APInt(32, 0);
6667 else if (S->getString().getAsInteger(0, fill))
6668 return false;
6669
6670 if (SNaN)
6671 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
6672 else
6673 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
6674 return true;
6675}
6676
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006677bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006678 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006679 default:
6680 return ExprEvaluatorBaseTy::VisitCallExpr(E);
6681
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006682 case Builtin::BI__builtin_huge_val:
6683 case Builtin::BI__builtin_huge_valf:
6684 case Builtin::BI__builtin_huge_vall:
6685 case Builtin::BI__builtin_inf:
6686 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00006687 case Builtin::BI__builtin_infl: {
6688 const llvm::fltSemantics &Sem =
6689 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00006690 Result = llvm::APFloat::getInf(Sem);
6691 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00006692 }
Mike Stump11289f42009-09-09 15:08:12 +00006693
John McCall16291492010-02-28 13:00:19 +00006694 case Builtin::BI__builtin_nans:
6695 case Builtin::BI__builtin_nansf:
6696 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006697 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6698 true, Result))
6699 return Error(E);
6700 return true;
John McCall16291492010-02-28 13:00:19 +00006701
Chris Lattner0b7282e2008-10-06 06:31:58 +00006702 case Builtin::BI__builtin_nan:
6703 case Builtin::BI__builtin_nanf:
6704 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00006705 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00006706 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00006707 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6708 false, Result))
6709 return Error(E);
6710 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006711
6712 case Builtin::BI__builtin_fabs:
6713 case Builtin::BI__builtin_fabsf:
6714 case Builtin::BI__builtin_fabsl:
6715 if (!EvaluateFloat(E->getArg(0), Result, Info))
6716 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006717
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006718 if (Result.isNegative())
6719 Result.changeSign();
6720 return true;
6721
Mike Stump11289f42009-09-09 15:08:12 +00006722 case Builtin::BI__builtin_copysign:
6723 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006724 case Builtin::BI__builtin_copysignl: {
6725 APFloat RHS(0.);
6726 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
6727 !EvaluateFloat(E->getArg(1), RHS, Info))
6728 return false;
6729 Result.copySign(RHS);
6730 return true;
6731 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006732 }
6733}
6734
John McCallb1fb0d32010-05-07 22:08:54 +00006735bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00006736 if (E->getSubExpr()->getType()->isAnyComplexType()) {
6737 ComplexValue CV;
6738 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
6739 return false;
6740 Result = CV.FloatReal;
6741 return true;
6742 }
6743
6744 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00006745}
6746
6747bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00006748 if (E->getSubExpr()->getType()->isAnyComplexType()) {
6749 ComplexValue CV;
6750 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
6751 return false;
6752 Result = CV.FloatImag;
6753 return true;
6754 }
6755
Richard Smith4a678122011-10-24 18:44:57 +00006756 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00006757 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
6758 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00006759 return true;
6760}
6761
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006762bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006763 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006764 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006765 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00006766 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00006767 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00006768 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
6769 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006770 Result.changeSign();
6771 return true;
6772 }
6773}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006774
Eli Friedman24c01542008-08-22 00:06:13 +00006775bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006776 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
6777 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00006778
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006779 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00006780 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
6781 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00006782 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00006783 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
6784 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00006785}
6786
6787bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
6788 Result = E->getValue();
6789 return true;
6790}
6791
Peter Collingbournee9200682011-05-13 03:29:01 +00006792bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
6793 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00006794
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006795 switch (E->getCastKind()) {
6796 default:
Richard Smith11562c52011-10-28 17:51:58 +00006797 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006798
6799 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006800 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00006801 return EvaluateInteger(SubExpr, IntResult, Info) &&
6802 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
6803 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006804 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006805
6806 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006807 if (!Visit(SubExpr))
6808 return false;
Richard Smith357362d2011-12-13 06:39:58 +00006809 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
6810 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006811 }
John McCalld7646252010-11-14 08:17:51 +00006812
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006813 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00006814 ComplexValue V;
6815 if (!EvaluateComplex(SubExpr, V, Info))
6816 return false;
6817 Result = V.getComplexFloatReal();
6818 return true;
6819 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006820 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006821}
6822
Eli Friedman24c01542008-08-22 00:06:13 +00006823//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006824// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00006825//===----------------------------------------------------------------------===//
6826
6827namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006828class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00006829 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00006830 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00006831
Anders Carlsson537969c2008-11-16 20:27:53 +00006832public:
John McCall93d91dc2010-05-07 17:22:02 +00006833 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006834 : ExprEvaluatorBaseTy(info), Result(Result) {}
6835
Richard Smith2e312c82012-03-03 22:46:17 +00006836 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006837 Result.setFrom(V);
6838 return true;
6839 }
Mike Stump11289f42009-09-09 15:08:12 +00006840
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006841 bool ZeroInitialization(const Expr *E);
6842
Anders Carlsson537969c2008-11-16 20:27:53 +00006843 //===--------------------------------------------------------------------===//
6844 // Visitor Methods
6845 //===--------------------------------------------------------------------===//
6846
Peter Collingbournee9200682011-05-13 03:29:01 +00006847 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006848 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00006849 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006850 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006851 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00006852};
6853} // end anonymous namespace
6854
John McCall93d91dc2010-05-07 17:22:02 +00006855static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
6856 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006857 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006858 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00006859}
6860
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006861bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00006862 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006863 if (ElemTy->isRealFloatingType()) {
6864 Result.makeComplexFloat();
6865 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
6866 Result.FloatReal = Zero;
6867 Result.FloatImag = Zero;
6868 } else {
6869 Result.makeComplexInt();
6870 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
6871 Result.IntReal = Zero;
6872 Result.IntImag = Zero;
6873 }
6874 return true;
6875}
6876
Peter Collingbournee9200682011-05-13 03:29:01 +00006877bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
6878 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006879
6880 if (SubExpr->getType()->isRealFloatingType()) {
6881 Result.makeComplexFloat();
6882 APFloat &Imag = Result.FloatImag;
6883 if (!EvaluateFloat(SubExpr, Imag, Info))
6884 return false;
6885
6886 Result.FloatReal = APFloat(Imag.getSemantics());
6887 return true;
6888 } else {
6889 assert(SubExpr->getType()->isIntegerType() &&
6890 "Unexpected imaginary literal.");
6891
6892 Result.makeComplexInt();
6893 APSInt &Imag = Result.IntImag;
6894 if (!EvaluateInteger(SubExpr, Imag, Info))
6895 return false;
6896
6897 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
6898 return true;
6899 }
6900}
6901
Peter Collingbournee9200682011-05-13 03:29:01 +00006902bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006903
John McCallfcef3cf2010-12-14 17:51:41 +00006904 switch (E->getCastKind()) {
6905 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006906 case CK_BaseToDerived:
6907 case CK_DerivedToBase:
6908 case CK_UncheckedDerivedToBase:
6909 case CK_Dynamic:
6910 case CK_ToUnion:
6911 case CK_ArrayToPointerDecay:
6912 case CK_FunctionToPointerDecay:
6913 case CK_NullToPointer:
6914 case CK_NullToMemberPointer:
6915 case CK_BaseToDerivedMemberPointer:
6916 case CK_DerivedToBaseMemberPointer:
6917 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00006918 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00006919 case CK_ConstructorConversion:
6920 case CK_IntegralToPointer:
6921 case CK_PointerToIntegral:
6922 case CK_PointerToBoolean:
6923 case CK_ToVoid:
6924 case CK_VectorSplat:
6925 case CK_IntegralCast:
6926 case CK_IntegralToBoolean:
6927 case CK_IntegralToFloating:
6928 case CK_FloatingToIntegral:
6929 case CK_FloatingToBoolean:
6930 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00006931 case CK_CPointerToObjCPointerCast:
6932 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006933 case CK_AnyPointerToBlockPointerCast:
6934 case CK_ObjCObjectLValueCast:
6935 case CK_FloatingComplexToReal:
6936 case CK_FloatingComplexToBoolean:
6937 case CK_IntegralComplexToReal:
6938 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00006939 case CK_ARCProduceObject:
6940 case CK_ARCConsumeObject:
6941 case CK_ARCReclaimReturnedObject:
6942 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00006943 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00006944 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006945 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00006946 case CK_NonAtomicToAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00006947 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00006948
John McCallfcef3cf2010-12-14 17:51:41 +00006949 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006950 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00006951 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00006952 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00006953
6954 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006955 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006956 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006957 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00006958
6959 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006960 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00006961 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006962 return false;
6963
John McCallfcef3cf2010-12-14 17:51:41 +00006964 Result.makeComplexFloat();
6965 Result.FloatImag = APFloat(Real.getSemantics());
6966 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006967 }
6968
John McCallfcef3cf2010-12-14 17:51:41 +00006969 case CK_FloatingComplexCast: {
6970 if (!Visit(E->getSubExpr()))
6971 return false;
6972
6973 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6974 QualType From
6975 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6976
Richard Smith357362d2011-12-13 06:39:58 +00006977 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
6978 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006979 }
6980
6981 case CK_FloatingComplexToIntegralComplex: {
6982 if (!Visit(E->getSubExpr()))
6983 return false;
6984
6985 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6986 QualType From
6987 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6988 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00006989 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
6990 To, Result.IntReal) &&
6991 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
6992 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006993 }
6994
6995 case CK_IntegralRealToComplex: {
6996 APSInt &Real = Result.IntReal;
6997 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
6998 return false;
6999
7000 Result.makeComplexInt();
7001 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
7002 return true;
7003 }
7004
7005 case CK_IntegralComplexCast: {
7006 if (!Visit(E->getSubExpr()))
7007 return false;
7008
7009 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7010 QualType From
7011 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7012
Richard Smith911e1422012-01-30 22:27:01 +00007013 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7014 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007015 return true;
7016 }
7017
7018 case CK_IntegralComplexToFloatingComplex: {
7019 if (!Visit(E->getSubExpr()))
7020 return false;
7021
Ted Kremenek28831752012-08-23 20:46:57 +00007022 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007023 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00007024 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007025 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00007026 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7027 To, Result.FloatReal) &&
7028 HandleIntToFloatCast(Info, E, From, Result.IntImag,
7029 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007030 }
7031 }
7032
7033 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007034}
7035
John McCall93d91dc2010-05-07 17:22:02 +00007036bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007037 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00007038 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7039
Richard Smith253c2a32012-01-27 01:14:48 +00007040 bool LHSOK = Visit(E->getLHS());
7041 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00007042 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007043
John McCall93d91dc2010-05-07 17:22:02 +00007044 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00007045 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00007046 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007047
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007048 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
7049 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007050 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007051 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007052 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007053 if (Result.isComplexFloat()) {
7054 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
7055 APFloat::rmNearestTiesToEven);
7056 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
7057 APFloat::rmNearestTiesToEven);
7058 } else {
7059 Result.getComplexIntReal() += RHS.getComplexIntReal();
7060 Result.getComplexIntImag() += RHS.getComplexIntImag();
7061 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007062 break;
John McCalle3027922010-08-25 11:45:40 +00007063 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007064 if (Result.isComplexFloat()) {
7065 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
7066 APFloat::rmNearestTiesToEven);
7067 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
7068 APFloat::rmNearestTiesToEven);
7069 } else {
7070 Result.getComplexIntReal() -= RHS.getComplexIntReal();
7071 Result.getComplexIntImag() -= RHS.getComplexIntImag();
7072 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007073 break;
John McCalle3027922010-08-25 11:45:40 +00007074 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007075 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00007076 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007077 APFloat &LHS_r = LHS.getComplexFloatReal();
7078 APFloat &LHS_i = LHS.getComplexFloatImag();
7079 APFloat &RHS_r = RHS.getComplexFloatReal();
7080 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00007081
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007082 APFloat Tmp = LHS_r;
7083 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7084 Result.getComplexFloatReal() = Tmp;
7085 Tmp = LHS_i;
7086 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7087 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
7088
7089 Tmp = LHS_r;
7090 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7091 Result.getComplexFloatImag() = Tmp;
7092 Tmp = LHS_i;
7093 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7094 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
7095 } else {
John McCall93d91dc2010-05-07 17:22:02 +00007096 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00007097 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007098 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
7099 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00007100 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007101 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
7102 LHS.getComplexIntImag() * RHS.getComplexIntReal());
7103 }
7104 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007105 case BO_Div:
7106 if (Result.isComplexFloat()) {
7107 ComplexValue LHS = Result;
7108 APFloat &LHS_r = LHS.getComplexFloatReal();
7109 APFloat &LHS_i = LHS.getComplexFloatImag();
7110 APFloat &RHS_r = RHS.getComplexFloatReal();
7111 APFloat &RHS_i = RHS.getComplexFloatImag();
7112 APFloat &Res_r = Result.getComplexFloatReal();
7113 APFloat &Res_i = Result.getComplexFloatImag();
7114
7115 APFloat Den = RHS_r;
7116 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7117 APFloat Tmp = RHS_i;
7118 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7119 Den.add(Tmp, APFloat::rmNearestTiesToEven);
7120
7121 Res_r = LHS_r;
7122 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7123 Tmp = LHS_i;
7124 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7125 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
7126 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
7127
7128 Res_i = LHS_i;
7129 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7130 Tmp = LHS_r;
7131 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7132 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
7133 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
7134 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007135 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
7136 return Error(E, diag::note_expr_divide_by_zero);
7137
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007138 ComplexValue LHS = Result;
7139 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
7140 RHS.getComplexIntImag() * RHS.getComplexIntImag();
7141 Result.getComplexIntReal() =
7142 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
7143 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
7144 Result.getComplexIntImag() =
7145 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
7146 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
7147 }
7148 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007149 }
7150
John McCall93d91dc2010-05-07 17:22:02 +00007151 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007152}
7153
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007154bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7155 // Get the operand value into 'Result'.
7156 if (!Visit(E->getSubExpr()))
7157 return false;
7158
7159 switch (E->getOpcode()) {
7160 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007161 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007162 case UO_Extension:
7163 return true;
7164 case UO_Plus:
7165 // The result is always just the subexpr.
7166 return true;
7167 case UO_Minus:
7168 if (Result.isComplexFloat()) {
7169 Result.getComplexFloatReal().changeSign();
7170 Result.getComplexFloatImag().changeSign();
7171 }
7172 else {
7173 Result.getComplexIntReal() = -Result.getComplexIntReal();
7174 Result.getComplexIntImag() = -Result.getComplexIntImag();
7175 }
7176 return true;
7177 case UO_Not:
7178 if (Result.isComplexFloat())
7179 Result.getComplexFloatImag().changeSign();
7180 else
7181 Result.getComplexIntImag() = -Result.getComplexIntImag();
7182 return true;
7183 }
7184}
7185
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007186bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7187 if (E->getNumInits() == 2) {
7188 if (E->getType()->isComplexType()) {
7189 Result.makeComplexFloat();
7190 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
7191 return false;
7192 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
7193 return false;
7194 } else {
7195 Result.makeComplexInt();
7196 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
7197 return false;
7198 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
7199 return false;
7200 }
7201 return true;
7202 }
7203 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
7204}
7205
Anders Carlsson537969c2008-11-16 20:27:53 +00007206//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00007207// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
7208// implicit conversion.
7209//===----------------------------------------------------------------------===//
7210
7211namespace {
7212class AtomicExprEvaluator :
7213 public ExprEvaluatorBase<AtomicExprEvaluator, bool> {
7214 APValue &Result;
7215public:
7216 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
7217 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7218
7219 bool Success(const APValue &V, const Expr *E) {
7220 Result = V;
7221 return true;
7222 }
7223
7224 bool ZeroInitialization(const Expr *E) {
7225 ImplicitValueInitExpr VIE(
7226 E->getType()->castAs<AtomicType>()->getValueType());
7227 return Evaluate(Result, Info, &VIE);
7228 }
7229
7230 bool VisitCastExpr(const CastExpr *E) {
7231 switch (E->getCastKind()) {
7232 default:
7233 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7234 case CK_NonAtomicToAtomic:
7235 return Evaluate(Result, Info, E->getSubExpr());
7236 }
7237 }
7238};
7239} // end anonymous namespace
7240
7241static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
7242 assert(E->isRValue() && E->getType()->isAtomicType());
7243 return AtomicExprEvaluator(Info, Result).Visit(E);
7244}
7245
7246//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00007247// Void expression evaluation, primarily for a cast to void on the LHS of a
7248// comma operator
7249//===----------------------------------------------------------------------===//
7250
7251namespace {
7252class VoidExprEvaluator
7253 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
7254public:
7255 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
7256
Richard Smith2e312c82012-03-03 22:46:17 +00007257 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00007258
7259 bool VisitCastExpr(const CastExpr *E) {
7260 switch (E->getCastKind()) {
7261 default:
7262 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7263 case CK_ToVoid:
7264 VisitIgnoredValue(E->getSubExpr());
7265 return true;
7266 }
7267 }
7268};
7269} // end anonymous namespace
7270
7271static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
7272 assert(E->isRValue() && E->getType()->isVoidType());
7273 return VoidExprEvaluator(Info).Visit(E);
7274}
7275
7276//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00007277// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00007278//===----------------------------------------------------------------------===//
7279
Richard Smith2e312c82012-03-03 22:46:17 +00007280static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007281 // In C, function designators are not lvalues, but we evaluate them as if they
7282 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00007283 QualType T = E->getType();
7284 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00007285 LValue LV;
7286 if (!EvaluateLValue(E, LV, Info))
7287 return false;
7288 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007289 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007290 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007291 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007292 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007293 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007294 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007295 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00007296 LValue LV;
7297 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007298 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007299 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007300 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00007301 llvm::APFloat F(0.0);
7302 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007303 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007304 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00007305 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00007306 ComplexValue C;
7307 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007308 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007309 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007310 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00007311 MemberPtr P;
7312 if (!EvaluateMemberPointer(E, P, Info))
7313 return false;
7314 P.moveInto(Result);
7315 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00007316 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007317 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007318 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00007319 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00007320 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007321 Result = Info.CurrentCall->Temporaries[E];
Richard Smitha23ab512013-05-23 00:30:41 +00007322 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007323 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007324 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00007325 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
7326 return false;
7327 Result = Info.CurrentCall->Temporaries[E];
Richard Smitha23ab512013-05-23 00:30:41 +00007328 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007329 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007330 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00007331 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00007332 if (!EvaluateVoid(E, Info))
7333 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007334 } else if (T->isAtomicType()) {
7335 if (!EvaluateAtomic(E, Result, Info))
7336 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007337 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007338 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00007339 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007340 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007341 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00007342 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007343 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007344
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00007345 return true;
7346}
7347
Richard Smithb228a862012-02-15 02:18:13 +00007348/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
7349/// cases, the in-place evaluation is essential, since later initializers for
7350/// an object can indirectly refer to subobjects which were initialized earlier.
7351static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00007352 const Expr *E, bool AllowNonLiteralTypes) {
7353 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00007354 return false;
7355
7356 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00007357 // Evaluate arrays and record types in-place, so that later initializers can
7358 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00007359 if (E->getType()->isArrayType())
7360 return EvaluateArray(E, This, Result, Info);
7361 else if (E->getType()->isRecordType())
7362 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00007363 }
7364
7365 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00007366 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00007367}
7368
Richard Smithf57d8cb2011-12-09 22:58:01 +00007369/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
7370/// lvalue-to-rvalue cast if it is an lvalue.
7371static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00007372 if (!CheckLiteralType(Info, E))
7373 return false;
7374
Richard Smith2e312c82012-03-03 22:46:17 +00007375 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007376 return false;
7377
7378 if (E->isGLValue()) {
7379 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00007380 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00007381 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007382 return false;
7383 }
7384
Richard Smith2e312c82012-03-03 22:46:17 +00007385 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00007386 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007387}
Richard Smith11562c52011-10-28 17:51:58 +00007388
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007389static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
7390 const ASTContext &Ctx, bool &IsConst) {
7391 // Fast-path evaluations of integer literals, since we sometimes see files
7392 // containing vast quantities of these.
7393 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
7394 Result.Val = APValue(APSInt(L->getValue(),
7395 L->getType()->isUnsignedIntegerType()));
7396 IsConst = true;
7397 return true;
7398 }
7399
7400 // FIXME: Evaluating values of large array and record types can cause
7401 // performance problems. Only do so in C++11 for now.
7402 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
7403 Exp->getType()->isRecordType()) &&
7404 !Ctx.getLangOpts().CPlusPlus11) {
7405 IsConst = false;
7406 return true;
7407 }
7408 return false;
7409}
7410
7411
Richard Smith7b553f12011-10-29 00:50:52 +00007412/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00007413/// any crazy technique (that has nothing to do with language standards) that
7414/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00007415/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
7416/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00007417bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007418 bool IsConst;
7419 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
7420 return IsConst;
7421
Richard Smithf57d8cb2011-12-09 22:58:01 +00007422 EvalInfo Info(Ctx, Result);
7423 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00007424}
7425
Jay Foad39c79802011-01-12 09:06:06 +00007426bool Expr::EvaluateAsBooleanCondition(bool &Result,
7427 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00007428 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00007429 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00007430 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00007431}
7432
Richard Smith5fab0c92011-12-28 19:48:30 +00007433bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
7434 SideEffectsKind AllowSideEffects) const {
7435 if (!getType()->isIntegralOrEnumerationType())
7436 return false;
7437
Richard Smith11562c52011-10-28 17:51:58 +00007438 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00007439 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
7440 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00007441 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007442
Richard Smith11562c52011-10-28 17:51:58 +00007443 Result = ExprResult.Val.getInt();
7444 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00007445}
7446
Jay Foad39c79802011-01-12 09:06:06 +00007447bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00007448 EvalInfo Info(Ctx, Result);
7449
John McCall45d55e42010-05-07 21:00:08 +00007450 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007451 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
7452 !CheckLValueConstantExpression(Info, getExprLoc(),
7453 Ctx.getLValueReferenceType(getType()), LV))
7454 return false;
7455
Richard Smith2e312c82012-03-03 22:46:17 +00007456 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00007457 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00007458}
7459
Richard Smithd0b4dd62011-12-19 06:19:21 +00007460bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
7461 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007462 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00007463 // FIXME: Evaluating initializers for large array and record types can cause
7464 // performance problems. Only do so in C++11 for now.
7465 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007466 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00007467 return false;
7468
Richard Smithd0b4dd62011-12-19 06:19:21 +00007469 Expr::EvalStatus EStatus;
7470 EStatus.Diag = &Notes;
7471
7472 EvalInfo InitInfo(Ctx, EStatus);
7473 InitInfo.setEvaluatingDecl(VD, Value);
7474
7475 LValue LVal;
7476 LVal.set(VD);
7477
Richard Smithfddd3842011-12-30 21:15:51 +00007478 // C++11 [basic.start.init]p2:
7479 // Variables with static storage duration or thread storage duration shall be
7480 // zero-initialized before any other initialization takes place.
7481 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007482 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00007483 !VD->getType()->isReferenceType()) {
7484 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00007485 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00007486 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00007487 return false;
7488 }
7489
Richard Smith7525ff62013-05-09 07:14:00 +00007490 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
7491 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00007492 EStatus.HasSideEffects)
7493 return false;
7494
7495 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
7496 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00007497}
7498
Richard Smith7b553f12011-10-29 00:50:52 +00007499/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
7500/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00007501bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00007502 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00007503 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00007504}
Anders Carlsson59689ed2008-11-22 21:04:56 +00007505
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007506APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007507 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007508 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007509 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00007510 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00007511 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00007512 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007513 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00007514
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007515 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00007516}
John McCall864e3962010-05-07 05:32:02 +00007517
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007518void Expr::EvaluateForOverflow(const ASTContext &Ctx,
7519 SmallVectorImpl<PartialDiagnosticAt> *Diags) const {
7520 bool IsConst;
7521 EvalResult EvalResult;
7522 EvalResult.Diag = Diags;
7523 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
7524 EvalInfo Info(Ctx, EvalResult, true);
7525 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
7526 }
7527}
7528
Abramo Bagnaraf8199452010-05-14 17:07:14 +00007529 bool Expr::EvalResult::isGlobalLValue() const {
7530 assert(Val.isLValue());
7531 return IsGlobalLValue(Val.getLValueBase());
7532 }
7533
7534
John McCall864e3962010-05-07 05:32:02 +00007535/// isIntegerConstantExpr - this recursive routine will test if an expression is
7536/// an integer constant expression.
7537
7538/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
7539/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00007540
7541// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00007542// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
7543// and a (possibly null) SourceLocation indicating the location of the problem.
7544//
John McCall864e3962010-05-07 05:32:02 +00007545// Note that to reduce code duplication, this helper does no evaluation
7546// itself; the caller checks whether the expression is evaluatable, and
7547// in the rare cases where CheckICE actually cares about the evaluated
7548// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00007549
Dan Gohman28ade552010-07-26 21:25:24 +00007550namespace {
7551
Richard Smith9e575da2012-12-28 13:25:52 +00007552enum ICEKind {
7553 /// This expression is an ICE.
7554 IK_ICE,
7555 /// This expression is not an ICE, but if it isn't evaluated, it's
7556 /// a legal subexpression for an ICE. This return value is used to handle
7557 /// the comma operator in C99 mode, and non-constant subexpressions.
7558 IK_ICEIfUnevaluated,
7559 /// This expression is not an ICE, and is not a legal subexpression for one.
7560 IK_NotICE
7561};
7562
John McCall864e3962010-05-07 05:32:02 +00007563struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00007564 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00007565 SourceLocation Loc;
7566
Richard Smith9e575da2012-12-28 13:25:52 +00007567 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00007568};
7569
Dan Gohman28ade552010-07-26 21:25:24 +00007570}
7571
Richard Smith9e575da2012-12-28 13:25:52 +00007572static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
7573
7574static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00007575
7576static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
7577 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00007578 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00007579 !EVResult.Val.isInt())
7580 return ICEDiag(IK_NotICE, E->getLocStart());
7581
John McCall864e3962010-05-07 05:32:02 +00007582 return NoDiag();
7583}
7584
7585static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
7586 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00007587 if (!E->getType()->isIntegralOrEnumerationType())
7588 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007589
7590 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00007591#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00007592#define STMT(Node, Base) case Expr::Node##Class:
7593#define EXPR(Node, Base)
7594#include "clang/AST/StmtNodes.inc"
7595 case Expr::PredefinedExprClass:
7596 case Expr::FloatingLiteralClass:
7597 case Expr::ImaginaryLiteralClass:
7598 case Expr::StringLiteralClass:
7599 case Expr::ArraySubscriptExprClass:
7600 case Expr::MemberExprClass:
7601 case Expr::CompoundAssignOperatorClass:
7602 case Expr::CompoundLiteralExprClass:
7603 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00007604 case Expr::DesignatedInitExprClass:
7605 case Expr::ImplicitValueInitExprClass:
7606 case Expr::ParenListExprClass:
7607 case Expr::VAArgExprClass:
7608 case Expr::AddrLabelExprClass:
7609 case Expr::StmtExprClass:
7610 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00007611 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00007612 case Expr::CXXDynamicCastExprClass:
7613 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00007614 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00007615 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00007616 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00007617 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00007618 case Expr::CXXThisExprClass:
7619 case Expr::CXXThrowExprClass:
7620 case Expr::CXXNewExprClass:
7621 case Expr::CXXDeleteExprClass:
7622 case Expr::CXXPseudoDestructorExprClass:
7623 case Expr::UnresolvedLookupExprClass:
7624 case Expr::DependentScopeDeclRefExprClass:
7625 case Expr::CXXConstructExprClass:
7626 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00007627 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00007628 case Expr::CXXTemporaryObjectExprClass:
7629 case Expr::CXXUnresolvedConstructExprClass:
7630 case Expr::CXXDependentScopeMemberExprClass:
7631 case Expr::UnresolvedMemberExprClass:
7632 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00007633 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007634 case Expr::ObjCArrayLiteralClass:
7635 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00007636 case Expr::ObjCEncodeExprClass:
7637 case Expr::ObjCMessageExprClass:
7638 case Expr::ObjCSelectorExprClass:
7639 case Expr::ObjCProtocolExprClass:
7640 case Expr::ObjCIvarRefExprClass:
7641 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007642 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00007643 case Expr::ObjCIsaExprClass:
7644 case Expr::ShuffleVectorExprClass:
7645 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00007646 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00007647 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00007648 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00007649 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00007650 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00007651 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00007652 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00007653 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00007654 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00007655 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00007656 case Expr::InitListExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00007657 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00007658 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00007659
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007660 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00007661 case Expr::GNUNullExprClass:
7662 // GCC considers the GNU __null value to be an integral constant expression.
7663 return NoDiag();
7664
John McCall7c454bb2011-07-15 05:09:51 +00007665 case Expr::SubstNonTypeTemplateParmExprClass:
7666 return
7667 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
7668
John McCall864e3962010-05-07 05:32:02 +00007669 case Expr::ParenExprClass:
7670 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00007671 case Expr::GenericSelectionExprClass:
7672 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007673 case Expr::IntegerLiteralClass:
7674 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007675 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00007676 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00007677 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00007678 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00007679 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00007680 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00007681 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00007682 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007683 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00007684 return NoDiag();
7685 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00007686 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00007687 // C99 6.6/3 allows function calls within unevaluated subexpressions of
7688 // constant expressions, but they can never be ICEs because an ICE cannot
7689 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00007690 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00007691 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00007692 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007693 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007694 }
Richard Smith6365c912012-02-24 22:12:32 +00007695 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00007696 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
7697 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00007698 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00007699 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00007700 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00007701 // Parameter variables are never constants. Without this check,
7702 // getAnyInitializer() can find a default argument, which leads
7703 // to chaos.
7704 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00007705 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00007706
7707 // C++ 7.1.5.1p2
7708 // A variable of non-volatile const-qualified integral or enumeration
7709 // type initialized by an ICE can be used in ICEs.
7710 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00007711 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00007712 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00007713
Richard Smithd0b4dd62011-12-19 06:19:21 +00007714 const VarDecl *VD;
7715 // Look for a declaration of this variable that has an initializer, and
7716 // check whether it is an ICE.
7717 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
7718 return NoDiag();
7719 else
Richard Smith9e575da2012-12-28 13:25:52 +00007720 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00007721 }
7722 }
Richard Smith9e575da2012-12-28 13:25:52 +00007723 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00007724 }
John McCall864e3962010-05-07 05:32:02 +00007725 case Expr::UnaryOperatorClass: {
7726 const UnaryOperator *Exp = cast<UnaryOperator>(E);
7727 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007728 case UO_PostInc:
7729 case UO_PostDec:
7730 case UO_PreInc:
7731 case UO_PreDec:
7732 case UO_AddrOf:
7733 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00007734 // C99 6.6/3 allows increment and decrement within unevaluated
7735 // subexpressions of constant expressions, but they can never be ICEs
7736 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00007737 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00007738 case UO_Extension:
7739 case UO_LNot:
7740 case UO_Plus:
7741 case UO_Minus:
7742 case UO_Not:
7743 case UO_Real:
7744 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00007745 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007746 }
Richard Smith9e575da2012-12-28 13:25:52 +00007747
John McCall864e3962010-05-07 05:32:02 +00007748 // OffsetOf falls through here.
7749 }
7750 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00007751 // Note that per C99, offsetof must be an ICE. And AFAIK, using
7752 // EvaluateAsRValue matches the proposed gcc behavior for cases like
7753 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
7754 // compliance: we should warn earlier for offsetof expressions with
7755 // array subscripts that aren't ICEs, and if the array subscripts
7756 // are ICEs, the value of the offsetof must be an integer constant.
7757 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00007758 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00007759 case Expr::UnaryExprOrTypeTraitExprClass: {
7760 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
7761 if ((Exp->getKind() == UETT_SizeOf) &&
7762 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00007763 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007764 return NoDiag();
7765 }
7766 case Expr::BinaryOperatorClass: {
7767 const BinaryOperator *Exp = cast<BinaryOperator>(E);
7768 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007769 case BO_PtrMemD:
7770 case BO_PtrMemI:
7771 case BO_Assign:
7772 case BO_MulAssign:
7773 case BO_DivAssign:
7774 case BO_RemAssign:
7775 case BO_AddAssign:
7776 case BO_SubAssign:
7777 case BO_ShlAssign:
7778 case BO_ShrAssign:
7779 case BO_AndAssign:
7780 case BO_XorAssign:
7781 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00007782 // C99 6.6/3 allows assignments within unevaluated subexpressions of
7783 // constant expressions, but they can never be ICEs because an ICE cannot
7784 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00007785 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007786
John McCalle3027922010-08-25 11:45:40 +00007787 case BO_Mul:
7788 case BO_Div:
7789 case BO_Rem:
7790 case BO_Add:
7791 case BO_Sub:
7792 case BO_Shl:
7793 case BO_Shr:
7794 case BO_LT:
7795 case BO_GT:
7796 case BO_LE:
7797 case BO_GE:
7798 case BO_EQ:
7799 case BO_NE:
7800 case BO_And:
7801 case BO_Xor:
7802 case BO_Or:
7803 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00007804 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
7805 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00007806 if (Exp->getOpcode() == BO_Div ||
7807 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00007808 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00007809 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00007810 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00007811 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00007812 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00007813 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007814 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00007815 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00007816 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00007817 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007818 }
7819 }
7820 }
John McCalle3027922010-08-25 11:45:40 +00007821 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007822 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00007823 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
7824 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00007825 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
7826 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007827 } else {
7828 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00007829 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007830 }
7831 }
Richard Smith9e575da2012-12-28 13:25:52 +00007832 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00007833 }
John McCalle3027922010-08-25 11:45:40 +00007834 case BO_LAnd:
7835 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00007836 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
7837 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007838 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00007839 // Rare case where the RHS has a comma "side-effect"; we need
7840 // to actually check the condition to see whether the side
7841 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00007842 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00007843 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00007844 return RHSResult;
7845 return NoDiag();
7846 }
7847
Richard Smith9e575da2012-12-28 13:25:52 +00007848 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00007849 }
7850 }
7851 }
7852 case Expr::ImplicitCastExprClass:
7853 case Expr::CStyleCastExprClass:
7854 case Expr::CXXFunctionalCastExprClass:
7855 case Expr::CXXStaticCastExprClass:
7856 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00007857 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007858 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00007859 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00007860 if (isa<ExplicitCastExpr>(E)) {
7861 if (const FloatingLiteral *FL
7862 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
7863 unsigned DestWidth = Ctx.getIntWidth(E->getType());
7864 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
7865 APSInt IgnoredVal(DestWidth, !DestSigned);
7866 bool Ignored;
7867 // If the value does not fit in the destination type, the behavior is
7868 // undefined, so we are not required to treat it as a constant
7869 // expression.
7870 if (FL->getValue().convertToInteger(IgnoredVal,
7871 llvm::APFloat::rmTowardZero,
7872 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00007873 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00007874 return NoDiag();
7875 }
7876 }
Eli Friedman76d4e432011-09-29 21:49:34 +00007877 switch (cast<CastExpr>(E)->getCastKind()) {
7878 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007879 case CK_AtomicToNonAtomic:
7880 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00007881 case CK_NoOp:
7882 case CK_IntegralToBoolean:
7883 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00007884 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00007885 default:
Richard Smith9e575da2012-12-28 13:25:52 +00007886 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00007887 }
John McCall864e3962010-05-07 05:32:02 +00007888 }
John McCallc07a0c72011-02-17 10:25:35 +00007889 case Expr::BinaryConditionalOperatorClass: {
7890 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
7891 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007892 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00007893 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007894 if (FalseResult.Kind == IK_NotICE) return FalseResult;
7895 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
7896 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00007897 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00007898 return FalseResult;
7899 }
John McCall864e3962010-05-07 05:32:02 +00007900 case Expr::ConditionalOperatorClass: {
7901 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
7902 // If the condition (ignoring parens) is a __builtin_constant_p call,
7903 // then only the true side is actually considered in an integer constant
7904 // expression, and it is fully evaluated. This is an important GNU
7905 // extension. See GCC PR38377 for discussion.
7906 if (const CallExpr *CallCE
7907 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00007908 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
7909 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00007910 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007911 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007912 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007913
Richard Smithf57d8cb2011-12-09 22:58:01 +00007914 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
7915 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007916
Richard Smith9e575da2012-12-28 13:25:52 +00007917 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007918 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007919 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007920 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007921 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00007922 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007923 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00007924 return NoDiag();
7925 // Rare case where the diagnostics depend on which side is evaluated
7926 // Note that if we get here, CondResult is 0, and at least one of
7927 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00007928 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00007929 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00007930 return TrueResult;
7931 }
7932 case Expr::CXXDefaultArgExprClass:
7933 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00007934 case Expr::CXXDefaultInitExprClass:
7935 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007936 case Expr::ChooseExprClass: {
7937 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
7938 }
7939 }
7940
David Blaikiee4d798f2012-01-20 21:50:17 +00007941 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00007942}
7943
Richard Smithf57d8cb2011-12-09 22:58:01 +00007944/// Evaluate an expression as a C++11 integral constant expression.
7945static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
7946 const Expr *E,
7947 llvm::APSInt *Value,
7948 SourceLocation *Loc) {
7949 if (!E->getType()->isIntegralOrEnumerationType()) {
7950 if (Loc) *Loc = E->getExprLoc();
7951 return false;
7952 }
7953
Richard Smith66e05fe2012-01-18 05:21:49 +00007954 APValue Result;
7955 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00007956 return false;
7957
Richard Smith66e05fe2012-01-18 05:21:49 +00007958 assert(Result.isInt() && "pointer cast to int is not an ICE");
7959 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00007960 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007961}
7962
Richard Smith92b1ce02011-12-12 09:28:41 +00007963bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007964 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007965 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
7966
Richard Smith9e575da2012-12-28 13:25:52 +00007967 ICEDiag D = CheckICE(this, Ctx);
7968 if (D.Kind != IK_ICE) {
7969 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00007970 return false;
7971 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007972 return true;
7973}
7974
7975bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
7976 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007977 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007978 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
7979
7980 if (!isIntegerConstantExpr(Ctx, Loc))
7981 return false;
7982 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00007983 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00007984 return true;
7985}
Richard Smith66e05fe2012-01-18 05:21:49 +00007986
Richard Smith98a0a492012-02-14 21:38:30 +00007987bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00007988 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00007989}
7990
Richard Smith66e05fe2012-01-18 05:21:49 +00007991bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
7992 SourceLocation *Loc) const {
7993 // We support this checking in C++98 mode in order to diagnose compatibility
7994 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007995 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00007996
Richard Smith98a0a492012-02-14 21:38:30 +00007997 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00007998 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007999 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00008000 Status.Diag = &Diags;
8001 EvalInfo Info(Ctx, Status);
8002
8003 APValue Scratch;
8004 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
8005
8006 if (!Diags.empty()) {
8007 IsConstExpr = false;
8008 if (Loc) *Loc = Diags[0].first;
8009 } else if (!IsConstExpr) {
8010 // FIXME: This shouldn't happen.
8011 if (Loc) *Loc = getExprLoc();
8012 }
8013
8014 return IsConstExpr;
8015}
Richard Smith253c2a32012-01-27 01:14:48 +00008016
8017bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008018 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00008019 PartialDiagnosticAt> &Diags) {
8020 // FIXME: It would be useful to check constexpr function templates, but at the
8021 // moment the constant expression evaluator cannot cope with the non-rigorous
8022 // ASTs which we build for dependent expressions.
8023 if (FD->isDependentContext())
8024 return true;
8025
8026 Expr::EvalStatus Status;
8027 Status.Diag = &Diags;
8028
8029 EvalInfo Info(FD->getASTContext(), Status);
8030 Info.CheckingPotentialConstantExpression = true;
8031
8032 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8033 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
8034
Richard Smith7525ff62013-05-09 07:14:00 +00008035 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00008036 // is a temporary being used as the 'this' pointer.
8037 LValue This;
8038 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00008039 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00008040
Richard Smith253c2a32012-01-27 01:14:48 +00008041 ArrayRef<const Expr*> Args;
8042
8043 SourceLocation Loc = FD->getLocation();
8044
Richard Smith2e312c82012-03-03 22:46:17 +00008045 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00008046 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
8047 // Evaluate the call as a constant initializer, to allow the construction
8048 // of objects of non-literal types.
8049 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00008050 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00008051 } else
Richard Smith253c2a32012-01-27 01:14:48 +00008052 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
8053 Args, FD->getBody(), Info, Scratch);
8054
8055 return Diags.empty();
8056}