blob: 67c187c039b1ef59e45c56fec0f80b48c63fe49d [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();
Richard Smith84401042013-06-03 05:03:02 +000066
67 const Expr *Base = B.get<const Expr*>();
68
69 // For a materialized temporary, the type of the temporary we materialized
70 // may not be the type of the expression.
71 if (const MaterializeTemporaryExpr *MTE =
72 dyn_cast<MaterializeTemporaryExpr>(Base)) {
73 SmallVector<const Expr *, 2> CommaLHSs;
74 SmallVector<SubobjectAdjustment, 2> Adjustments;
75 const Expr *Temp = MTE->GetTemporaryExpr();
76 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
77 Adjustments);
78 // Keep any cv-qualifiers from the reference if we generated a temporary
79 // for it.
80 if (Inner != Temp)
81 return Inner->getType();
82 }
83
84 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +000085 }
86
Richard Smithd62306a2011-11-10 06:34:14 +000087 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000088 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000089 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000090 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000091 APValue::BaseOrMemberType Value;
92 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +000093 return Value;
94 }
95
96 /// Get an LValue path entry, which is known to not be an array index, as a
97 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +000098 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000099 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000100 }
101 /// Get an LValue path entry, which is known to not be an array index, as a
102 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000103 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000104 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000105 }
106 /// Determine whether this LValue path entry for a base class names a virtual
107 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000108 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000109 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000110 }
111
Richard Smitha8105bc2012-01-06 16:39:00 +0000112 /// Find the path length and type of the most-derived subobject in the given
113 /// path, and find the size of the containing array, if any.
114 static
115 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
116 ArrayRef<APValue::LValuePathEntry> Path,
117 uint64_t &ArraySize, QualType &Type) {
118 unsigned MostDerivedLength = 0;
119 Type = Base;
Richard Smith80815602011-11-07 05:07:52 +0000120 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000121 if (Type->isArrayType()) {
122 const ConstantArrayType *CAT =
123 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
124 Type = CAT->getElementType();
125 ArraySize = CAT->getSize().getZExtValue();
126 MostDerivedLength = I + 1;
Richard Smith66c96992012-02-18 22:04:06 +0000127 } else if (Type->isAnyComplexType()) {
128 const ComplexType *CT = Type->castAs<ComplexType>();
129 Type = CT->getElementType();
130 ArraySize = 2;
131 MostDerivedLength = I + 1;
Richard Smitha8105bc2012-01-06 16:39:00 +0000132 } else if (const FieldDecl *FD = getAsField(Path[I])) {
133 Type = FD->getType();
134 ArraySize = 0;
135 MostDerivedLength = I + 1;
136 } else {
Richard Smith80815602011-11-07 05:07:52 +0000137 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000138 ArraySize = 0;
139 }
Richard Smith80815602011-11-07 05:07:52 +0000140 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000141 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000142 }
143
Richard Smitha8105bc2012-01-06 16:39:00 +0000144 // The order of this enum is important for diagnostics.
145 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000146 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000147 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000148 };
149
Richard Smith96e0c102011-11-04 02:25:55 +0000150 /// A path from a glvalue to a subobject of that glvalue.
151 struct SubobjectDesignator {
152 /// True if the subobject was named in a manner not supported by C++11. Such
153 /// lvalues can still be folded, but they are not core constant expressions
154 /// and we cannot perform lvalue-to-rvalue conversions on them.
155 bool Invalid : 1;
156
Richard Smitha8105bc2012-01-06 16:39:00 +0000157 /// Is this a pointer one past the end of an object?
158 bool IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000159
Richard Smitha8105bc2012-01-06 16:39:00 +0000160 /// The length of the path to the most-derived object of which this is a
161 /// subobject.
162 unsigned MostDerivedPathLength : 30;
163
164 /// The size of the array of which the most-derived object is an element, or
165 /// 0 if the most-derived object is not an array element.
166 uint64_t MostDerivedArraySize;
167
168 /// The type of the most derived object referred to by this address.
169 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000170
Richard Smith80815602011-11-07 05:07:52 +0000171 typedef APValue::LValuePathEntry PathEntry;
172
Richard Smith96e0c102011-11-04 02:25:55 +0000173 /// The entries on the path from the glvalue to the designated subobject.
174 SmallVector<PathEntry, 8> Entries;
175
Richard Smitha8105bc2012-01-06 16:39:00 +0000176 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000177
Richard Smitha8105bc2012-01-06 16:39:00 +0000178 explicit SubobjectDesignator(QualType T)
179 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
180 MostDerivedArraySize(0), MostDerivedType(T) {}
181
182 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
183 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
184 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith80815602011-11-07 05:07:52 +0000185 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000186 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000187 ArrayRef<PathEntry> VEntries = V.getLValuePath();
188 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
189 if (V.getLValueBase())
Richard Smitha8105bc2012-01-06 16:39:00 +0000190 MostDerivedPathLength =
191 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
192 V.getLValuePath(), MostDerivedArraySize,
193 MostDerivedType);
Richard Smith80815602011-11-07 05:07:52 +0000194 }
195 }
196
Richard Smith96e0c102011-11-04 02:25:55 +0000197 void setInvalid() {
198 Invalid = true;
199 Entries.clear();
200 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000201
202 /// Determine whether this is a one-past-the-end pointer.
203 bool isOnePastTheEnd() const {
204 if (IsOnePastTheEnd)
205 return true;
206 if (MostDerivedArraySize &&
207 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
208 return true;
209 return false;
210 }
211
212 /// Check that this refers to a valid subobject.
213 bool isValidSubobject() const {
214 if (Invalid)
215 return false;
216 return !isOnePastTheEnd();
217 }
218 /// Check that this refers to a valid subobject, and if not, produce a
219 /// relevant diagnostic and set the designator as invalid.
220 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
221
222 /// Update this designator to refer to the first element within this array.
223 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000224 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000225 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000226 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000227
228 // This is a most-derived object.
229 MostDerivedType = CAT->getElementType();
230 MostDerivedArraySize = CAT->getSize().getZExtValue();
231 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000232 }
233 /// Update this designator to refer to the given base or member of this
234 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000235 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000236 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000237 APValue::BaseOrMemberType Value(D, Virtual);
238 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000239 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000240
241 // If this isn't a base class, it's a new most-derived object.
242 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
243 MostDerivedType = FD->getType();
244 MostDerivedArraySize = 0;
245 MostDerivedPathLength = Entries.size();
246 }
Richard Smith96e0c102011-11-04 02:25:55 +0000247 }
Richard Smith66c96992012-02-18 22:04:06 +0000248 /// Update this designator to refer to the given complex component.
249 void addComplexUnchecked(QualType EltTy, bool Imag) {
250 PathEntry Entry;
251 Entry.ArrayIndex = Imag;
252 Entries.push_back(Entry);
253
254 // This is technically a most-derived object, though in practice this
255 // is unlikely to matter.
256 MostDerivedType = EltTy;
257 MostDerivedArraySize = 2;
258 MostDerivedPathLength = Entries.size();
259 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000260 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith96e0c102011-11-04 02:25:55 +0000261 /// Add N to the address of this subobject.
Richard Smitha8105bc2012-01-06 16:39:00 +0000262 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith96e0c102011-11-04 02:25:55 +0000263 if (Invalid) return;
Richard Smitha8105bc2012-01-06 16:39:00 +0000264 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith80815602011-11-07 05:07:52 +0000265 Entries.back().ArrayIndex += N;
Richard Smitha8105bc2012-01-06 16:39:00 +0000266 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
267 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
268 setInvalid();
269 }
Richard Smith96e0c102011-11-04 02:25:55 +0000270 return;
271 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000272 // [expr.add]p4: For the purposes of these operators, a pointer to a
273 // nonarray object behaves the same as a pointer to the first element of
274 // an array of length one with the type of the object as its element type.
275 if (IsOnePastTheEnd && N == (uint64_t)-1)
276 IsOnePastTheEnd = false;
277 else if (!IsOnePastTheEnd && N == 1)
278 IsOnePastTheEnd = true;
279 else if (N != 0) {
280 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith96e0c102011-11-04 02:25:55 +0000281 setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000282 }
Richard Smith96e0c102011-11-04 02:25:55 +0000283 }
284 };
285
Richard Smith254a73d2011-10-28 22:34:42 +0000286 /// A stack frame in the constexpr call stack.
287 struct CallStackFrame {
288 EvalInfo &Info;
289
290 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000291 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000292
Richard Smithf6f003a2011-12-16 19:06:07 +0000293 /// CallLoc - The location of the call expression for this call.
294 SourceLocation CallLoc;
295
296 /// Callee - The function which was called.
297 const FunctionDecl *Callee;
298
Richard Smithb228a862012-02-15 02:18:13 +0000299 /// Index - The call index of this call.
300 unsigned Index;
301
Richard Smithd62306a2011-11-10 06:34:14 +0000302 /// This - The binding for the this pointer in this call, if any.
303 const LValue *This;
304
Richard Smith254a73d2011-10-28 22:34:42 +0000305 /// ParmBindings - Parameter bindings for this function call, indexed by
306 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000307 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000308
Eli Friedman4830ec82012-06-25 21:21:08 +0000309 // Note that we intentionally use std::map here so that references to
310 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000311 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000312 typedef MapTy::const_iterator temp_iterator;
313 /// Temporaries - Temporary lvalues materialized within this stack frame.
314 MapTy Temporaries;
315
Richard Smithf6f003a2011-12-16 19:06:07 +0000316 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
317 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000318 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000319 ~CallStackFrame();
Richard Smith254a73d2011-10-28 22:34:42 +0000320 };
321
Richard Smith852c9db2013-04-20 22:23:05 +0000322 /// Temporarily override 'this'.
323 class ThisOverrideRAII {
324 public:
325 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
326 : Frame(Frame), OldThis(Frame.This) {
327 if (Enable)
328 Frame.This = NewThis;
329 }
330 ~ThisOverrideRAII() {
331 Frame.This = OldThis;
332 }
333 private:
334 CallStackFrame &Frame;
335 const LValue *OldThis;
336 };
337
Richard Smith92b1ce02011-12-12 09:28:41 +0000338 /// A partial diagnostic which we might know in advance that we are not going
339 /// to emit.
340 class OptionalDiagnostic {
341 PartialDiagnostic *Diag;
342
343 public:
344 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
345
346 template<typename T>
347 OptionalDiagnostic &operator<<(const T &v) {
348 if (Diag)
349 *Diag << v;
350 return *this;
351 }
Richard Smithfe800032012-01-31 04:08:20 +0000352
353 OptionalDiagnostic &operator<<(const APSInt &I) {
354 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000355 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000356 I.toString(Buffer);
357 *Diag << StringRef(Buffer.data(), Buffer.size());
358 }
359 return *this;
360 }
361
362 OptionalDiagnostic &operator<<(const APFloat &F) {
363 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000364 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000365 F.toString(Buffer);
366 *Diag << StringRef(Buffer.data(), Buffer.size());
367 }
368 return *this;
369 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000370 };
371
Richard Smithb228a862012-02-15 02:18:13 +0000372 /// EvalInfo - This is a private struct used by the evaluator to capture
373 /// information about a subexpression as it is folded. It retains information
374 /// about the AST context, but also maintains information about the folded
375 /// expression.
376 ///
377 /// If an expression could be evaluated, it is still possible it is not a C
378 /// "integer constant expression" or constant expression. If not, this struct
379 /// captures information about how and why not.
380 ///
381 /// One bit of information passed *into* the request for constant folding
382 /// indicates whether the subexpression is "evaluated" or not according to C
383 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
384 /// evaluate the expression regardless of what the RHS is, but C only allows
385 /// certain things in certain situations.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000386 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000387 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000388
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000389 /// EvalStatus - Contains information about the evaluation.
390 Expr::EvalStatus &EvalStatus;
391
392 /// CurrentCall - The top of the constexpr call stack.
393 CallStackFrame *CurrentCall;
394
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000395 /// CallStackDepth - The number of calls in the call stack right now.
396 unsigned CallStackDepth;
397
Richard Smithb228a862012-02-15 02:18:13 +0000398 /// NextCallIndex - The next call index to assign.
399 unsigned NextCallIndex;
400
Richard Smitha3d3bd22013-05-08 02:12:03 +0000401 /// StepsLeft - The remaining number of evaluation steps we're permitted
402 /// to perform. This is essentially a limit for the number of statements
403 /// we will evaluate.
404 unsigned StepsLeft;
405
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000406 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000407 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000408 CallStackFrame BottomFrame;
409
Richard Smithd62306a2011-11-10 06:34:14 +0000410 /// EvaluatingDecl - This is the declaration whose initializer is being
411 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000412 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000413
414 /// EvaluatingDeclValue - This is the value being constructed for the
415 /// declaration whose initializer is being evaluated, if any.
416 APValue *EvaluatingDeclValue;
417
Richard Smith357362d2011-12-13 06:39:58 +0000418 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
419 /// notes attached to it will also be stored, otherwise they will not be.
420 bool HasActiveDiagnostic;
421
Richard Smith253c2a32012-01-27 01:14:48 +0000422 /// CheckingPotentialConstantExpression - Are we checking whether the
423 /// expression is a potential constant expression? If so, some diagnostics
424 /// are suppressed.
425 bool CheckingPotentialConstantExpression;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000426
427 bool IntOverflowCheckMode;
Richard Smith253c2a32012-01-27 01:14:48 +0000428
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000429 EvalInfo(const ASTContext &C, Expr::EvalStatus &S,
Richard Smitha3d3bd22013-05-08 02:12:03 +0000430 bool OverflowCheckMode = false)
Richard Smith92b1ce02011-12-12 09:28:41 +0000431 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smithb228a862012-02-15 02:18:13 +0000432 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000433 StepsLeft(getLangOpts().ConstexprStepLimit),
Richard Smithb228a862012-02-15 02:18:13 +0000434 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith7525ff62013-05-09 07:14:00 +0000435 EvaluatingDecl((const ValueDecl*)0), EvaluatingDeclValue(0),
436 HasActiveDiagnostic(false), CheckingPotentialConstantExpression(false),
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000437 IntOverflowCheckMode(OverflowCheckMode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000438
Richard Smith7525ff62013-05-09 07:14:00 +0000439 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
440 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000441 EvaluatingDeclValue = &Value;
442 }
443
David Blaikiebbafb8a2012-03-11 07:00:24 +0000444 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000445
Richard Smith357362d2011-12-13 06:39:58 +0000446 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000447 // Don't perform any constexpr calls (other than the call we're checking)
448 // when checking a potential constant expression.
449 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
450 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000451 if (NextCallIndex == 0) {
452 // NextCallIndex has wrapped around.
453 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
454 return false;
455 }
Richard Smith357362d2011-12-13 06:39:58 +0000456 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
457 return true;
458 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
459 << getLangOpts().ConstexprCallDepth;
460 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000461 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000462
Richard Smithb228a862012-02-15 02:18:13 +0000463 CallStackFrame *getCallFrame(unsigned CallIndex) {
464 assert(CallIndex && "no call index in getCallFrame");
465 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
466 // be null in this loop.
467 CallStackFrame *Frame = CurrentCall;
468 while (Frame->Index > CallIndex)
469 Frame = Frame->Caller;
470 return (Frame->Index == CallIndex) ? Frame : 0;
471 }
472
Richard Smitha3d3bd22013-05-08 02:12:03 +0000473 bool nextStep(const Stmt *S) {
474 if (!StepsLeft) {
475 Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
476 return false;
477 }
478 --StepsLeft;
479 return true;
480 }
481
Richard Smith357362d2011-12-13 06:39:58 +0000482 private:
483 /// Add a diagnostic to the diagnostics list.
484 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
485 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
486 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
487 return EvalStatus.Diag->back().second;
488 }
489
Richard Smithf6f003a2011-12-16 19:06:07 +0000490 /// Add notes containing a call stack to the current point of evaluation.
491 void addCallStack(unsigned Limit);
492
Richard Smith357362d2011-12-13 06:39:58 +0000493 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000494 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000495 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
496 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000497 unsigned ExtraNotes = 0) {
Richard Smithf57d8cb2011-12-09 22:58:01 +0000498 // If we have a prior diagnostic, it will be noting that the expression
499 // isn't a constant expression. This diagnostic is more important.
500 // FIXME: We might want to show both diagnostics to the user.
Richard Smith92b1ce02011-12-12 09:28:41 +0000501 if (EvalStatus.Diag) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000502 unsigned CallStackNotes = CallStackDepth - 1;
503 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
504 if (Limit)
505 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith253c2a32012-01-27 01:14:48 +0000506 if (CheckingPotentialConstantExpression)
507 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000508
Richard Smith357362d2011-12-13 06:39:58 +0000509 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000510 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000511 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
512 addDiag(Loc, DiagId);
Richard Smith253c2a32012-01-27 01:14:48 +0000513 if (!CheckingPotentialConstantExpression)
514 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000515 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000516 }
Richard Smith357362d2011-12-13 06:39:58 +0000517 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000518 return OptionalDiagnostic();
519 }
520
Richard Smithce1ec5e2012-03-15 04:53:45 +0000521 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
522 = diag::note_invalid_subexpr_in_const_expr,
523 unsigned ExtraNotes = 0) {
524 if (EvalStatus.Diag)
525 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
526 HasActiveDiagnostic = false;
527 return OptionalDiagnostic();
528 }
529
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000530 bool getIntOverflowCheckMode() { return IntOverflowCheckMode; }
531
Richard Smith92b1ce02011-12-12 09:28:41 +0000532 /// Diagnose that the evaluation does not produce a C++11 core constant
533 /// expression.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000534 template<typename LocArg>
535 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000536 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000537 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000538 // Don't override a previous diagnostic.
Eli Friedmanebea9af2012-02-21 22:41:33 +0000539 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
540 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000541 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000542 }
Richard Smith357362d2011-12-13 06:39:58 +0000543 return Diag(Loc, DiagId, ExtraNotes);
544 }
545
546 /// Add a note to a prior diagnostic.
547 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
548 if (!HasActiveDiagnostic)
549 return OptionalDiagnostic();
550 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000551 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000552
553 /// Add a stack of notes to a prior diagnostic.
554 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
555 if (HasActiveDiagnostic) {
556 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
557 Diags.begin(), Diags.end());
558 }
559 }
Richard Smith253c2a32012-01-27 01:14:48 +0000560
561 /// Should we continue evaluation as much as possible after encountering a
562 /// construct which can't be folded?
563 bool keepEvaluatingAfterFailure() {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000564 // Should return true in IntOverflowCheckMode, so that we check for
565 // overflow even if some subexpressions can't be evaluated as constants.
Richard Smitha3d3bd22013-05-08 02:12:03 +0000566 return StepsLeft && (IntOverflowCheckMode ||
567 (CheckingPotentialConstantExpression &&
568 EvalStatus.Diag && EvalStatus.Diag->empty()));
Richard Smith253c2a32012-01-27 01:14:48 +0000569 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000570 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000571
572 /// Object used to treat all foldable expressions as constant expressions.
573 struct FoldConstant {
574 bool Enabled;
575
576 explicit FoldConstant(EvalInfo &Info)
577 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
578 !Info.EvalStatus.HasSideEffects) {
579 }
580 // Treat the value we've computed since this object was created as constant.
581 void Fold(EvalInfo &Info) {
582 if (Enabled && !Info.EvalStatus.Diag->empty() &&
583 !Info.EvalStatus.HasSideEffects)
584 Info.EvalStatus.Diag->clear();
585 }
586 };
Richard Smith17100ba2012-02-16 02:46:34 +0000587
588 /// RAII object used to suppress diagnostics and side-effects from a
589 /// speculative evaluation.
590 class SpeculativeEvaluationRAII {
591 EvalInfo &Info;
592 Expr::EvalStatus Old;
593
594 public:
595 SpeculativeEvaluationRAII(EvalInfo &Info,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000596 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = 0)
Richard Smith17100ba2012-02-16 02:46:34 +0000597 : Info(Info), Old(Info.EvalStatus) {
598 Info.EvalStatus.Diag = NewDiag;
599 }
600 ~SpeculativeEvaluationRAII() {
601 Info.EvalStatus = Old;
602 }
603 };
Richard Smithf6f003a2011-12-16 19:06:07 +0000604}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000605
Richard Smitha8105bc2012-01-06 16:39:00 +0000606bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
607 CheckSubobjectKind CSK) {
608 if (Invalid)
609 return false;
610 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000611 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000612 << CSK;
613 setInvalid();
614 return false;
615 }
616 return true;
617}
618
619void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
620 const Expr *E, uint64_t N) {
621 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000622 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000623 << static_cast<int>(N) << /*array*/ 0
624 << static_cast<unsigned>(MostDerivedArraySize);
625 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000626 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000627 << static_cast<int>(N) << /*non-array*/ 1;
628 setInvalid();
629}
630
Richard Smithf6f003a2011-12-16 19:06:07 +0000631CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
632 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000633 APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000634 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000635 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000636 Info.CurrentCall = this;
637 ++Info.CallStackDepth;
638}
639
640CallStackFrame::~CallStackFrame() {
641 assert(Info.CurrentCall == this && "calls retired out of order");
642 --Info.CallStackDepth;
643 Info.CurrentCall = Caller;
644}
645
Richard Smith84401042013-06-03 05:03:02 +0000646static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +0000647
648void EvalInfo::addCallStack(unsigned Limit) {
649 // Determine which calls to skip, if any.
650 unsigned ActiveCalls = CallStackDepth - 1;
651 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
652 if (Limit && Limit < ActiveCalls) {
653 SkipStart = Limit / 2 + Limit % 2;
654 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000655 }
656
Richard Smithf6f003a2011-12-16 19:06:07 +0000657 // Walk the call stack and add the diagnostics.
658 unsigned CallIdx = 0;
659 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
660 Frame = Frame->Caller, ++CallIdx) {
661 // Skip this call?
662 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
663 if (CallIdx == SkipStart) {
664 // Note that we're skipping calls.
665 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
666 << unsigned(ActiveCalls - Limit);
667 }
668 continue;
669 }
670
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000671 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +0000672 llvm::raw_svector_ostream Out(Buffer);
673 describeCall(Frame, Out);
674 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
675 }
676}
677
678namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000679 struct ComplexValue {
680 private:
681 bool IsInt;
682
683 public:
684 APSInt IntReal, IntImag;
685 APFloat FloatReal, FloatImag;
686
687 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
688
689 void makeComplexFloat() { IsInt = false; }
690 bool isComplexFloat() const { return !IsInt; }
691 APFloat &getComplexFloatReal() { return FloatReal; }
692 APFloat &getComplexFloatImag() { return FloatImag; }
693
694 void makeComplexInt() { IsInt = true; }
695 bool isComplexInt() const { return IsInt; }
696 APSInt &getComplexIntReal() { return IntReal; }
697 APSInt &getComplexIntImag() { return IntImag; }
698
Richard Smith2e312c82012-03-03 22:46:17 +0000699 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000700 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +0000701 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000702 else
Richard Smith2e312c82012-03-03 22:46:17 +0000703 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000704 }
Richard Smith2e312c82012-03-03 22:46:17 +0000705 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000706 assert(v.isComplexFloat() || v.isComplexInt());
707 if (v.isComplexFloat()) {
708 makeComplexFloat();
709 FloatReal = v.getComplexFloatReal();
710 FloatImag = v.getComplexFloatImag();
711 } else {
712 makeComplexInt();
713 IntReal = v.getComplexIntReal();
714 IntImag = v.getComplexIntImag();
715 }
716 }
John McCall93d91dc2010-05-07 17:22:02 +0000717 };
John McCall45d55e42010-05-07 21:00:08 +0000718
719 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000720 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000721 CharUnits Offset;
Richard Smithb228a862012-02-15 02:18:13 +0000722 unsigned CallIndex;
Richard Smith96e0c102011-11-04 02:25:55 +0000723 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000724
Richard Smithce40ad62011-11-12 22:28:03 +0000725 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000726 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000727 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +0000728 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +0000729 SubobjectDesignator &getLValueDesignator() { return Designator; }
730 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000731
Richard Smith2e312c82012-03-03 22:46:17 +0000732 void moveInto(APValue &V) const {
733 if (Designator.Invalid)
734 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
735 else
736 V = APValue(Base, Offset, Designator.Entries,
737 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000738 }
Richard Smith2e312c82012-03-03 22:46:17 +0000739 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000740 assert(V.isLValue());
741 Base = V.getLValueBase();
742 Offset = V.getLValueOffset();
Richard Smithb228a862012-02-15 02:18:13 +0000743 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +0000744 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +0000745 }
746
Richard Smithb228a862012-02-15 02:18:13 +0000747 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smithce40ad62011-11-12 22:28:03 +0000748 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000749 Offset = CharUnits::Zero();
Richard Smithb228a862012-02-15 02:18:13 +0000750 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +0000751 Designator = SubobjectDesignator(getType(B));
752 }
753
754 // Check that this LValue is not based on a null pointer. If it is, produce
755 // a diagnostic and mark the designator as invalid.
756 bool checkNullPointer(EvalInfo &Info, const Expr *E,
757 CheckSubobjectKind CSK) {
758 if (Designator.Invalid)
759 return false;
760 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000761 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000762 << CSK;
763 Designator.setInvalid();
764 return false;
765 }
766 return true;
767 }
768
769 // Check this LValue refers to an object. If not, set the designator to be
770 // invalid and emit a diagnostic.
771 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000772 // Outside C++11, do not build a designator referring to a subobject of
773 // any object: we won't use such a designator for anything.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000774 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000775 Designator.setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000776 return checkNullPointer(Info, E, CSK) &&
777 Designator.checkSubobject(Info, E, CSK);
778 }
779
780 void addDecl(EvalInfo &Info, const Expr *E,
781 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000782 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
783 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +0000784 }
785 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000786 if (checkSubobject(Info, E, CSK_ArrayToPointer))
787 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +0000788 }
Richard Smith66c96992012-02-18 22:04:06 +0000789 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000790 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
791 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +0000792 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000793 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000794 if (checkNullPointer(Info, E, CSK_ArrayIndex))
795 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +0000796 }
John McCall45d55e42010-05-07 21:00:08 +0000797 };
Richard Smith027bf112011-11-17 22:56:20 +0000798
799 struct MemberPtr {
800 MemberPtr() {}
801 explicit MemberPtr(const ValueDecl *Decl) :
802 DeclAndIsDerivedMember(Decl, false), Path() {}
803
804 /// The member or (direct or indirect) field referred to by this member
805 /// pointer, or 0 if this is a null member pointer.
806 const ValueDecl *getDecl() const {
807 return DeclAndIsDerivedMember.getPointer();
808 }
809 /// Is this actually a member of some type derived from the relevant class?
810 bool isDerivedMember() const {
811 return DeclAndIsDerivedMember.getInt();
812 }
813 /// Get the class which the declaration actually lives in.
814 const CXXRecordDecl *getContainingRecord() const {
815 return cast<CXXRecordDecl>(
816 DeclAndIsDerivedMember.getPointer()->getDeclContext());
817 }
818
Richard Smith2e312c82012-03-03 22:46:17 +0000819 void moveInto(APValue &V) const {
820 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +0000821 }
Richard Smith2e312c82012-03-03 22:46:17 +0000822 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +0000823 assert(V.isMemberPointer());
824 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
825 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
826 Path.clear();
827 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
828 Path.insert(Path.end(), P.begin(), P.end());
829 }
830
831 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
832 /// whether the member is a member of some class derived from the class type
833 /// of the member pointer.
834 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
835 /// Path - The path of base/derived classes from the member declaration's
836 /// class (exclusive) to the class type of the member pointer (inclusive).
837 SmallVector<const CXXRecordDecl*, 4> Path;
838
839 /// Perform a cast towards the class of the Decl (either up or down the
840 /// hierarchy).
841 bool castBack(const CXXRecordDecl *Class) {
842 assert(!Path.empty());
843 const CXXRecordDecl *Expected;
844 if (Path.size() >= 2)
845 Expected = Path[Path.size() - 2];
846 else
847 Expected = getContainingRecord();
848 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
849 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
850 // if B does not contain the original member and is not a base or
851 // derived class of the class containing the original member, the result
852 // of the cast is undefined.
853 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
854 // (D::*). We consider that to be a language defect.
855 return false;
856 }
857 Path.pop_back();
858 return true;
859 }
860 /// Perform a base-to-derived member pointer cast.
861 bool castToDerived(const CXXRecordDecl *Derived) {
862 if (!getDecl())
863 return true;
864 if (!isDerivedMember()) {
865 Path.push_back(Derived);
866 return true;
867 }
868 if (!castBack(Derived))
869 return false;
870 if (Path.empty())
871 DeclAndIsDerivedMember.setInt(false);
872 return true;
873 }
874 /// Perform a derived-to-base member pointer cast.
875 bool castToBase(const CXXRecordDecl *Base) {
876 if (!getDecl())
877 return true;
878 if (Path.empty())
879 DeclAndIsDerivedMember.setInt(true);
880 if (isDerivedMember()) {
881 Path.push_back(Base);
882 return true;
883 }
884 return castBack(Base);
885 }
886 };
Richard Smith357362d2011-12-13 06:39:58 +0000887
Richard Smith7bb00672012-02-01 01:42:44 +0000888 /// Compare two member pointers, which are assumed to be of the same type.
889 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
890 if (!LHS.getDecl() || !RHS.getDecl())
891 return !LHS.getDecl() && !RHS.getDecl();
892 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
893 return false;
894 return LHS.Path == RHS.Path;
895 }
John McCall93d91dc2010-05-07 17:22:02 +0000896}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000897
Richard Smith2e312c82012-03-03 22:46:17 +0000898static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +0000899static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
900 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +0000901 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +0000902static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
903static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +0000904static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
905 EvalInfo &Info);
906static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000907static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +0000908static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000909 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000910static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000911static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +0000912static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000913
914//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000915// Misc utilities
916//===----------------------------------------------------------------------===//
917
Richard Smith84401042013-06-03 05:03:02 +0000918/// Produce a string describing the given constexpr call.
919static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
920 unsigned ArgIndex = 0;
921 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
922 !isa<CXXConstructorDecl>(Frame->Callee) &&
923 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
924
925 if (!IsMemberCall)
926 Out << *Frame->Callee << '(';
927
928 if (Frame->This && IsMemberCall) {
929 APValue Val;
930 Frame->This->moveInto(Val);
931 Val.printPretty(Out, Frame->Info.Ctx,
932 Frame->This->Designator.MostDerivedType);
933 // FIXME: Add parens around Val if needed.
934 Out << "->" << *Frame->Callee << '(';
935 IsMemberCall = false;
936 }
937
938 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
939 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
940 if (ArgIndex > (unsigned)IsMemberCall)
941 Out << ", ";
942
943 const ParmVarDecl *Param = *I;
944 const APValue &Arg = Frame->Arguments[ArgIndex];
945 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
946
947 if (ArgIndex == 0 && IsMemberCall)
948 Out << "->" << *Frame->Callee << '(';
949 }
950
951 Out << ')';
952}
953
Richard Smithd9f663b2013-04-22 15:31:51 +0000954/// Evaluate an expression to see if it had side-effects, and discard its
955/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +0000956/// \return \c true if the caller should keep evaluating.
957static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000958 APValue Scratch;
Richard Smith4e18ca52013-05-06 05:56:11 +0000959 if (!Evaluate(Scratch, Info, E)) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000960 Info.EvalStatus.HasSideEffects = true;
Richard Smith4e18ca52013-05-06 05:56:11 +0000961 return Info.keepEvaluatingAfterFailure();
962 }
963 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +0000964}
965
Richard Smith861b5b52013-05-07 23:34:45 +0000966/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
967/// return its existing value.
968static int64_t getExtValue(const APSInt &Value) {
969 return Value.isSigned() ? Value.getSExtValue()
970 : static_cast<int64_t>(Value.getZExtValue());
971}
972
Richard Smithd62306a2011-11-10 06:34:14 +0000973/// Should this call expression be treated as a string literal?
974static bool IsStringLiteralCall(const CallExpr *E) {
975 unsigned Builtin = E->isBuiltinCall();
976 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
977 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
978}
979
Richard Smithce40ad62011-11-12 22:28:03 +0000980static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +0000981 // C++11 [expr.const]p3 An address constant expression is a prvalue core
982 // constant expression of pointer type that evaluates to...
983
984 // ... a null pointer value, or a prvalue core constant expression of type
985 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +0000986 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +0000987
Richard Smithce40ad62011-11-12 22:28:03 +0000988 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
989 // ... the address of an object with static storage duration,
990 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
991 return VD->hasGlobalStorage();
992 // ... the address of a function,
993 return isa<FunctionDecl>(D);
994 }
995
996 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +0000997 switch (E->getStmtClass()) {
998 default:
999 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001000 case Expr::CompoundLiteralExprClass: {
1001 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1002 return CLE->isFileScope() && CLE->isLValue();
1003 }
Richard Smithe6c01442013-06-05 00:46:14 +00001004 case Expr::MaterializeTemporaryExprClass:
1005 // A materialized temporary might have been lifetime-extended to static
1006 // storage duration.
1007 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001008 // A string literal has static storage duration.
1009 case Expr::StringLiteralClass:
1010 case Expr::PredefinedExprClass:
1011 case Expr::ObjCStringLiteralClass:
1012 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001013 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001014 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001015 return true;
1016 case Expr::CallExprClass:
1017 return IsStringLiteralCall(cast<CallExpr>(E));
1018 // For GCC compatibility, &&label has static storage duration.
1019 case Expr::AddrLabelExprClass:
1020 return true;
1021 // A Block literal expression may be used as the initialization value for
1022 // Block variables at global or local static scope.
1023 case Expr::BlockExprClass:
1024 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001025 case Expr::ImplicitValueInitExprClass:
1026 // FIXME:
1027 // We can never form an lvalue with an implicit value initialization as its
1028 // base through expression evaluation, so these only appear in one case: the
1029 // implicit variable declaration we invent when checking whether a constexpr
1030 // constructor can produce a constant expression. We must assume that such
1031 // an expression might be a global lvalue.
1032 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001033 }
John McCall95007602010-05-10 23:27:23 +00001034}
1035
Richard Smithb228a862012-02-15 02:18:13 +00001036static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1037 assert(Base && "no location for a null lvalue");
1038 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1039 if (VD)
1040 Info.Note(VD->getLocation(), diag::note_declared_at);
1041 else
Ted Kremenek28831752012-08-23 20:46:57 +00001042 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001043 diag::note_constexpr_temporary_here);
1044}
1045
Richard Smith80815602011-11-07 05:07:52 +00001046/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001047/// value for an address or reference constant expression. Return true if we
1048/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001049static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1050 QualType Type, const LValue &LVal) {
1051 bool IsReferenceType = Type->isReferenceType();
1052
Richard Smith357362d2011-12-13 06:39:58 +00001053 APValue::LValueBase Base = LVal.getLValueBase();
1054 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1055
Richard Smith0dea49e2012-02-18 04:58:18 +00001056 // Check that the object is a global. Note that the fake 'this' object we
1057 // manufacture when checking potential constant expressions is conservatively
1058 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001059 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001060 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001061 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001062 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1063 << IsReferenceType << !Designator.Entries.empty()
1064 << !!VD << VD;
1065 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001066 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001067 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001068 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001069 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001070 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001071 }
Richard Smithb228a862012-02-15 02:18:13 +00001072 assert((Info.CheckingPotentialConstantExpression ||
1073 LVal.getLValueCallIndex() == 0) &&
1074 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001075
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001076 // Check if this is a thread-local variable.
1077 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1078 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
Richard Smithfd3834f2013-04-13 02:43:54 +00001079 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001080 return false;
1081 }
1082 }
1083
Richard Smitha8105bc2012-01-06 16:39:00 +00001084 // Allow address constant expressions to be past-the-end pointers. This is
1085 // an extension: the standard requires them to point to an object.
1086 if (!IsReferenceType)
1087 return true;
1088
1089 // A reference constant expression must refer to an object.
1090 if (!Base) {
1091 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001092 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001093 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001094 }
1095
Richard Smith357362d2011-12-13 06:39:58 +00001096 // Does this refer one past the end of some object?
Richard Smitha8105bc2012-01-06 16:39:00 +00001097 if (Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001098 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001099 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001100 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001101 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001102 }
1103
Richard Smith80815602011-11-07 05:07:52 +00001104 return true;
1105}
1106
Richard Smithfddd3842011-12-30 21:15:51 +00001107/// Check that this core constant expression is of literal type, and if not,
1108/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001109static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1110 const LValue *This = 0) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001111 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001112 return true;
1113
Richard Smith7525ff62013-05-09 07:14:00 +00001114 // C++1y: A constant initializer for an object o [...] may also invoke
1115 // constexpr constructors for o and its subobjects even if those objects
1116 // are of non-literal class types.
1117 if (Info.getLangOpts().CPlusPlus1y && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001118 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001119 return true;
1120
Richard Smithfddd3842011-12-30 21:15:51 +00001121 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001122 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001123 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001124 << E->getType();
1125 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001126 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001127 return false;
1128}
1129
Richard Smith0b0a0b62011-10-29 20:57:55 +00001130/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001131/// constant expression. If not, report an appropriate diagnostic. Does not
1132/// check that the expression is of literal type.
1133static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1134 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001135 if (Value.isUninit()) {
Richard Smith51f03172013-06-20 03:00:05 +00001136 Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1137 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001138 return false;
1139 }
1140
Richard Smithb228a862012-02-15 02:18:13 +00001141 // Core issue 1454: For a literal constant expression of array or class type,
1142 // each subobject of its value shall have been initialized by a constant
1143 // expression.
1144 if (Value.isArray()) {
1145 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1146 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1147 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1148 Value.getArrayInitializedElt(I)))
1149 return false;
1150 }
1151 if (!Value.hasArrayFiller())
1152 return true;
1153 return CheckConstantExpression(Info, DiagLoc, EltTy,
1154 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001155 }
Richard Smithb228a862012-02-15 02:18:13 +00001156 if (Value.isUnion() && Value.getUnionField()) {
1157 return CheckConstantExpression(Info, DiagLoc,
1158 Value.getUnionField()->getType(),
1159 Value.getUnionValue());
1160 }
1161 if (Value.isStruct()) {
1162 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1163 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1164 unsigned BaseIndex = 0;
1165 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1166 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1167 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1168 Value.getStructBase(BaseIndex)))
1169 return false;
1170 }
1171 }
1172 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1173 I != E; ++I) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001174 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1175 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001176 return false;
1177 }
1178 }
1179
1180 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001181 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001182 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001183 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1184 }
1185
1186 // Everything else is fine.
1187 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001188}
1189
Richard Smith83c68212011-10-31 05:11:32 +00001190const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001191 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001192}
1193
1194static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001195 if (Value.CallIndex)
1196 return false;
1197 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1198 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001199}
1200
Richard Smithcecf1842011-11-01 21:06:14 +00001201static bool IsWeakLValue(const LValue &Value) {
1202 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001203 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001204}
1205
Richard Smith2e312c82012-03-03 22:46:17 +00001206static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001207 // A null base expression indicates a null pointer. These are always
1208 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001209 if (!Value.getLValueBase()) {
1210 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001211 return true;
1212 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001213
Richard Smith027bf112011-11-17 22:56:20 +00001214 // We have a non-null base. These are generally known to be true, but if it's
1215 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001216 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001217 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001218 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001219}
1220
Richard Smith2e312c82012-03-03 22:46:17 +00001221static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001222 switch (Val.getKind()) {
1223 case APValue::Uninitialized:
1224 return false;
1225 case APValue::Int:
1226 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001227 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001228 case APValue::Float:
1229 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001230 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001231 case APValue::ComplexInt:
1232 Result = Val.getComplexIntReal().getBoolValue() ||
1233 Val.getComplexIntImag().getBoolValue();
1234 return true;
1235 case APValue::ComplexFloat:
1236 Result = !Val.getComplexFloatReal().isZero() ||
1237 !Val.getComplexFloatImag().isZero();
1238 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001239 case APValue::LValue:
1240 return EvalPointerValueAsBool(Val, Result);
1241 case APValue::MemberPointer:
1242 Result = Val.getMemberPointerDecl();
1243 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001244 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001245 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001246 case APValue::Struct:
1247 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001248 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001249 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001250 }
1251
Richard Smith11562c52011-10-28 17:51:58 +00001252 llvm_unreachable("unknown APValue kind");
1253}
1254
1255static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1256 EvalInfo &Info) {
1257 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001258 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001259 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001260 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001261 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001262}
1263
Richard Smith357362d2011-12-13 06:39:58 +00001264template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001265static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001266 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001267 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001268 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001269}
1270
1271static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1272 QualType SrcType, const APFloat &Value,
1273 QualType DestType, APSInt &Result) {
1274 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001275 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001276 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001277
Richard Smith357362d2011-12-13 06:39:58 +00001278 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001279 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001280 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1281 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001282 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001283 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001284}
1285
Richard Smith357362d2011-12-13 06:39:58 +00001286static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1287 QualType SrcType, QualType DestType,
1288 APFloat &Result) {
1289 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001290 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001291 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1292 APFloat::rmNearestTiesToEven, &ignored)
1293 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001294 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001295 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001296}
1297
Richard Smith911e1422012-01-30 22:27:01 +00001298static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1299 QualType DestType, QualType SrcType,
1300 APSInt &Value) {
1301 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001302 APSInt Result = Value;
1303 // Figure out if this is a truncate, extend or noop cast.
1304 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001305 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001306 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001307 return Result;
1308}
1309
Richard Smith357362d2011-12-13 06:39:58 +00001310static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1311 QualType SrcType, const APSInt &Value,
1312 QualType DestType, APFloat &Result) {
1313 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1314 if (Result.convertFromAPInt(Value, Value.isSigned(),
1315 APFloat::rmNearestTiesToEven)
1316 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001317 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001318 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001319}
1320
Eli Friedman803acb32011-12-22 03:51:45 +00001321static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1322 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001323 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001324 if (!Evaluate(SVal, Info, E))
1325 return false;
1326 if (SVal.isInt()) {
1327 Res = SVal.getInt();
1328 return true;
1329 }
1330 if (SVal.isFloat()) {
1331 Res = SVal.getFloat().bitcastToAPInt();
1332 return true;
1333 }
1334 if (SVal.isVector()) {
1335 QualType VecTy = E->getType();
1336 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1337 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1338 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1339 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1340 Res = llvm::APInt::getNullValue(VecSize);
1341 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1342 APValue &Elt = SVal.getVectorElt(i);
1343 llvm::APInt EltAsInt;
1344 if (Elt.isInt()) {
1345 EltAsInt = Elt.getInt();
1346 } else if (Elt.isFloat()) {
1347 EltAsInt = Elt.getFloat().bitcastToAPInt();
1348 } else {
1349 // Don't try to handle vectors of anything other than int or float
1350 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001351 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001352 return false;
1353 }
1354 unsigned BaseEltSize = EltAsInt.getBitWidth();
1355 if (BigEndian)
1356 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1357 else
1358 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1359 }
1360 return true;
1361 }
1362 // Give up if the input isn't an int, float, or vector. For example, we
1363 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001364 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001365 return false;
1366}
1367
Richard Smith43e77732013-05-07 04:50:00 +00001368/// Perform the given integer operation, which is known to need at most BitWidth
1369/// bits, and check for overflow in the original type (if that type was not an
1370/// unsigned type).
1371template<typename Operation>
1372static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1373 const APSInt &LHS, const APSInt &RHS,
1374 unsigned BitWidth, Operation Op) {
1375 if (LHS.isUnsigned())
1376 return Op(LHS, RHS);
1377
1378 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1379 APSInt Result = Value.trunc(LHS.getBitWidth());
1380 if (Result.extend(BitWidth) != Value) {
1381 if (Info.getIntOverflowCheckMode())
1382 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1383 diag::warn_integer_constant_overflow)
1384 << Result.toString(10) << E->getType();
1385 else
1386 HandleOverflow(Info, E, Value, E->getType());
1387 }
1388 return Result;
1389}
1390
1391/// Perform the given binary integer operation.
1392static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1393 BinaryOperatorKind Opcode, APSInt RHS,
1394 APSInt &Result) {
1395 switch (Opcode) {
1396 default:
1397 Info.Diag(E);
1398 return false;
1399 case BO_Mul:
1400 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1401 std::multiplies<APSInt>());
1402 return true;
1403 case BO_Add:
1404 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1405 std::plus<APSInt>());
1406 return true;
1407 case BO_Sub:
1408 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1409 std::minus<APSInt>());
1410 return true;
1411 case BO_And: Result = LHS & RHS; return true;
1412 case BO_Xor: Result = LHS ^ RHS; return true;
1413 case BO_Or: Result = LHS | RHS; return true;
1414 case BO_Div:
1415 case BO_Rem:
1416 if (RHS == 0) {
1417 Info.Diag(E, diag::note_expr_divide_by_zero);
1418 return false;
1419 }
1420 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1421 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1422 LHS.isSigned() && LHS.isMinSignedValue())
1423 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1424 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1425 return true;
1426 case BO_Shl: {
1427 if (Info.getLangOpts().OpenCL)
1428 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1429 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1430 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1431 RHS.isUnsigned());
1432 else if (RHS.isSigned() && RHS.isNegative()) {
1433 // During constant-folding, a negative shift is an opposite shift. Such
1434 // a shift is not a constant expression.
1435 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1436 RHS = -RHS;
1437 goto shift_right;
1438 }
1439 shift_left:
1440 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1441 // the shifted type.
1442 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1443 if (SA != RHS) {
1444 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1445 << RHS << E->getType() << LHS.getBitWidth();
1446 } else if (LHS.isSigned()) {
1447 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1448 // operand, and must not overflow the corresponding unsigned type.
1449 if (LHS.isNegative())
1450 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1451 else if (LHS.countLeadingZeros() < SA)
1452 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1453 }
1454 Result = LHS << SA;
1455 return true;
1456 }
1457 case BO_Shr: {
1458 if (Info.getLangOpts().OpenCL)
1459 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1460 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1461 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1462 RHS.isUnsigned());
1463 else if (RHS.isSigned() && RHS.isNegative()) {
1464 // During constant-folding, a negative shift is an opposite shift. Such a
1465 // shift is not a constant expression.
1466 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1467 RHS = -RHS;
1468 goto shift_left;
1469 }
1470 shift_right:
1471 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1472 // shifted type.
1473 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1474 if (SA != RHS)
1475 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1476 << RHS << E->getType() << LHS.getBitWidth();
1477 Result = LHS >> SA;
1478 return true;
1479 }
1480
1481 case BO_LT: Result = LHS < RHS; return true;
1482 case BO_GT: Result = LHS > RHS; return true;
1483 case BO_LE: Result = LHS <= RHS; return true;
1484 case BO_GE: Result = LHS >= RHS; return true;
1485 case BO_EQ: Result = LHS == RHS; return true;
1486 case BO_NE: Result = LHS != RHS; return true;
1487 }
1488}
1489
Richard Smith861b5b52013-05-07 23:34:45 +00001490/// Perform the given binary floating-point operation, in-place, on LHS.
1491static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1492 APFloat &LHS, BinaryOperatorKind Opcode,
1493 const APFloat &RHS) {
1494 switch (Opcode) {
1495 default:
1496 Info.Diag(E);
1497 return false;
1498 case BO_Mul:
1499 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1500 break;
1501 case BO_Add:
1502 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1503 break;
1504 case BO_Sub:
1505 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1506 break;
1507 case BO_Div:
1508 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1509 break;
1510 }
1511
1512 if (LHS.isInfinity() || LHS.isNaN())
1513 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1514 return true;
1515}
1516
Richard Smitha8105bc2012-01-06 16:39:00 +00001517/// Cast an lvalue referring to a base subobject to a derived class, by
1518/// truncating the lvalue's path to the given length.
1519static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1520 const RecordDecl *TruncatedType,
1521 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001522 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001523
1524 // Check we actually point to a derived class object.
1525 if (TruncatedElements == D.Entries.size())
1526 return true;
1527 assert(TruncatedElements >= D.MostDerivedPathLength &&
1528 "not casting to a derived class");
1529 if (!Result.checkSubobject(Info, E, CSK_Derived))
1530 return false;
1531
1532 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001533 const RecordDecl *RD = TruncatedType;
1534 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001535 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001536 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1537 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001538 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001539 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001540 else
Richard Smithd62306a2011-11-10 06:34:14 +00001541 Result.Offset -= Layout.getBaseClassOffset(Base);
1542 RD = Base;
1543 }
Richard Smith027bf112011-11-17 22:56:20 +00001544 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001545 return true;
1546}
1547
John McCalld7bca762012-05-01 00:38:49 +00001548static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001549 const CXXRecordDecl *Derived,
1550 const CXXRecordDecl *Base,
1551 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001552 if (!RL) {
1553 if (Derived->isInvalidDecl()) return false;
1554 RL = &Info.Ctx.getASTRecordLayout(Derived);
1555 }
1556
Richard Smithd62306a2011-11-10 06:34:14 +00001557 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001558 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001559 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001560}
1561
Richard Smitha8105bc2012-01-06 16:39:00 +00001562static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001563 const CXXRecordDecl *DerivedDecl,
1564 const CXXBaseSpecifier *Base) {
1565 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1566
John McCalld7bca762012-05-01 00:38:49 +00001567 if (!Base->isVirtual())
1568 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001569
Richard Smitha8105bc2012-01-06 16:39:00 +00001570 SubobjectDesignator &D = Obj.Designator;
1571 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001572 return false;
1573
Richard Smitha8105bc2012-01-06 16:39:00 +00001574 // Extract most-derived object and corresponding type.
1575 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1576 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1577 return false;
1578
1579 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001580 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001581 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1582 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001583 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001584 return true;
1585}
1586
Richard Smith84401042013-06-03 05:03:02 +00001587static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1588 QualType Type, LValue &Result) {
1589 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1590 PathE = E->path_end();
1591 PathI != PathE; ++PathI) {
1592 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1593 *PathI))
1594 return false;
1595 Type = (*PathI)->getType();
1596 }
1597 return true;
1598}
1599
Richard Smithd62306a2011-11-10 06:34:14 +00001600/// Update LVal to refer to the given field, which must be a member of the type
1601/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001602static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001603 const FieldDecl *FD,
1604 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001605 if (!RL) {
1606 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001607 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001608 }
Richard Smithd62306a2011-11-10 06:34:14 +00001609
1610 unsigned I = FD->getFieldIndex();
1611 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001612 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001613 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001614}
1615
Richard Smith1b78b3d2012-01-25 22:15:11 +00001616/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001617static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001618 LValue &LVal,
1619 const IndirectFieldDecl *IFD) {
1620 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1621 CE = IFD->chain_end(); C != CE; ++C)
John McCalld7bca762012-05-01 00:38:49 +00001622 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1623 return false;
1624 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001625}
1626
Richard Smithd62306a2011-11-10 06:34:14 +00001627/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001628static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1629 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001630 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1631 // extension.
1632 if (Type->isVoidType() || Type->isFunctionType()) {
1633 Size = CharUnits::One();
1634 return true;
1635 }
1636
1637 if (!Type->isConstantSizeType()) {
1638 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001639 // FIXME: Better diagnostic.
1640 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001641 return false;
1642 }
1643
1644 Size = Info.Ctx.getTypeSizeInChars(Type);
1645 return true;
1646}
1647
1648/// Update a pointer value to model pointer arithmetic.
1649/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001650/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001651/// \param LVal - The pointer value to be updated.
1652/// \param EltTy - The pointee type represented by LVal.
1653/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001654static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1655 LValue &LVal, QualType EltTy,
1656 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001657 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001658 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001659 return false;
1660
1661 // Compute the new offset in the appropriate width.
1662 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001663 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001664 return true;
1665}
1666
Richard Smith66c96992012-02-18 22:04:06 +00001667/// Update an lvalue to refer to a component of a complex number.
1668/// \param Info - Information about the ongoing evaluation.
1669/// \param LVal - The lvalue to be updated.
1670/// \param EltTy - The complex number's component type.
1671/// \param Imag - False for the real component, true for the imaginary.
1672static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1673 LValue &LVal, QualType EltTy,
1674 bool Imag) {
1675 if (Imag) {
1676 CharUnits SizeOfComponent;
1677 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1678 return false;
1679 LVal.Offset += SizeOfComponent;
1680 }
1681 LVal.addComplex(Info, E, EltTy, Imag);
1682 return true;
1683}
1684
Richard Smith27908702011-10-24 17:54:18 +00001685/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001686///
1687/// \param Info Information about the ongoing evaluation.
1688/// \param E An expression to be used when printing diagnostics.
1689/// \param VD The variable whose initializer should be obtained.
1690/// \param Frame The frame in which the variable was created. Must be null
1691/// if this variable is not local to the evaluation.
1692/// \param Result Filled in with a pointer to the value of the variable.
1693static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1694 const VarDecl *VD, CallStackFrame *Frame,
1695 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001696 // If this is a parameter to an active constexpr function call, perform
1697 // argument substitution.
1698 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001699 // Assume arguments of a potential constant expression are unknown
1700 // constant expressions.
1701 if (Info.CheckingPotentialConstantExpression)
1702 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001703 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001704 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001705 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001706 }
Richard Smith3229b742013-05-05 21:17:10 +00001707 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00001708 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001709 }
Richard Smith27908702011-10-24 17:54:18 +00001710
Richard Smithd9f663b2013-04-22 15:31:51 +00001711 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00001712 if (Frame) {
1713 Result = &Frame->Temporaries[VD];
Richard Smithd9f663b2013-04-22 15:31:51 +00001714 // If we've carried on past an unevaluatable local variable initializer,
1715 // we can't go any further. This can happen during potential constant
1716 // expression checking.
Richard Smith3229b742013-05-05 21:17:10 +00001717 return !Result->isUninit();
Richard Smithd9f663b2013-04-22 15:31:51 +00001718 }
1719
Richard Smithd0b4dd62011-12-19 06:19:21 +00001720 // Dig out the initializer, and use the declaration which it's attached to.
1721 const Expr *Init = VD->getAnyInitializer(VD);
1722 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001723 // If we're checking a potential constant expression, the variable could be
1724 // initialized later.
1725 if (!Info.CheckingPotentialConstantExpression)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001726 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001727 return false;
1728 }
1729
Richard Smithd62306a2011-11-10 06:34:14 +00001730 // If we're currently evaluating the initializer of this declaration, use that
1731 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00001732 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00001733 Result = Info.EvaluatingDeclValue;
1734 return !Result->isUninit();
Richard Smithd62306a2011-11-10 06:34:14 +00001735 }
1736
Richard Smithcecf1842011-11-01 21:06:14 +00001737 // Never evaluate the initializer of a weak variable. We can't be sure that
1738 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001739 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001740 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001741 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001742 }
Richard Smithcecf1842011-11-01 21:06:14 +00001743
Richard Smithd0b4dd62011-12-19 06:19:21 +00001744 // Check that we can fold the initializer. In C++, we will have already done
1745 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001746 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001747 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001748 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001749 Notes.size() + 1) << VD;
1750 Info.Note(VD->getLocation(), diag::note_declared_at);
1751 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001752 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001753 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001754 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001755 Notes.size() + 1) << VD;
1756 Info.Note(VD->getLocation(), diag::note_declared_at);
1757 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001758 }
Richard Smith27908702011-10-24 17:54:18 +00001759
Richard Smith3229b742013-05-05 21:17:10 +00001760 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001761 return true;
Richard Smith27908702011-10-24 17:54:18 +00001762}
1763
Richard Smith11562c52011-10-28 17:51:58 +00001764static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001765 Qualifiers Quals = T.getQualifiers();
1766 return Quals.hasConst() && !Quals.hasVolatile();
1767}
1768
Richard Smithe97cbd72011-11-11 04:05:33 +00001769/// Get the base index of the given base class within an APValue representing
1770/// the given derived class.
1771static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1772 const CXXRecordDecl *Base) {
1773 Base = Base->getCanonicalDecl();
1774 unsigned Index = 0;
1775 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1776 E = Derived->bases_end(); I != E; ++I, ++Index) {
1777 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1778 return Index;
1779 }
1780
1781 llvm_unreachable("base class missing from derived class's bases list");
1782}
1783
Richard Smith3da88fa2013-04-26 14:36:30 +00001784/// Extract the value of a character from a string literal.
1785static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1786 uint64_t Index) {
Richard Smith14a94132012-02-17 03:35:37 +00001787 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith3da88fa2013-04-26 14:36:30 +00001788 const StringLiteral *S = cast<StringLiteral>(Lit);
1789 const ConstantArrayType *CAT =
1790 Info.Ctx.getAsConstantArrayType(S->getType());
1791 assert(CAT && "string literal isn't an array");
1792 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00001793 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00001794
1795 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00001796 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00001797 if (Index < S->getLength())
1798 Value = S->getCodeUnit(Index);
1799 return Value;
1800}
1801
Richard Smith3da88fa2013-04-26 14:36:30 +00001802// Expand a string literal into an array of characters.
1803static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
1804 APValue &Result) {
1805 const StringLiteral *S = cast<StringLiteral>(Lit);
1806 const ConstantArrayType *CAT =
1807 Info.Ctx.getAsConstantArrayType(S->getType());
1808 assert(CAT && "string literal isn't an array");
1809 QualType CharType = CAT->getElementType();
1810 assert(CharType->isIntegerType() && "unexpected character type");
1811
1812 unsigned Elts = CAT->getSize().getZExtValue();
1813 Result = APValue(APValue::UninitArray(),
1814 std::min(S->getLength(), Elts), Elts);
1815 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1816 CharType->isUnsignedIntegerType());
1817 if (Result.hasArrayFiller())
1818 Result.getArrayFiller() = APValue(Value);
1819 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
1820 Value = S->getCodeUnit(I);
1821 Result.getArrayInitializedElt(I) = APValue(Value);
1822 }
1823}
1824
1825// Expand an array so that it has more than Index filled elements.
1826static void expandArray(APValue &Array, unsigned Index) {
1827 unsigned Size = Array.getArraySize();
1828 assert(Index < Size);
1829
1830 // Always at least double the number of elements for which we store a value.
1831 unsigned OldElts = Array.getArrayInitializedElts();
1832 unsigned NewElts = std::max(Index+1, OldElts * 2);
1833 NewElts = std::min(Size, std::max(NewElts, 8u));
1834
1835 // Copy the data across.
1836 APValue NewValue(APValue::UninitArray(), NewElts, Size);
1837 for (unsigned I = 0; I != OldElts; ++I)
1838 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
1839 for (unsigned I = OldElts; I != NewElts; ++I)
1840 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
1841 if (NewValue.hasArrayFiller())
1842 NewValue.getArrayFiller() = Array.getArrayFiller();
1843 Array.swap(NewValue);
1844}
1845
Richard Smith861b5b52013-05-07 23:34:45 +00001846/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00001847enum AccessKinds {
1848 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00001849 AK_Assign,
1850 AK_Increment,
1851 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00001852};
1853
Richard Smith3229b742013-05-05 21:17:10 +00001854/// A handle to a complete object (an object that is not a subobject of
1855/// another object).
1856struct CompleteObject {
1857 /// The value of the complete object.
1858 APValue *Value;
1859 /// The type of the complete object.
1860 QualType Type;
1861
1862 CompleteObject() : Value(0) {}
1863 CompleteObject(APValue *Value, QualType Type)
1864 : Value(Value), Type(Type) {
1865 assert(Value && "missing value for complete object");
1866 }
1867
David Blaikie7d170102013-05-15 07:37:26 +00001868 LLVM_EXPLICIT operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00001869};
1870
Richard Smith3da88fa2013-04-26 14:36:30 +00001871/// Find the designated sub-object of an rvalue.
1872template<typename SubobjectHandler>
1873typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00001874findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00001875 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001876 if (Sub.Invalid)
1877 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00001878 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00001879 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001880 if (Info.getLangOpts().CPlusPlus11)
1881 Info.Diag(E, diag::note_constexpr_access_past_end)
1882 << handler.AccessKind;
1883 else
1884 Info.Diag(E);
1885 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001886 }
Richard Smith6804be52011-11-11 08:28:03 +00001887 if (Sub.Entries.empty())
Richard Smith3229b742013-05-05 21:17:10 +00001888 return handler.found(*Obj.Value, Obj.Type);
1889 if (Info.CheckingPotentialConstantExpression && Obj.Value->isUninit())
Richard Smith253c2a32012-01-27 01:14:48 +00001890 // This object might be initialized later.
Richard Smith3da88fa2013-04-26 14:36:30 +00001891 return handler.failed();
Richard Smithf3e9e432011-11-07 09:22:26 +00001892
Richard Smith3229b742013-05-05 21:17:10 +00001893 APValue *O = Obj.Value;
1894 QualType ObjType = Obj.Type;
Richard Smithd62306a2011-11-10 06:34:14 +00001895 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001896 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001897 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001898 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001899 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001900 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001901 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001902 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001903 // Note, it should not be possible to form a pointer with a valid
1904 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00001905 if (Info.getLangOpts().CPlusPlus11)
1906 Info.Diag(E, diag::note_constexpr_access_past_end)
1907 << handler.AccessKind;
1908 else
1909 Info.Diag(E);
1910 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001911 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001912
1913 ObjType = CAT->getElementType();
1914
Richard Smith14a94132012-02-17 03:35:37 +00001915 // An array object is represented as either an Array APValue or as an
1916 // LValue which refers to a string literal.
1917 if (O->isLValue()) {
1918 assert(I == N - 1 && "extracting subobject of character?");
1919 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00001920 if (handler.AccessKind != AK_Read)
1921 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
1922 *O);
1923 else
1924 return handler.foundString(*O, ObjType, Index);
1925 }
1926
1927 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00001928 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00001929 else if (handler.AccessKind != AK_Read) {
1930 expandArray(*O, Index);
1931 O = &O->getArrayInitializedElt(Index);
1932 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00001933 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00001934 } else if (ObjType->isAnyComplexType()) {
1935 // Next subobject is a complex number.
1936 uint64_t Index = Sub.Entries[I].ArrayIndex;
1937 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001938 if (Info.getLangOpts().CPlusPlus11)
1939 Info.Diag(E, diag::note_constexpr_access_past_end)
1940 << handler.AccessKind;
1941 else
1942 Info.Diag(E);
1943 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00001944 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001945
1946 bool WasConstQualified = ObjType.isConstQualified();
1947 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1948 if (WasConstQualified)
1949 ObjType.addConst();
1950
Richard Smith66c96992012-02-18 22:04:06 +00001951 assert(I == N - 1 && "extracting subobject of scalar?");
1952 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001953 return handler.found(Index ? O->getComplexIntImag()
1954 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001955 } else {
1956 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00001957 return handler.found(Index ? O->getComplexFloatImag()
1958 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001959 }
Richard Smithd62306a2011-11-10 06:34:14 +00001960 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001961 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001962 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00001963 << Field;
1964 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00001965 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00001966 }
1967
Richard Smithd62306a2011-11-10 06:34:14 +00001968 // Next subobject is a class, struct or union field.
1969 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1970 if (RD->isUnion()) {
1971 const FieldDecl *UnionField = O->getUnionField();
1972 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001973 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001974 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
1975 << handler.AccessKind << Field << !UnionField << UnionField;
1976 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001977 }
Richard Smithd62306a2011-11-10 06:34:14 +00001978 O = &O->getUnionValue();
1979 } else
1980 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00001981
1982 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00001983 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00001984 if (WasConstQualified && !Field->isMutable())
1985 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00001986
1987 if (ObjType.isVolatileQualified()) {
1988 if (Info.getLangOpts().CPlusPlus) {
1989 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00001990 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
1991 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00001992 Info.Note(Field->getLocation(), diag::note_declared_at);
1993 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001994 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001995 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001996 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001997 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001998 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001999 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002000 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2001 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2002 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002003
2004 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002005 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002006 if (WasConstQualified)
2007 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002008 }
Richard Smithd62306a2011-11-10 06:34:14 +00002009
Richard Smithf57d8cb2011-12-09 22:58:01 +00002010 if (O->isUninit()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002011 if (!Info.CheckingPotentialConstantExpression)
Richard Smith3da88fa2013-04-26 14:36:30 +00002012 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2013 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002014 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002015 }
2016
Richard Smith3da88fa2013-04-26 14:36:30 +00002017 return handler.found(*O, ObjType);
2018}
2019
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002020namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002021struct ExtractSubobjectHandler {
2022 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002023 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002024
2025 static const AccessKinds AccessKind = AK_Read;
2026
2027 typedef bool result_type;
2028 bool failed() { return false; }
2029 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002030 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002031 return true;
2032 }
2033 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002034 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002035 return true;
2036 }
2037 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002038 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002039 return true;
2040 }
2041 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002042 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002043 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2044 return true;
2045 }
2046};
Richard Smith3229b742013-05-05 21:17:10 +00002047} // end anonymous namespace
2048
Richard Smith3da88fa2013-04-26 14:36:30 +00002049const AccessKinds ExtractSubobjectHandler::AccessKind;
2050
2051/// Extract the designated sub-object of an rvalue.
2052static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002053 const CompleteObject &Obj,
2054 const SubobjectDesignator &Sub,
2055 APValue &Result) {
2056 ExtractSubobjectHandler Handler = { Info, Result };
2057 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002058}
2059
Richard Smith3229b742013-05-05 21:17:10 +00002060namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002061struct ModifySubobjectHandler {
2062 EvalInfo &Info;
2063 APValue &NewVal;
2064 const Expr *E;
2065
2066 typedef bool result_type;
2067 static const AccessKinds AccessKind = AK_Assign;
2068
2069 bool checkConst(QualType QT) {
2070 // Assigning to a const object has undefined behavior.
2071 if (QT.isConstQualified()) {
2072 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2073 return false;
2074 }
2075 return true;
2076 }
2077
2078 bool failed() { return false; }
2079 bool found(APValue &Subobj, QualType SubobjType) {
2080 if (!checkConst(SubobjType))
2081 return false;
2082 // We've been given ownership of NewVal, so just swap it in.
2083 Subobj.swap(NewVal);
2084 return true;
2085 }
2086 bool found(APSInt &Value, QualType SubobjType) {
2087 if (!checkConst(SubobjType))
2088 return false;
2089 if (!NewVal.isInt()) {
2090 // Maybe trying to write a cast pointer value into a complex?
2091 Info.Diag(E);
2092 return false;
2093 }
2094 Value = NewVal.getInt();
2095 return true;
2096 }
2097 bool found(APFloat &Value, QualType SubobjType) {
2098 if (!checkConst(SubobjType))
2099 return false;
2100 Value = NewVal.getFloat();
2101 return true;
2102 }
2103 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2104 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2105 }
2106};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002107} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002108
Richard Smith3229b742013-05-05 21:17:10 +00002109const AccessKinds ModifySubobjectHandler::AccessKind;
2110
Richard Smith3da88fa2013-04-26 14:36:30 +00002111/// Update the designated sub-object of an rvalue to the given value.
2112static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002113 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002114 const SubobjectDesignator &Sub,
2115 APValue &NewVal) {
2116 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002117 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002118}
2119
Richard Smith84f6dcf2012-02-02 01:16:57 +00002120/// Find the position where two subobject designators diverge, or equivalently
2121/// the length of the common initial subsequence.
2122static unsigned FindDesignatorMismatch(QualType ObjType,
2123 const SubobjectDesignator &A,
2124 const SubobjectDesignator &B,
2125 bool &WasArrayIndex) {
2126 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2127 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002128 if (!ObjType.isNull() &&
2129 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002130 // Next subobject is an array element.
2131 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2132 WasArrayIndex = true;
2133 return I;
2134 }
Richard Smith66c96992012-02-18 22:04:06 +00002135 if (ObjType->isAnyComplexType())
2136 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2137 else
2138 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002139 } else {
2140 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2141 WasArrayIndex = false;
2142 return I;
2143 }
2144 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2145 // Next subobject is a field.
2146 ObjType = FD->getType();
2147 else
2148 // Next subobject is a base class.
2149 ObjType = QualType();
2150 }
2151 }
2152 WasArrayIndex = false;
2153 return I;
2154}
2155
2156/// Determine whether the given subobject designators refer to elements of the
2157/// same array object.
2158static bool AreElementsOfSameArray(QualType ObjType,
2159 const SubobjectDesignator &A,
2160 const SubobjectDesignator &B) {
2161 if (A.Entries.size() != B.Entries.size())
2162 return false;
2163
2164 bool IsArray = A.MostDerivedArraySize != 0;
2165 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2166 // A is a subobject of the array element.
2167 return false;
2168
2169 // If A (and B) designates an array element, the last entry will be the array
2170 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2171 // of length 1' case, and the entire path must match.
2172 bool WasArrayIndex;
2173 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2174 return CommonLength >= A.Entries.size() - IsArray;
2175}
2176
Richard Smith3229b742013-05-05 21:17:10 +00002177/// Find the complete object to which an LValue refers.
2178CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
2179 const LValue &LVal, QualType LValType) {
2180 if (!LVal.Base) {
2181 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2182 return CompleteObject();
2183 }
2184
2185 CallStackFrame *Frame = 0;
2186 if (LVal.CallIndex) {
2187 Frame = Info.getCallFrame(LVal.CallIndex);
2188 if (!Frame) {
2189 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2190 << AK << LVal.Base.is<const ValueDecl*>();
2191 NoteLValueLocation(Info, LVal.Base);
2192 return CompleteObject();
2193 }
Richard Smith3229b742013-05-05 21:17:10 +00002194 }
2195
2196 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2197 // is not a constant expression (even if the object is non-volatile). We also
2198 // apply this rule to C++98, in order to conform to the expected 'volatile'
2199 // semantics.
2200 if (LValType.isVolatileQualified()) {
2201 if (Info.getLangOpts().CPlusPlus)
2202 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2203 << AK << LValType;
2204 else
2205 Info.Diag(E);
2206 return CompleteObject();
2207 }
2208
2209 // Compute value storage location and type of base object.
2210 APValue *BaseVal = 0;
Richard Smith84401042013-06-03 05:03:02 +00002211 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002212
2213 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2214 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2215 // In C++11, constexpr, non-volatile variables initialized with constant
2216 // expressions are constant expressions too. Inside constexpr functions,
2217 // parameters are constant expressions even if they're non-const.
2218 // In C++1y, objects local to a constant expression (those with a Frame) are
2219 // both readable and writable inside constant expressions.
2220 // In C, such things can also be folded, although they are not ICEs.
2221 const VarDecl *VD = dyn_cast<VarDecl>(D);
2222 if (VD) {
2223 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2224 VD = VDef;
2225 }
2226 if (!VD || VD->isInvalidDecl()) {
2227 Info.Diag(E);
2228 return CompleteObject();
2229 }
2230
2231 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002232 if (BaseType.isVolatileQualified()) {
2233 if (Info.getLangOpts().CPlusPlus) {
2234 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2235 << AK << 1 << VD;
2236 Info.Note(VD->getLocation(), diag::note_declared_at);
2237 } else {
2238 Info.Diag(E);
2239 }
2240 return CompleteObject();
2241 }
2242
2243 // Unless we're looking at a local variable or argument in a constexpr call,
2244 // the variable we're reading must be const.
2245 if (!Frame) {
Richard Smith7525ff62013-05-09 07:14:00 +00002246 if (Info.getLangOpts().CPlusPlus1y &&
2247 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2248 // OK, we can read and modify an object if we're in the process of
2249 // evaluating its initializer, because its lifetime began in this
2250 // evaluation.
2251 } else if (AK != AK_Read) {
2252 // All the remaining cases only permit reading.
2253 Info.Diag(E, diag::note_constexpr_modify_global);
2254 return CompleteObject();
2255 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002256 // OK, we can read this variable.
2257 } else if (BaseType->isIntegralOrEnumerationType()) {
2258 if (!BaseType.isConstQualified()) {
2259 if (Info.getLangOpts().CPlusPlus) {
2260 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2261 Info.Note(VD->getLocation(), diag::note_declared_at);
2262 } else {
2263 Info.Diag(E);
2264 }
2265 return CompleteObject();
2266 }
2267 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2268 // We support folding of const floating-point types, in order to make
2269 // static const data members of such types (supported as an extension)
2270 // more useful.
2271 if (Info.getLangOpts().CPlusPlus11) {
2272 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2273 Info.Note(VD->getLocation(), diag::note_declared_at);
2274 } else {
2275 Info.CCEDiag(E);
2276 }
2277 } else {
2278 // FIXME: Allow folding of values of any literal type in all languages.
2279 if (Info.getLangOpts().CPlusPlus11) {
2280 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2281 Info.Note(VD->getLocation(), diag::note_declared_at);
2282 } else {
2283 Info.Diag(E);
2284 }
2285 return CompleteObject();
2286 }
2287 }
2288
2289 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2290 return CompleteObject();
2291 } else {
2292 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2293
2294 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002295 if (const MaterializeTemporaryExpr *MTE =
2296 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2297 assert(MTE->getStorageDuration() == SD_Static &&
2298 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002299
Richard Smithe6c01442013-06-05 00:46:14 +00002300 // Per C++1y [expr.const]p2:
2301 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2302 // - a [...] glvalue of integral or enumeration type that refers to
2303 // a non-volatile const object [...]
2304 // [...]
2305 // - a [...] glvalue of literal type that refers to a non-volatile
2306 // object whose lifetime began within the evaluation of e.
2307 //
2308 // C++11 misses the 'began within the evaluation of e' check and
2309 // instead allows all temporaries, including things like:
2310 // int &&r = 1;
2311 // int x = ++r;
2312 // constexpr int k = r;
2313 // Therefore we use the C++1y rules in C++11 too.
2314 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2315 const ValueDecl *ED = MTE->getExtendingDecl();
2316 if (!(BaseType.isConstQualified() &&
2317 BaseType->isIntegralOrEnumerationType()) &&
2318 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2319 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2320 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2321 return CompleteObject();
2322 }
2323
2324 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2325 assert(BaseVal && "got reference to unevaluated temporary");
2326 } else {
2327 Info.Diag(E);
2328 return CompleteObject();
2329 }
2330 } else {
2331 BaseVal = &Frame->Temporaries[Base];
2332 }
Richard Smith3229b742013-05-05 21:17:10 +00002333
2334 // Volatile temporary objects cannot be accessed in constant expressions.
2335 if (BaseType.isVolatileQualified()) {
2336 if (Info.getLangOpts().CPlusPlus) {
2337 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2338 << AK << 0;
2339 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2340 } else {
2341 Info.Diag(E);
2342 }
2343 return CompleteObject();
2344 }
2345 }
2346
Richard Smith7525ff62013-05-09 07:14:00 +00002347 // During the construction of an object, it is not yet 'const'.
2348 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2349 // and this doesn't do quite the right thing for const subobjects of the
2350 // object under construction.
2351 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2352 BaseType = Info.Ctx.getCanonicalType(BaseType);
2353 BaseType.removeLocalConst();
2354 }
2355
Richard Smith3229b742013-05-05 21:17:10 +00002356 // In C++1y, we can't safely access any mutable state when checking a
2357 // potential constant expression.
2358 if (Frame && Info.getLangOpts().CPlusPlus1y &&
2359 Info.CheckingPotentialConstantExpression)
2360 return CompleteObject();
2361
2362 return CompleteObject(BaseVal, BaseType);
2363}
2364
Richard Smith243ef902013-05-05 23:31:59 +00002365/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2366/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2367/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002368///
2369/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002370/// \param Conv - The expression for which we are performing the conversion.
2371/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002372/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2373/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002374/// \param LVal - The glvalue on which we are attempting to perform this action.
2375/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002376static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002377 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002378 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002379 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002380 return false;
2381
Richard Smith3229b742013-05-05 21:17:10 +00002382 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002383 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith3229b742013-05-05 21:17:10 +00002384 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2385 !Type.isVolatileQualified()) {
2386 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2387 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2388 // initializer until now for such expressions. Such an expression can't be
2389 // an ICE in C, so this only matters for fold.
2390 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2391 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002392 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002393 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002394 }
Richard Smith3229b742013-05-05 21:17:10 +00002395 APValue Lit;
2396 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2397 return false;
2398 CompleteObject LitObj(&Lit, Base->getType());
2399 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2400 } else if (isa<StringLiteral>(Base)) {
2401 // We represent a string literal array as an lvalue pointing at the
2402 // corresponding expression, rather than building an array of chars.
2403 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2404 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2405 CompleteObject StrObj(&Str, Base->getType());
2406 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002407 }
Richard Smith11562c52011-10-28 17:51:58 +00002408 }
2409
Richard Smith3229b742013-05-05 21:17:10 +00002410 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2411 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002412}
2413
2414/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002415static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002416 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002417 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002418 return false;
2419
Richard Smith3229b742013-05-05 21:17:10 +00002420 if (!Info.getLangOpts().CPlusPlus1y) {
2421 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002422 return false;
2423 }
2424
Richard Smith3229b742013-05-05 21:17:10 +00002425 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2426 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002427}
2428
Richard Smith243ef902013-05-05 23:31:59 +00002429static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2430 return T->isSignedIntegerType() &&
2431 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2432}
2433
2434namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002435struct CompoundAssignSubobjectHandler {
2436 EvalInfo &Info;
2437 const Expr *E;
2438 QualType PromotedLHSType;
2439 BinaryOperatorKind Opcode;
2440 const APValue &RHS;
2441
2442 static const AccessKinds AccessKind = AK_Assign;
2443
2444 typedef bool result_type;
2445
2446 bool checkConst(QualType QT) {
2447 // Assigning to a const object has undefined behavior.
2448 if (QT.isConstQualified()) {
2449 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2450 return false;
2451 }
2452 return true;
2453 }
2454
2455 bool failed() { return false; }
2456 bool found(APValue &Subobj, QualType SubobjType) {
2457 switch (Subobj.getKind()) {
2458 case APValue::Int:
2459 return found(Subobj.getInt(), SubobjType);
2460 case APValue::Float:
2461 return found(Subobj.getFloat(), SubobjType);
2462 case APValue::ComplexInt:
2463 case APValue::ComplexFloat:
2464 // FIXME: Implement complex compound assignment.
2465 Info.Diag(E);
2466 return false;
2467 case APValue::LValue:
2468 return foundPointer(Subobj, SubobjType);
2469 default:
2470 // FIXME: can this happen?
2471 Info.Diag(E);
2472 return false;
2473 }
2474 }
2475 bool found(APSInt &Value, QualType SubobjType) {
2476 if (!checkConst(SubobjType))
2477 return false;
2478
2479 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2480 // We don't support compound assignment on integer-cast-to-pointer
2481 // values.
2482 Info.Diag(E);
2483 return false;
2484 }
2485
2486 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2487 SubobjType, Value);
2488 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2489 return false;
2490 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2491 return true;
2492 }
2493 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002494 return checkConst(SubobjType) &&
2495 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2496 Value) &&
2497 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2498 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00002499 }
2500 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2501 if (!checkConst(SubobjType))
2502 return false;
2503
2504 QualType PointeeType;
2505 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2506 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00002507
2508 if (PointeeType.isNull() || !RHS.isInt() ||
2509 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00002510 Info.Diag(E);
2511 return false;
2512 }
2513
Richard Smith861b5b52013-05-07 23:34:45 +00002514 int64_t Offset = getExtValue(RHS.getInt());
2515 if (Opcode == BO_Sub)
2516 Offset = -Offset;
2517
2518 LValue LVal;
2519 LVal.setFrom(Info.Ctx, Subobj);
2520 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2521 return false;
2522 LVal.moveInto(Subobj);
2523 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002524 }
2525 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2526 llvm_unreachable("shouldn't encounter string elements here");
2527 }
2528};
2529} // end anonymous namespace
2530
2531const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2532
2533/// Perform a compound assignment of LVal <op>= RVal.
2534static bool handleCompoundAssignment(
2535 EvalInfo &Info, const Expr *E,
2536 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2537 BinaryOperatorKind Opcode, const APValue &RVal) {
2538 if (LVal.Designator.Invalid)
2539 return false;
2540
2541 if (!Info.getLangOpts().CPlusPlus1y) {
2542 Info.Diag(E);
2543 return false;
2544 }
2545
2546 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2547 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2548 RVal };
2549 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2550}
2551
2552namespace {
Richard Smith243ef902013-05-05 23:31:59 +00002553struct IncDecSubobjectHandler {
2554 EvalInfo &Info;
2555 const Expr *E;
2556 AccessKinds AccessKind;
2557 APValue *Old;
2558
2559 typedef bool result_type;
2560
2561 bool checkConst(QualType QT) {
2562 // Assigning to a const object has undefined behavior.
2563 if (QT.isConstQualified()) {
2564 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2565 return false;
2566 }
2567 return true;
2568 }
2569
2570 bool failed() { return false; }
2571 bool found(APValue &Subobj, QualType SubobjType) {
2572 // Stash the old value. Also clear Old, so we don't clobber it later
2573 // if we're post-incrementing a complex.
2574 if (Old) {
2575 *Old = Subobj;
2576 Old = 0;
2577 }
2578
2579 switch (Subobj.getKind()) {
2580 case APValue::Int:
2581 return found(Subobj.getInt(), SubobjType);
2582 case APValue::Float:
2583 return found(Subobj.getFloat(), SubobjType);
2584 case APValue::ComplexInt:
2585 return found(Subobj.getComplexIntReal(),
2586 SubobjType->castAs<ComplexType>()->getElementType()
2587 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2588 case APValue::ComplexFloat:
2589 return found(Subobj.getComplexFloatReal(),
2590 SubobjType->castAs<ComplexType>()->getElementType()
2591 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2592 case APValue::LValue:
2593 return foundPointer(Subobj, SubobjType);
2594 default:
2595 // FIXME: can this happen?
2596 Info.Diag(E);
2597 return false;
2598 }
2599 }
2600 bool found(APSInt &Value, QualType SubobjType) {
2601 if (!checkConst(SubobjType))
2602 return false;
2603
2604 if (!SubobjType->isIntegerType()) {
2605 // We don't support increment / decrement on integer-cast-to-pointer
2606 // values.
2607 Info.Diag(E);
2608 return false;
2609 }
2610
2611 if (Old) *Old = APValue(Value);
2612
2613 // bool arithmetic promotes to int, and the conversion back to bool
2614 // doesn't reduce mod 2^n, so special-case it.
2615 if (SubobjType->isBooleanType()) {
2616 if (AccessKind == AK_Increment)
2617 Value = 1;
2618 else
2619 Value = !Value;
2620 return true;
2621 }
2622
2623 bool WasNegative = Value.isNegative();
2624 if (AccessKind == AK_Increment) {
2625 ++Value;
2626
2627 if (!WasNegative && Value.isNegative() &&
2628 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2629 APSInt ActualValue(Value, /*IsUnsigned*/true);
2630 HandleOverflow(Info, E, ActualValue, SubobjType);
2631 }
2632 } else {
2633 --Value;
2634
2635 if (WasNegative && !Value.isNegative() &&
2636 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2637 unsigned BitWidth = Value.getBitWidth();
2638 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2639 ActualValue.setBit(BitWidth);
2640 HandleOverflow(Info, E, ActualValue, SubobjType);
2641 }
2642 }
2643 return true;
2644 }
2645 bool found(APFloat &Value, QualType SubobjType) {
2646 if (!checkConst(SubobjType))
2647 return false;
2648
2649 if (Old) *Old = APValue(Value);
2650
2651 APFloat One(Value.getSemantics(), 1);
2652 if (AccessKind == AK_Increment)
2653 Value.add(One, APFloat::rmNearestTiesToEven);
2654 else
2655 Value.subtract(One, APFloat::rmNearestTiesToEven);
2656 return true;
2657 }
2658 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2659 if (!checkConst(SubobjType))
2660 return false;
2661
2662 QualType PointeeType;
2663 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2664 PointeeType = PT->getPointeeType();
2665 else {
2666 Info.Diag(E);
2667 return false;
2668 }
2669
2670 LValue LVal;
2671 LVal.setFrom(Info.Ctx, Subobj);
2672 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2673 AccessKind == AK_Increment ? 1 : -1))
2674 return false;
2675 LVal.moveInto(Subobj);
2676 return true;
2677 }
2678 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2679 llvm_unreachable("shouldn't encounter string elements here");
2680 }
2681};
2682} // end anonymous namespace
2683
2684/// Perform an increment or decrement on LVal.
2685static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
2686 QualType LValType, bool IsIncrement, APValue *Old) {
2687 if (LVal.Designator.Invalid)
2688 return false;
2689
2690 if (!Info.getLangOpts().CPlusPlus1y) {
2691 Info.Diag(E);
2692 return false;
2693 }
2694
2695 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
2696 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
2697 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
2698 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2699}
2700
Richard Smithe97cbd72011-11-11 04:05:33 +00002701/// Build an lvalue for the object argument of a member function call.
2702static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2703 LValue &This) {
2704 if (Object->getType()->isPointerType())
2705 return EvaluatePointer(Object, This, Info);
2706
2707 if (Object->isGLValue())
2708 return EvaluateLValue(Object, This, Info);
2709
Richard Smithd9f663b2013-04-22 15:31:51 +00002710 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00002711 return EvaluateTemporary(Object, This, Info);
2712
2713 return false;
2714}
2715
2716/// HandleMemberPointerAccess - Evaluate a member access operation and build an
2717/// lvalue referring to the result.
2718///
2719/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00002720/// \param LV - An lvalue referring to the base of the member pointer.
2721/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00002722/// \param IncludeMember - Specifies whether the member itself is included in
2723/// the resulting LValue subobject designator. This is not possible when
2724/// creating a bound member function.
2725/// \return The field or method declaration to which the member pointer refers,
2726/// or 0 if evaluation fails.
2727static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00002728 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00002729 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00002730 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00002731 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00002732 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00002733 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Richard Smith027bf112011-11-17 22:56:20 +00002734 return 0;
2735
2736 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2737 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00002738 if (!MemPtr.getDecl()) {
2739 // FIXME: Specific diagnostic.
2740 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002741 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002742 }
Richard Smith253c2a32012-01-27 01:14:48 +00002743
Richard Smith027bf112011-11-17 22:56:20 +00002744 if (MemPtr.isDerivedMember()) {
2745 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00002746 // The end of the derived-to-base path for the base object must match the
2747 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00002748 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00002749 LV.Designator.Entries.size()) {
2750 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002751 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002752 }
Richard Smith027bf112011-11-17 22:56:20 +00002753 unsigned PathLengthToMember =
2754 LV.Designator.Entries.size() - MemPtr.Path.size();
2755 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
2756 const CXXRecordDecl *LVDecl = getAsBaseClass(
2757 LV.Designator.Entries[PathLengthToMember + I]);
2758 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00002759 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
2760 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002761 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002762 }
Richard Smith027bf112011-11-17 22:56:20 +00002763 }
2764
2765 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00002766 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00002767 PathLengthToMember))
2768 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002769 } else if (!MemPtr.Path.empty()) {
2770 // Extend the LValue path with the member pointer's path.
2771 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
2772 MemPtr.Path.size() + IncludeMember);
2773
2774 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00002775 if (const PointerType *PT = LVType->getAs<PointerType>())
2776 LVType = PT->getPointeeType();
2777 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
2778 assert(RD && "member pointer access on non-class-type expression");
2779 // The first class in the path is that of the lvalue.
2780 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
2781 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00002782 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
John McCalld7bca762012-05-01 00:38:49 +00002783 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002784 RD = Base;
2785 }
2786 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00002787 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
2788 MemPtr.getContainingRecord()))
John McCalld7bca762012-05-01 00:38:49 +00002789 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002790 }
2791
2792 // Add the member. Note that we cannot build bound member functions here.
2793 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00002794 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00002795 if (!HandleLValueMember(Info, RHS, LV, FD))
John McCalld7bca762012-05-01 00:38:49 +00002796 return 0;
2797 } else if (const IndirectFieldDecl *IFD =
2798 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00002799 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
John McCalld7bca762012-05-01 00:38:49 +00002800 return 0;
2801 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002802 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00002803 }
Richard Smith027bf112011-11-17 22:56:20 +00002804 }
2805
2806 return MemPtr.getDecl();
2807}
2808
Richard Smith84401042013-06-03 05:03:02 +00002809static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
2810 const BinaryOperator *BO,
2811 LValue &LV,
2812 bool IncludeMember = true) {
2813 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
2814
2815 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
2816 if (Info.keepEvaluatingAfterFailure()) {
2817 MemberPtr MemPtr;
2818 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
2819 }
2820 return 0;
2821 }
2822
2823 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
2824 BO->getRHS(), IncludeMember);
2825}
2826
Richard Smith027bf112011-11-17 22:56:20 +00002827/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
2828/// the provided lvalue, which currently refers to the base object.
2829static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
2830 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00002831 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002832 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00002833 return false;
2834
Richard Smitha8105bc2012-01-06 16:39:00 +00002835 QualType TargetQT = E->getType();
2836 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2837 TargetQT = PT->getPointeeType();
2838
2839 // Check this cast lands within the final derived-to-base subobject path.
2840 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002841 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002842 << D.MostDerivedType << TargetQT;
2843 return false;
2844 }
2845
Richard Smith027bf112011-11-17 22:56:20 +00002846 // Check the type of the final cast. We don't need to check the path,
2847 // since a cast can only be formed if the path is unique.
2848 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00002849 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2850 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00002851 if (NewEntriesSize == D.MostDerivedPathLength)
2852 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2853 else
Richard Smith027bf112011-11-17 22:56:20 +00002854 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00002855 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002856 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002857 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00002858 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00002859 }
Richard Smith027bf112011-11-17 22:56:20 +00002860
2861 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002862 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00002863}
2864
Mike Stump876387b2009-10-27 22:09:17 +00002865namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00002866enum EvalStmtResult {
2867 /// Evaluation failed.
2868 ESR_Failed,
2869 /// Hit a 'return' statement.
2870 ESR_Returned,
2871 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00002872 ESR_Succeeded,
2873 /// Hit a 'continue' statement.
2874 ESR_Continue,
2875 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00002876 ESR_Break,
2877 /// Still scanning for 'case' or 'default' statement.
2878 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00002879};
2880}
2881
Richard Smithd9f663b2013-04-22 15:31:51 +00002882static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
2883 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2884 // We don't need to evaluate the initializer for a static local.
2885 if (!VD->hasLocalStorage())
2886 return true;
2887
2888 LValue Result;
2889 Result.set(VD, Info.CurrentCall->Index);
2890 APValue &Val = Info.CurrentCall->Temporaries[VD];
2891
Richard Smith51f03172013-06-20 03:00:05 +00002892 if (!VD->getInit()) {
2893 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
2894 << false << VD->getType();
2895 Val = APValue();
2896 return false;
2897 }
2898
Richard Smithd9f663b2013-04-22 15:31:51 +00002899 if (!EvaluateInPlace(Val, Info, Result, VD->getInit())) {
2900 // Wipe out any partially-computed value, to allow tracking that this
2901 // evaluation failed.
2902 Val = APValue();
2903 return false;
2904 }
2905 }
2906
2907 return true;
2908}
2909
Richard Smith4e18ca52013-05-06 05:56:11 +00002910/// Evaluate a condition (either a variable declaration or an expression).
2911static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
2912 const Expr *Cond, bool &Result) {
2913 if (CondDecl && !EvaluateDecl(Info, CondDecl))
2914 return false;
2915 return EvaluateAsBooleanCondition(Cond, Result, Info);
2916}
2917
2918static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00002919 const Stmt *S, const SwitchCase *SC = 0);
Richard Smith4e18ca52013-05-06 05:56:11 +00002920
2921/// Evaluate the body of a loop, and translate the result as appropriate.
2922static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00002923 const Stmt *Body,
2924 const SwitchCase *Case = 0) {
2925 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00002926 case ESR_Break:
2927 return ESR_Succeeded;
2928 case ESR_Succeeded:
2929 case ESR_Continue:
2930 return ESR_Continue;
2931 case ESR_Failed:
2932 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00002933 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00002934 return ESR;
2935 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00002936 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00002937}
2938
Richard Smith496ddcf2013-05-12 17:32:42 +00002939/// Evaluate a switch statement.
2940static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
2941 const SwitchStmt *SS) {
2942 // Evaluate the switch condition.
2943 if (SS->getConditionVariable() &&
2944 !EvaluateDecl(Info, SS->getConditionVariable()))
2945 return ESR_Failed;
2946 APSInt Value;
2947 if (!EvaluateInteger(SS->getCond(), Value, Info))
2948 return ESR_Failed;
2949
2950 // Find the switch case corresponding to the value of the condition.
2951 // FIXME: Cache this lookup.
2952 const SwitchCase *Found = 0;
2953 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
2954 SC = SC->getNextSwitchCase()) {
2955 if (isa<DefaultStmt>(SC)) {
2956 Found = SC;
2957 continue;
2958 }
2959
2960 const CaseStmt *CS = cast<CaseStmt>(SC);
2961 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
2962 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
2963 : LHS;
2964 if (LHS <= Value && Value <= RHS) {
2965 Found = SC;
2966 break;
2967 }
2968 }
2969
2970 if (!Found)
2971 return ESR_Succeeded;
2972
2973 // Search the switch body for the switch case and evaluate it from there.
2974 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
2975 case ESR_Break:
2976 return ESR_Succeeded;
2977 case ESR_Succeeded:
2978 case ESR_Continue:
2979 case ESR_Failed:
2980 case ESR_Returned:
2981 return ESR;
2982 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00002983 // This can only happen if the switch case is nested within a statement
2984 // expression. We have no intention of supporting that.
2985 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
2986 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00002987 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00002988 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00002989}
2990
Richard Smith254a73d2011-10-28 22:34:42 +00002991// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00002992static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00002993 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00002994 if (!Info.nextStep(S))
2995 return ESR_Failed;
2996
Richard Smith496ddcf2013-05-12 17:32:42 +00002997 // If we're hunting down a 'case' or 'default' label, recurse through
2998 // substatements until we hit the label.
2999 if (Case) {
3000 // FIXME: We don't start the lifetime of objects whose initialization we
3001 // jump over. However, such objects must be of class type with a trivial
3002 // default constructor that initialize all subobjects, so must be empty,
3003 // so this almost never matters.
3004 switch (S->getStmtClass()) {
3005 case Stmt::CompoundStmtClass:
3006 // FIXME: Precompute which substatement of a compound statement we
3007 // would jump to, and go straight there rather than performing a
3008 // linear scan each time.
3009 case Stmt::LabelStmtClass:
3010 case Stmt::AttributedStmtClass:
3011 case Stmt::DoStmtClass:
3012 break;
3013
3014 case Stmt::CaseStmtClass:
3015 case Stmt::DefaultStmtClass:
3016 if (Case == S)
3017 Case = 0;
3018 break;
3019
3020 case Stmt::IfStmtClass: {
3021 // FIXME: Precompute which side of an 'if' we would jump to, and go
3022 // straight there rather than scanning both sides.
3023 const IfStmt *IS = cast<IfStmt>(S);
3024 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3025 if (ESR != ESR_CaseNotFound || !IS->getElse())
3026 return ESR;
3027 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3028 }
3029
3030 case Stmt::WhileStmtClass: {
3031 EvalStmtResult ESR =
3032 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3033 if (ESR != ESR_Continue)
3034 return ESR;
3035 break;
3036 }
3037
3038 case Stmt::ForStmtClass: {
3039 const ForStmt *FS = cast<ForStmt>(S);
3040 EvalStmtResult ESR =
3041 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3042 if (ESR != ESR_Continue)
3043 return ESR;
3044 if (FS->getInc() && !EvaluateIgnoredValue(Info, FS->getInc()))
3045 return ESR_Failed;
3046 break;
3047 }
3048
3049 case Stmt::DeclStmtClass:
3050 // FIXME: If the variable has initialization that can't be jumped over,
3051 // bail out of any immediately-surrounding compound-statement too.
3052 default:
3053 return ESR_CaseNotFound;
3054 }
3055 }
3056
Richard Smithd9f663b2013-04-22 15:31:51 +00003057 // FIXME: Mark all temporaries in the current frame as destroyed at
3058 // the end of each full-expression.
Richard Smith254a73d2011-10-28 22:34:42 +00003059 switch (S->getStmtClass()) {
3060 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003061 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003062 // Don't bother evaluating beyond an expression-statement which couldn't
3063 // be evaluated.
Richard Smith4e18ca52013-05-06 05:56:11 +00003064 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003065 return ESR_Failed;
3066 return ESR_Succeeded;
3067 }
3068
3069 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003070 return ESR_Failed;
3071
3072 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003073 return ESR_Succeeded;
3074
Richard Smithd9f663b2013-04-22 15:31:51 +00003075 case Stmt::DeclStmtClass: {
3076 const DeclStmt *DS = cast<DeclStmt>(S);
3077 for (DeclStmt::const_decl_iterator DclIt = DS->decl_begin(),
3078 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt)
3079 if (!EvaluateDecl(Info, *DclIt) && !Info.keepEvaluatingAfterFailure())
3080 return ESR_Failed;
3081 return ESR_Succeeded;
3082 }
3083
Richard Smith357362d2011-12-13 06:39:58 +00003084 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003085 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smithd9f663b2013-04-22 15:31:51 +00003086 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00003087 return ESR_Failed;
3088 return ESR_Returned;
3089 }
Richard Smith254a73d2011-10-28 22:34:42 +00003090
3091 case Stmt::CompoundStmtClass: {
3092 const CompoundStmt *CS = cast<CompoundStmt>(S);
3093 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
3094 BE = CS->body_end(); BI != BE; ++BI) {
Richard Smith496ddcf2013-05-12 17:32:42 +00003095 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI, Case);
3096 if (ESR == ESR_Succeeded)
3097 Case = 0;
3098 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003099 return ESR;
3100 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003101 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003102 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003103
3104 case Stmt::IfStmtClass: {
3105 const IfStmt *IS = cast<IfStmt>(S);
3106
3107 // Evaluate the condition, as either a var decl or as an expression.
3108 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003109 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003110 return ESR_Failed;
3111
3112 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3113 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3114 if (ESR != ESR_Succeeded)
3115 return ESR;
3116 }
3117 return ESR_Succeeded;
3118 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003119
3120 case Stmt::WhileStmtClass: {
3121 const WhileStmt *WS = cast<WhileStmt>(S);
3122 while (true) {
3123 bool Continue;
3124 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3125 Continue))
3126 return ESR_Failed;
3127 if (!Continue)
3128 break;
3129
3130 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3131 if (ESR != ESR_Continue)
3132 return ESR;
3133 }
3134 return ESR_Succeeded;
3135 }
3136
3137 case Stmt::DoStmtClass: {
3138 const DoStmt *DS = cast<DoStmt>(S);
3139 bool Continue;
3140 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003141 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003142 if (ESR != ESR_Continue)
3143 return ESR;
Richard Smith496ddcf2013-05-12 17:32:42 +00003144 Case = 0;
Richard Smith4e18ca52013-05-06 05:56:11 +00003145
3146 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3147 return ESR_Failed;
3148 } while (Continue);
3149 return ESR_Succeeded;
3150 }
3151
3152 case Stmt::ForStmtClass: {
3153 const ForStmt *FS = cast<ForStmt>(S);
3154 if (FS->getInit()) {
3155 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3156 if (ESR != ESR_Succeeded)
3157 return ESR;
3158 }
3159 while (true) {
3160 bool Continue = true;
3161 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3162 FS->getCond(), Continue))
3163 return ESR_Failed;
3164 if (!Continue)
3165 break;
3166
3167 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3168 if (ESR != ESR_Continue)
3169 return ESR;
3170
3171 if (FS->getInc() && !EvaluateIgnoredValue(Info, FS->getInc()))
3172 return ESR_Failed;
3173 }
3174 return ESR_Succeeded;
3175 }
3176
Richard Smith896e0d72013-05-06 06:51:17 +00003177 case Stmt::CXXForRangeStmtClass: {
3178 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
3179
3180 // Initialize the __range variable.
3181 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3182 if (ESR != ESR_Succeeded)
3183 return ESR;
3184
3185 // Create the __begin and __end iterators.
3186 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3187 if (ESR != ESR_Succeeded)
3188 return ESR;
3189
3190 while (true) {
3191 // Condition: __begin != __end.
3192 bool Continue = true;
3193 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3194 return ESR_Failed;
3195 if (!Continue)
3196 break;
3197
3198 // User's variable declaration, initialized by *__begin.
3199 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3200 if (ESR != ESR_Succeeded)
3201 return ESR;
3202
3203 // Loop body.
3204 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3205 if (ESR != ESR_Continue)
3206 return ESR;
3207
3208 // Increment: ++__begin
3209 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3210 return ESR_Failed;
3211 }
3212
3213 return ESR_Succeeded;
3214 }
3215
Richard Smith496ddcf2013-05-12 17:32:42 +00003216 case Stmt::SwitchStmtClass:
3217 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3218
Richard Smith4e18ca52013-05-06 05:56:11 +00003219 case Stmt::ContinueStmtClass:
3220 return ESR_Continue;
3221
3222 case Stmt::BreakStmtClass:
3223 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003224
3225 case Stmt::LabelStmtClass:
3226 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3227
3228 case Stmt::AttributedStmtClass:
3229 // As a general principle, C++11 attributes can be ignored without
3230 // any semantic impact.
3231 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3232 Case);
3233
3234 case Stmt::CaseStmtClass:
3235 case Stmt::DefaultStmtClass:
3236 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003237 }
3238}
3239
Richard Smithcc36f692011-12-22 02:22:31 +00003240/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3241/// default constructor. If so, we'll fold it whether or not it's marked as
3242/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3243/// so we need special handling.
3244static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003245 const CXXConstructorDecl *CD,
3246 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003247 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3248 return false;
3249
Richard Smith66e05fe2012-01-18 05:21:49 +00003250 // Value-initialization does not call a trivial default constructor, so such a
3251 // call is a core constant expression whether or not the constructor is
3252 // constexpr.
3253 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003254 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003255 // FIXME: If DiagDecl is an implicitly-declared special member function,
3256 // we should be much more explicit about why it's not constexpr.
3257 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3258 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3259 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003260 } else {
3261 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3262 }
3263 }
3264 return true;
3265}
3266
Richard Smith357362d2011-12-13 06:39:58 +00003267/// CheckConstexprFunction - Check that a function can be called in a constant
3268/// expression.
3269static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3270 const FunctionDecl *Declaration,
3271 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00003272 // Potential constant expressions can contain calls to declared, but not yet
3273 // defined, constexpr functions.
3274 if (Info.CheckingPotentialConstantExpression && !Definition &&
3275 Declaration->isConstexpr())
3276 return false;
3277
Richard Smith0838f3a2013-05-14 05:18:44 +00003278 // Bail out with no diagnostic if the function declaration itself is invalid.
3279 // We will have produced a relevant diagnostic while parsing it.
3280 if (Declaration->isInvalidDecl())
3281 return false;
3282
Richard Smith357362d2011-12-13 06:39:58 +00003283 // Can we evaluate this function call?
3284 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3285 return true;
3286
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003287 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003288 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003289 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3290 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003291 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3292 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3293 << DiagDecl;
3294 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3295 } else {
3296 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3297 }
3298 return false;
3299}
3300
Richard Smithd62306a2011-11-10 06:34:14 +00003301namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003302typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003303}
3304
3305/// EvaluateArgs - Evaluate the arguments to a function call.
3306static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3307 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003308 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003309 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003310 I != E; ++I) {
3311 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3312 // If we're checking for a potential constant expression, evaluate all
3313 // initializers even if some of them fail.
3314 if (!Info.keepEvaluatingAfterFailure())
3315 return false;
3316 Success = false;
3317 }
3318 }
3319 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003320}
3321
Richard Smith254a73d2011-10-28 22:34:42 +00003322/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003323static bool HandleFunctionCall(SourceLocation CallLoc,
3324 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003325 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00003326 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003327 ArgVector ArgValues(Args.size());
3328 if (!EvaluateArgs(Args, ArgValues, Info))
3329 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003330
Richard Smith253c2a32012-01-27 01:14:48 +00003331 if (!Info.CheckCallLimit(CallLoc))
3332 return false;
3333
3334 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003335
3336 // For a trivial copy or move assignment, perform an APValue copy. This is
3337 // essential for unions, where the operations performed by the assignment
3338 // operator cannot be represented as statements.
3339 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3340 if (MD && MD->isDefaulted() && MD->isTrivial()) {
3341 assert(This &&
3342 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3343 LValue RHS;
3344 RHS.setFrom(Info.Ctx, ArgValues[0]);
3345 APValue RHSValue;
3346 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3347 RHS, RHSValue))
3348 return false;
3349 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3350 RHSValue))
3351 return false;
3352 This->moveInto(Result);
3353 return true;
3354 }
3355
Richard Smithd9f663b2013-04-22 15:31:51 +00003356 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003357 if (ESR == ESR_Succeeded) {
3358 if (Callee->getResultType()->isVoidType())
3359 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003360 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003361 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003362 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003363}
3364
Richard Smithd62306a2011-11-10 06:34:14 +00003365/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003366static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003367 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003368 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003369 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003370 ArgVector ArgValues(Args.size());
3371 if (!EvaluateArgs(Args, ArgValues, Info))
3372 return false;
3373
Richard Smith253c2a32012-01-27 01:14:48 +00003374 if (!Info.CheckCallLimit(CallLoc))
3375 return false;
3376
Richard Smith3607ffe2012-02-13 03:54:03 +00003377 const CXXRecordDecl *RD = Definition->getParent();
3378 if (RD->getNumVBases()) {
3379 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3380 return false;
3381 }
3382
Richard Smith253c2a32012-01-27 01:14:48 +00003383 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003384
3385 // If it's a delegating constructor, just delegate.
3386 if (Definition->isDelegatingConstructor()) {
3387 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smithd9f663b2013-04-22 15:31:51 +00003388 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3389 return false;
3390 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003391 }
3392
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003393 // For a trivial copy or move constructor, perform an APValue copy. This is
3394 // essential for unions, where the operations performed by the constructor
3395 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003396 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00003397 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3398 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003399 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003400 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003401 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003402 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003403 }
3404
3405 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003406 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003407 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3408 std::distance(RD->field_begin(), RD->field_end()));
3409
John McCalld7bca762012-05-01 00:38:49 +00003410 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003411 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3412
Richard Smith253c2a32012-01-27 01:14:48 +00003413 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003414 unsigned BasesSeen = 0;
3415#ifndef NDEBUG
3416 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3417#endif
3418 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
3419 E = Definition->init_end(); I != E; ++I) {
Richard Smith253c2a32012-01-27 01:14:48 +00003420 LValue Subobject = This;
3421 APValue *Value = &Result;
3422
3423 // Determine the subobject to initialize.
Richard Smithd62306a2011-11-10 06:34:14 +00003424 if ((*I)->isBaseInitializer()) {
3425 QualType BaseType((*I)->getBaseClass(), 0);
3426#ifndef NDEBUG
3427 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003428 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003429 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3430 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3431 "base class initializers not in expected order");
3432 ++BaseIt;
3433#endif
John McCalld7bca762012-05-01 00:38:49 +00003434 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
3435 BaseType->getAsCXXRecordDecl(), &Layout))
3436 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003437 Value = &Result.getStructBase(BasesSeen++);
Richard Smithd62306a2011-11-10 06:34:14 +00003438 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCalld7bca762012-05-01 00:38:49 +00003439 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
3440 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003441 if (RD->isUnion()) {
3442 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003443 Value = &Result.getUnionValue();
3444 } else {
3445 Value = &Result.getStructField(FD->getFieldIndex());
3446 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00003447 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003448 // Walk the indirect field decl's chain to find the object to initialize,
3449 // and make sure we've initialized every step along it.
3450 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
3451 CE = IFD->chain_end();
3452 C != CE; ++C) {
3453 FieldDecl *FD = cast<FieldDecl>(*C);
3454 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3455 // Switch the union field if it differs. This happens if we had
3456 // preceding zero-initialization, and we're now initializing a union
3457 // subobject other than the first.
3458 // FIXME: In this case, the values of the other subobjects are
3459 // specified, since zero-initialization sets all padding bits to zero.
3460 if (Value->isUninit() ||
3461 (Value->isUnion() && Value->getUnionField() != FD)) {
3462 if (CD->isUnion())
3463 *Value = APValue(FD);
3464 else
3465 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
3466 std::distance(CD->field_begin(), CD->field_end()));
3467 }
John McCalld7bca762012-05-01 00:38:49 +00003468 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
3469 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003470 if (CD->isUnion())
3471 Value = &Value->getUnionValue();
3472 else
3473 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00003474 }
Richard Smithd62306a2011-11-10 06:34:14 +00003475 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003476 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00003477 }
Richard Smith253c2a32012-01-27 01:14:48 +00003478
Richard Smith7525ff62013-05-09 07:14:00 +00003479 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit())) {
Richard Smith253c2a32012-01-27 01:14:48 +00003480 // If we're checking for a potential constant expression, evaluate all
3481 // initializers even if some of them fail.
3482 if (!Info.keepEvaluatingAfterFailure())
3483 return false;
3484 Success = false;
3485 }
Richard Smithd62306a2011-11-10 06:34:14 +00003486 }
3487
Richard Smithd9f663b2013-04-22 15:31:51 +00003488 return Success &&
3489 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003490}
3491
Eli Friedman9a156e52008-11-12 09:44:48 +00003492//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00003493// Generic Evaluation
3494//===----------------------------------------------------------------------===//
3495namespace {
3496
Richard Smithf57d8cb2011-12-09 22:58:01 +00003497// FIXME: RetTy is always bool. Remove it.
3498template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00003499class ExprEvaluatorBase
3500 : public ConstStmtVisitor<Derived, RetTy> {
3501private:
Richard Smith2e312c82012-03-03 22:46:17 +00003502 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003503 return static_cast<Derived*>(this)->Success(V, E);
3504 }
Richard Smithfddd3842011-12-30 21:15:51 +00003505 RetTy DerivedZeroInitialization(const Expr *E) {
3506 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003507 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003508
Richard Smith17100ba2012-02-16 02:46:34 +00003509 // Check whether a conditional operator with a non-constant condition is a
3510 // potential constant expression. If neither arm is a potential constant
3511 // expression, then the conditional operator is not either.
3512 template<typename ConditionalOperator>
3513 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
3514 assert(Info.CheckingPotentialConstantExpression);
3515
3516 // Speculatively evaluate both arms.
3517 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003518 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00003519 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3520
3521 StmtVisitorTy::Visit(E->getFalseExpr());
3522 if (Diag.empty())
3523 return;
3524
3525 Diag.clear();
3526 StmtVisitorTy::Visit(E->getTrueExpr());
3527 if (Diag.empty())
3528 return;
3529 }
3530
3531 Error(E, diag::note_constexpr_conditional_never_const);
3532 }
3533
3534
3535 template<typename ConditionalOperator>
3536 bool HandleConditionalOperator(const ConditionalOperator *E) {
3537 bool BoolResult;
3538 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
3539 if (Info.CheckingPotentialConstantExpression)
3540 CheckPotentialConstantConditional(E);
3541 return false;
3542 }
3543
3544 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3545 return StmtVisitorTy::Visit(EvalExpr);
3546 }
3547
Peter Collingbournee9200682011-05-13 03:29:01 +00003548protected:
3549 EvalInfo &Info;
3550 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
3551 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3552
Richard Smith92b1ce02011-12-12 09:28:41 +00003553 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003554 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003555 }
3556
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003557 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
3558
3559public:
3560 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3561
3562 EvalInfo &getEvalInfo() { return Info; }
3563
Richard Smithf57d8cb2011-12-09 22:58:01 +00003564 /// Report an evaluation error. This should only be called when an error is
3565 /// first discovered. When propagating an error, just return false.
3566 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003567 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003568 return false;
3569 }
3570 bool Error(const Expr *E) {
3571 return Error(E, diag::note_invalid_subexpr_in_const_expr);
3572 }
3573
Peter Collingbournee9200682011-05-13 03:29:01 +00003574 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00003575 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00003576 }
3577 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003578 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003579 }
3580
3581 RetTy VisitParenExpr(const ParenExpr *E)
3582 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3583 RetTy VisitUnaryExtension(const UnaryOperator *E)
3584 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3585 RetTy VisitUnaryPlus(const UnaryOperator *E)
3586 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3587 RetTy VisitChooseExpr(const ChooseExpr *E)
3588 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
3589 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
3590 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00003591 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
3592 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00003593 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
3594 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith852c9db2013-04-20 22:23:05 +00003595 RetTy VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
3596 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00003597 // We cannot create any objects for which cleanups are required, so there is
3598 // nothing to do here; all cleanups must come from unevaluated subexpressions.
3599 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
3600 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003601
Richard Smith6d6ecc32011-12-12 12:46:16 +00003602 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
3603 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3604 return static_cast<Derived*>(this)->VisitCastExpr(E);
3605 }
3606 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
3607 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3608 return static_cast<Derived*>(this)->VisitCastExpr(E);
3609 }
3610
Richard Smith027bf112011-11-17 22:56:20 +00003611 RetTy VisitBinaryOperator(const BinaryOperator *E) {
3612 switch (E->getOpcode()) {
3613 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003614 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003615
3616 case BO_Comma:
3617 VisitIgnoredValue(E->getLHS());
3618 return StmtVisitorTy::Visit(E->getRHS());
3619
3620 case BO_PtrMemD:
3621 case BO_PtrMemI: {
3622 LValue Obj;
3623 if (!HandleMemberPointerAccess(Info, E, Obj))
3624 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003625 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00003626 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00003627 return false;
3628 return DerivedSuccess(Result, E);
3629 }
3630 }
3631 }
3632
Peter Collingbournee9200682011-05-13 03:29:01 +00003633 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003634 // Evaluate and cache the common expression. We treat it as a temporary,
3635 // even though it's not quite the same thing.
3636 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
3637 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003638 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00003639
Richard Smith17100ba2012-02-16 02:46:34 +00003640 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003641 }
3642
3643 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003644 bool IsBcpCall = false;
3645 // If the condition (ignoring parens) is a __builtin_constant_p call,
3646 // the result is a constant expression if it can be folded without
3647 // side-effects. This is an important GNU extension. See GCC PR38377
3648 // for discussion.
3649 if (const CallExpr *CallCE =
3650 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
3651 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
3652 IsBcpCall = true;
3653
3654 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3655 // constant expression; we can't check whether it's potentially foldable.
3656 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
3657 return false;
3658
3659 FoldConstant Fold(Info);
3660
Richard Smith17100ba2012-02-16 02:46:34 +00003661 if (!HandleConditionalOperator(E))
Richard Smith84f6dcf2012-02-02 01:16:57 +00003662 return false;
3663
3664 if (IsBcpCall)
3665 Fold.Fold(Info);
3666
3667 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00003668 }
3669
3670 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003671 APValue &Value = Info.CurrentCall->Temporaries[E];
3672 if (Value.isUninit()) {
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003673 const Expr *Source = E->getSourceExpr();
3674 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003675 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003676 if (Source == E) { // sanity checking.
3677 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00003678 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003679 }
3680 return StmtVisitorTy::Visit(Source);
3681 }
Richard Smith26d4cc12012-06-26 08:12:11 +00003682 return DerivedSuccess(Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003683 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003684
Richard Smith254a73d2011-10-28 22:34:42 +00003685 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003686 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00003687 QualType CalleeType = Callee->getType();
3688
Richard Smith254a73d2011-10-28 22:34:42 +00003689 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00003690 LValue *This = 0, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003691 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00003692 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00003693
Richard Smithe97cbd72011-11-11 04:05:33 +00003694 // Extract function decl and 'this' pointer from the callee.
3695 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003696 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00003697 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3698 // Explicit bound member calls, such as x.f() or p->g();
3699 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003700 return false;
3701 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00003702 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00003703 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00003704 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
3705 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00003706 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
3707 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00003708 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00003709 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003710 return Error(Callee);
3711
3712 FD = dyn_cast<FunctionDecl>(Member);
3713 if (!FD)
3714 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003715 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003716 LValue Call;
3717 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003718 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00003719
Richard Smitha8105bc2012-01-06 16:39:00 +00003720 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003721 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00003722 FD = dyn_cast_or_null<FunctionDecl>(
3723 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00003724 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003725 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003726
3727 // Overloaded operator calls to member functions are represented as normal
3728 // calls with '*this' as the first argument.
3729 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
3730 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003731 // FIXME: When selecting an implicit conversion for an overloaded
3732 // operator delete, we sometimes try to evaluate calls to conversion
3733 // operators without a 'this' parameter!
3734 if (Args.empty())
3735 return Error(E);
3736
Richard Smithe97cbd72011-11-11 04:05:33 +00003737 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
3738 return false;
3739 This = &ThisVal;
3740 Args = Args.slice(1);
3741 }
3742
3743 // Don't call function pointers which have been cast to some other type.
3744 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003745 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00003746 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003747 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00003748
Richard Smith47b34932012-02-01 02:39:43 +00003749 if (This && !This->checkSubobject(Info, E, CSK_This))
3750 return false;
3751
Richard Smith3607ffe2012-02-13 03:54:03 +00003752 // DR1358 allows virtual constexpr functions in some cases. Don't allow
3753 // calls to such functions in constant expressions.
3754 if (This && !HasQualifier &&
3755 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
3756 return Error(E, diag::note_constexpr_virtual_call);
3757
Richard Smith357362d2011-12-13 06:39:58 +00003758 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00003759 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00003760 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00003761
Richard Smith357362d2011-12-13 06:39:58 +00003762 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00003763 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
3764 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003765 return false;
3766
Richard Smithb228a862012-02-15 02:18:13 +00003767 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00003768 }
3769
Richard Smith11562c52011-10-28 17:51:58 +00003770 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
3771 return StmtVisitorTy::Visit(E->getInitializer());
3772 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003773 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00003774 if (E->getNumInits() == 0)
3775 return DerivedZeroInitialization(E);
3776 if (E->getNumInits() == 1)
3777 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00003778 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003779 }
3780 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003781 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003782 }
3783 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003784 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003785 }
Richard Smith027bf112011-11-17 22:56:20 +00003786 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003787 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00003788 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003789
Richard Smithd62306a2011-11-10 06:34:14 +00003790 /// A member expression where the object is a prvalue is itself a prvalue.
3791 RetTy VisitMemberExpr(const MemberExpr *E) {
3792 assert(!E->isArrow() && "missing call to bound member function?");
3793
Richard Smith2e312c82012-03-03 22:46:17 +00003794 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00003795 if (!Evaluate(Val, Info, E->getBase()))
3796 return false;
3797
3798 QualType BaseTy = E->getBase()->getType();
3799
3800 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003801 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003802 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00003803 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00003804 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3805
Richard Smith3229b742013-05-05 21:17:10 +00003806 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00003807 SubobjectDesignator Designator(BaseTy);
3808 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00003809
Richard Smith3229b742013-05-05 21:17:10 +00003810 APValue Result;
3811 return extractSubobject(Info, E, Obj, Designator, Result) &&
3812 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00003813 }
3814
Richard Smith11562c52011-10-28 17:51:58 +00003815 RetTy VisitCastExpr(const CastExpr *E) {
3816 switch (E->getCastKind()) {
3817 default:
3818 break;
3819
Richard Smitha23ab512013-05-23 00:30:41 +00003820 case CK_AtomicToNonAtomic: {
3821 APValue AtomicVal;
3822 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
3823 return false;
3824 return DerivedSuccess(AtomicVal, E);
3825 }
3826
Richard Smith11562c52011-10-28 17:51:58 +00003827 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00003828 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00003829 return StmtVisitorTy::Visit(E->getSubExpr());
3830
3831 case CK_LValueToRValue: {
3832 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003833 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
3834 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003835 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00003836 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00003837 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00003838 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003839 return false;
3840 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00003841 }
3842 }
3843
Richard Smithf57d8cb2011-12-09 22:58:01 +00003844 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003845 }
3846
Richard Smith243ef902013-05-05 23:31:59 +00003847 RetTy VisitUnaryPostInc(const UnaryOperator *UO) {
3848 return VisitUnaryPostIncDec(UO);
3849 }
3850 RetTy VisitUnaryPostDec(const UnaryOperator *UO) {
3851 return VisitUnaryPostIncDec(UO);
3852 }
3853 RetTy VisitUnaryPostIncDec(const UnaryOperator *UO) {
3854 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
3855 return Error(UO);
3856
3857 LValue LVal;
3858 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
3859 return false;
3860 APValue RVal;
3861 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
3862 UO->isIncrementOp(), &RVal))
3863 return false;
3864 return DerivedSuccess(RVal, UO);
3865 }
3866
Richard Smith51f03172013-06-20 03:00:05 +00003867 RetTy VisitStmtExpr(const StmtExpr *E) {
3868 // We will have checked the full-expressions inside the statement expression
3869 // when they were completed, and don't need to check them again now.
3870 if (Info.getIntOverflowCheckMode())
3871 return Error(E);
3872
3873 const CompoundStmt *CS = E->getSubStmt();
3874 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
3875 BE = CS->body_end();
3876 /**/; ++BI) {
3877 if (BI + 1 == BE) {
3878 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
3879 if (!FinalExpr) {
3880 Info.Diag((*BI)->getLocStart(),
3881 diag::note_constexpr_stmt_expr_unsupported);
3882 return false;
3883 }
3884 return this->Visit(FinalExpr);
3885 }
3886
3887 APValue ReturnValue;
3888 EvalStmtResult ESR = EvaluateStmt(ReturnValue, Info, *BI);
3889 if (ESR != ESR_Succeeded) {
3890 // FIXME: If the statement-expression terminated due to 'return',
3891 // 'break', or 'continue', it would be nice to propagate that to
3892 // the outer statement evaluation rather than bailing out.
3893 if (ESR != ESR_Failed)
3894 Info.Diag((*BI)->getLocStart(),
3895 diag::note_constexpr_stmt_expr_unsupported);
3896 return false;
3897 }
3898 }
3899 }
3900
Richard Smith4a678122011-10-24 18:44:57 +00003901 /// Visit a value which is evaluated, but whose value is ignored.
3902 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003903 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00003904 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003905};
3906
3907}
3908
3909//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003910// Common base class for lvalue and temporary evaluation.
3911//===----------------------------------------------------------------------===//
3912namespace {
3913template<class Derived>
3914class LValueExprEvaluatorBase
3915 : public ExprEvaluatorBase<Derived, bool> {
3916protected:
3917 LValue &Result;
3918 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
3919 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
3920
3921 bool Success(APValue::LValueBase B) {
3922 Result.set(B);
3923 return true;
3924 }
3925
3926public:
3927 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
3928 ExprEvaluatorBaseTy(Info), Result(Result) {}
3929
Richard Smith2e312c82012-03-03 22:46:17 +00003930 bool Success(const APValue &V, const Expr *E) {
3931 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00003932 return true;
3933 }
Richard Smith027bf112011-11-17 22:56:20 +00003934
Richard Smith027bf112011-11-17 22:56:20 +00003935 bool VisitMemberExpr(const MemberExpr *E) {
3936 // Handle non-static data members.
3937 QualType BaseTy;
3938 if (E->isArrow()) {
3939 if (!EvaluatePointer(E->getBase(), Result, this->Info))
3940 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00003941 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00003942 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00003943 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00003944 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
3945 return false;
3946 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003947 } else {
3948 if (!this->Visit(E->getBase()))
3949 return false;
3950 BaseTy = E->getBase()->getType();
3951 }
Richard Smith027bf112011-11-17 22:56:20 +00003952
Richard Smith1b78b3d2012-01-25 22:15:11 +00003953 const ValueDecl *MD = E->getMemberDecl();
3954 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
3955 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
3956 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3957 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00003958 if (!HandleLValueMember(this->Info, E, Result, FD))
3959 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003960 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00003961 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
3962 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003963 } else
3964 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003965
Richard Smith1b78b3d2012-01-25 22:15:11 +00003966 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00003967 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00003968 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00003969 RefValue))
3970 return false;
3971 return Success(RefValue, E);
3972 }
3973 return true;
3974 }
3975
3976 bool VisitBinaryOperator(const BinaryOperator *E) {
3977 switch (E->getOpcode()) {
3978 default:
3979 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
3980
3981 case BO_PtrMemD:
3982 case BO_PtrMemI:
3983 return HandleMemberPointerAccess(this->Info, E, Result);
3984 }
3985 }
3986
3987 bool VisitCastExpr(const CastExpr *E) {
3988 switch (E->getCastKind()) {
3989 default:
3990 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3991
3992 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00003993 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00003994 if (!this->Visit(E->getSubExpr()))
3995 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003996
3997 // Now figure out the necessary offset to add to the base LV to get from
3998 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00003999 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4000 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004001 }
4002 }
4003};
4004}
4005
4006//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004007// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004008//
4009// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4010// function designators (in C), decl references to void objects (in C), and
4011// temporaries (if building with -Wno-address-of-temporary).
4012//
4013// LValue evaluation produces values comprising a base expression of one of the
4014// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004015// - Declarations
4016// * VarDecl
4017// * FunctionDecl
4018// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00004019// * CompoundLiteralExpr in C
4020// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004021// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004022// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004023// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004024// * ObjCEncodeExpr
4025// * AddrLabelExpr
4026// * BlockExpr
4027// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004028// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004029// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004030// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004031// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4032// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004033// * A MaterializeTemporaryExpr that has static storage duration, with no
4034// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004035// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004036//===----------------------------------------------------------------------===//
4037namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004038class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004039 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004040public:
Richard Smith027bf112011-11-17 22:56:20 +00004041 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4042 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004043
Richard Smith11562c52011-10-28 17:51:58 +00004044 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004045 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004046
Peter Collingbournee9200682011-05-13 03:29:01 +00004047 bool VisitDeclRefExpr(const DeclRefExpr *E);
4048 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004049 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004050 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4051 bool VisitMemberExpr(const MemberExpr *E);
4052 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4053 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004054 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004055 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004056 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4057 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004058 bool VisitUnaryReal(const UnaryOperator *E);
4059 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004060 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4061 return VisitUnaryPreIncDec(UO);
4062 }
4063 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4064 return VisitUnaryPreIncDec(UO);
4065 }
Richard Smith3229b742013-05-05 21:17:10 +00004066 bool VisitBinAssign(const BinaryOperator *BO);
4067 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004068
Peter Collingbournee9200682011-05-13 03:29:01 +00004069 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004070 switch (E->getCastKind()) {
4071 default:
Richard Smith027bf112011-11-17 22:56:20 +00004072 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004073
Eli Friedmance3e02a2011-10-11 00:13:24 +00004074 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004075 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004076 if (!Visit(E->getSubExpr()))
4077 return false;
4078 Result.Designator.setInvalid();
4079 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004080
Richard Smith027bf112011-11-17 22:56:20 +00004081 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004082 if (!Visit(E->getSubExpr()))
4083 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004084 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004085 }
4086 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004087};
4088} // end anonymous namespace
4089
Richard Smith11562c52011-10-28 17:51:58 +00004090/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smith9f8400e2013-05-01 19:00:39 +00004091/// expressions which are not glvalues, in two cases:
4092/// * function designators in C, and
4093/// * "extern void" objects
4094static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4095 assert(E->isGLValue() || E->getType()->isFunctionType() ||
4096 E->getType()->isVoidType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004097 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004098}
4099
Peter Collingbournee9200682011-05-13 03:29:01 +00004100bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004101 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
4102 return Success(FD);
4103 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004104 return VisitVarDecl(E, VD);
4105 return Error(E);
4106}
Richard Smith733237d2011-10-24 23:14:33 +00004107
Richard Smith11562c52011-10-28 17:51:58 +00004108bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith3229b742013-05-05 21:17:10 +00004109 CallStackFrame *Frame = 0;
4110 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4111 Frame = Info.CurrentCall;
4112
Richard Smithfec09922011-11-01 16:57:24 +00004113 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004114 if (Frame) {
4115 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004116 return true;
4117 }
Richard Smithce40ad62011-11-12 22:28:03 +00004118 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004119 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004120
Richard Smith3229b742013-05-05 21:17:10 +00004121 APValue *V;
4122 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004123 return false;
Richard Smith3229b742013-05-05 21:17:10 +00004124 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004125}
4126
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004127bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4128 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004129 // Walk through the expression to find the materialized temporary itself.
4130 SmallVector<const Expr *, 2> CommaLHSs;
4131 SmallVector<SubobjectAdjustment, 2> Adjustments;
4132 const Expr *Inner = E->GetTemporaryExpr()->
4133 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004134
Richard Smith84401042013-06-03 05:03:02 +00004135 // If we passed any comma operators, evaluate their LHSs.
4136 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4137 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4138 return false;
4139
Richard Smithe6c01442013-06-05 00:46:14 +00004140 // A materialized temporary with static storage duration can appear within the
4141 // result of a constant expression evaluation, so we need to preserve its
4142 // value for use outside this evaluation.
4143 APValue *Value;
4144 if (E->getStorageDuration() == SD_Static) {
4145 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004146 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004147 Result.set(E);
4148 } else {
4149 Value = &Info.CurrentCall->Temporaries[E];
4150 Result.set(E, Info.CurrentCall->Index);
4151 }
4152
Richard Smithea4ad5d2013-06-06 08:19:16 +00004153 QualType Type = Inner->getType();
4154
Richard Smith84401042013-06-03 05:03:02 +00004155 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004156 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4157 (E->getStorageDuration() == SD_Static &&
4158 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4159 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004160 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004161 }
Richard Smith84401042013-06-03 05:03:02 +00004162
4163 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004164 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4165 --I;
4166 switch (Adjustments[I].Kind) {
4167 case SubobjectAdjustment::DerivedToBaseAdjustment:
4168 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4169 Type, Result))
4170 return false;
4171 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4172 break;
4173
4174 case SubobjectAdjustment::FieldAdjustment:
4175 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4176 return false;
4177 Type = Adjustments[I].Field->getType();
4178 break;
4179
4180 case SubobjectAdjustment::MemberPointerAdjustment:
4181 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4182 Adjustments[I].Ptr.RHS))
4183 return false;
4184 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4185 break;
4186 }
4187 }
4188
4189 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004190}
4191
Peter Collingbournee9200682011-05-13 03:29:01 +00004192bool
4193LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004194 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4195 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4196 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004197 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004198}
4199
Richard Smith6e525142011-12-27 12:18:28 +00004200bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004201 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004202 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004203
4204 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4205 << E->getExprOperand()->getType()
4206 << E->getExprOperand()->getSourceRange();
4207 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004208}
4209
Francois Pichet0066db92012-04-16 04:08:35 +00004210bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4211 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004212}
Francois Pichet0066db92012-04-16 04:08:35 +00004213
Peter Collingbournee9200682011-05-13 03:29:01 +00004214bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004215 // Handle static data members.
4216 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4217 VisitIgnoredValue(E->getBase());
4218 return VisitVarDecl(E, VD);
4219 }
4220
Richard Smith254a73d2011-10-28 22:34:42 +00004221 // Handle static member functions.
4222 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4223 if (MD->isStatic()) {
4224 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004225 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004226 }
4227 }
4228
Richard Smithd62306a2011-11-10 06:34:14 +00004229 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004230 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004231}
4232
Peter Collingbournee9200682011-05-13 03:29:01 +00004233bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004234 // FIXME: Deal with vectors as array subscript bases.
4235 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004236 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004237
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004238 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004239 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004240
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004241 APSInt Index;
4242 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004243 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004244
Richard Smith861b5b52013-05-07 23:34:45 +00004245 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4246 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004247}
Eli Friedman9a156e52008-11-12 09:44:48 +00004248
Peter Collingbournee9200682011-05-13 03:29:01 +00004249bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004250 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004251}
4252
Richard Smith66c96992012-02-18 22:04:06 +00004253bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4254 if (!Visit(E->getSubExpr()))
4255 return false;
4256 // __real is a no-op on scalar lvalues.
4257 if (E->getSubExpr()->getType()->isAnyComplexType())
4258 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4259 return true;
4260}
4261
4262bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4263 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4264 "lvalue __imag__ on scalar?");
4265 if (!Visit(E->getSubExpr()))
4266 return false;
4267 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4268 return true;
4269}
4270
Richard Smith243ef902013-05-05 23:31:59 +00004271bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4272 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004273 return Error(UO);
4274
4275 if (!this->Visit(UO->getSubExpr()))
4276 return false;
4277
Richard Smith243ef902013-05-05 23:31:59 +00004278 return handleIncDec(
4279 this->Info, UO, Result, UO->getSubExpr()->getType(),
4280 UO->isIncrementOp(), 0);
Richard Smith3229b742013-05-05 21:17:10 +00004281}
4282
4283bool LValueExprEvaluator::VisitCompoundAssignOperator(
4284 const CompoundAssignOperator *CAO) {
Richard Smith243ef902013-05-05 23:31:59 +00004285 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004286 return Error(CAO);
4287
Richard Smith3229b742013-05-05 21:17:10 +00004288 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004289
4290 // The overall lvalue result is the result of evaluating the LHS.
4291 if (!this->Visit(CAO->getLHS())) {
4292 if (Info.keepEvaluatingAfterFailure())
4293 Evaluate(RHS, this->Info, CAO->getRHS());
4294 return false;
4295 }
4296
Richard Smith3229b742013-05-05 21:17:10 +00004297 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4298 return false;
4299
Richard Smith43e77732013-05-07 04:50:00 +00004300 return handleCompoundAssignment(
4301 this->Info, CAO,
4302 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4303 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004304}
4305
4306bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Richard Smith243ef902013-05-05 23:31:59 +00004307 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4308 return Error(E);
4309
Richard Smith3229b742013-05-05 21:17:10 +00004310 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004311
4312 if (!this->Visit(E->getLHS())) {
4313 if (Info.keepEvaluatingAfterFailure())
4314 Evaluate(NewVal, this->Info, E->getRHS());
4315 return false;
4316 }
4317
Richard Smith3229b742013-05-05 21:17:10 +00004318 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4319 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004320
4321 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004322 NewVal);
4323}
4324
Eli Friedman9a156e52008-11-12 09:44:48 +00004325//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004326// Pointer Evaluation
4327//===----------------------------------------------------------------------===//
4328
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004329namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004330class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004331 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00004332 LValue &Result;
4333
Peter Collingbournee9200682011-05-13 03:29:01 +00004334 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004335 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004336 return true;
4337 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004338public:
Mike Stump11289f42009-09-09 15:08:12 +00004339
John McCall45d55e42010-05-07 21:00:08 +00004340 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004341 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004342
Richard Smith2e312c82012-03-03 22:46:17 +00004343 bool Success(const APValue &V, const Expr *E) {
4344 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004345 return true;
4346 }
Richard Smithfddd3842011-12-30 21:15:51 +00004347 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00004348 return Success((Expr*)0);
4349 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004350
John McCall45d55e42010-05-07 21:00:08 +00004351 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004352 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004353 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004354 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004355 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004356 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00004357 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004358 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004359 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004360 bool VisitCallExpr(const CallExpr *E);
4361 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004362 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004363 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004364 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004365 }
Richard Smithd62306a2011-11-10 06:34:14 +00004366 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004367 // Can't look at 'this' when checking a potential constant expression.
4368 if (Info.CheckingPotentialConstantExpression)
4369 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004370 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004371 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004372 Result = *Info.CurrentCall->This;
4373 return true;
4374 }
John McCallc07a0c72011-02-17 10:25:35 +00004375
Eli Friedman449fe542009-03-23 04:56:01 +00004376 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004377};
Chris Lattner05706e882008-07-11 18:11:29 +00004378} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004379
John McCall45d55e42010-05-07 21:00:08 +00004380static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004381 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004382 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004383}
4384
John McCall45d55e42010-05-07 21:00:08 +00004385bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004386 if (E->getOpcode() != BO_Add &&
4387 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004388 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004389
Chris Lattner05706e882008-07-11 18:11:29 +00004390 const Expr *PExp = E->getLHS();
4391 const Expr *IExp = E->getRHS();
4392 if (IExp->getType()->isPointerType())
4393 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004394
Richard Smith253c2a32012-01-27 01:14:48 +00004395 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4396 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004397 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004398
John McCall45d55e42010-05-07 21:00:08 +00004399 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004400 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004401 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004402
4403 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004404 if (E->getOpcode() == BO_Sub)
4405 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004406
Ted Kremenek28831752012-08-23 20:46:57 +00004407 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004408 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4409 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004410}
Eli Friedman9a156e52008-11-12 09:44:48 +00004411
John McCall45d55e42010-05-07 21:00:08 +00004412bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4413 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004414}
Mike Stump11289f42009-09-09 15:08:12 +00004415
Peter Collingbournee9200682011-05-13 03:29:01 +00004416bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4417 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004418
Eli Friedman847a2bc2009-12-27 05:43:15 +00004419 switch (E->getCastKind()) {
4420 default:
4421 break;
4422
John McCalle3027922010-08-25 11:45:40 +00004423 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004424 case CK_CPointerToObjCPointerCast:
4425 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004426 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004427 if (!Visit(SubExpr))
4428 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004429 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4430 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4431 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004432 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004433 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004434 if (SubExpr->getType()->isVoidPointerType())
4435 CCEDiag(E, diag::note_constexpr_invalid_cast)
4436 << 3 << SubExpr->getType();
4437 else
4438 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4439 }
Richard Smith96e0c102011-11-04 02:25:55 +00004440 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004441
Anders Carlsson18275092010-10-31 20:41:46 +00004442 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004443 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00004444 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004445 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004446 if (!Result.Base && Result.Offset.isZero())
4447 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00004448
Richard Smithd62306a2011-11-10 06:34:14 +00004449 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00004450 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004451 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4452 castAs<PointerType>()->getPointeeType(),
4453 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00004454
Richard Smith027bf112011-11-17 22:56:20 +00004455 case CK_BaseToDerived:
4456 if (!Visit(E->getSubExpr()))
4457 return false;
4458 if (!Result.Base && Result.Offset.isZero())
4459 return true;
4460 return HandleBaseToDerivedCast(Info, E, Result);
4461
Richard Smith0b0a0b62011-10-29 20:57:55 +00004462 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004463 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004464 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00004465
John McCalle3027922010-08-25 11:45:40 +00004466 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004467 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4468
Richard Smith2e312c82012-03-03 22:46:17 +00004469 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00004470 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00004471 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00004472
John McCall45d55e42010-05-07 21:00:08 +00004473 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004474 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4475 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00004476 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004477 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00004478 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00004479 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004480 return true;
4481 } else {
4482 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00004483 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00004484 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00004485 }
4486 }
John McCalle3027922010-08-25 11:45:40 +00004487 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00004488 if (SubExpr->isGLValue()) {
4489 if (!EvaluateLValue(SubExpr, Result, Info))
4490 return false;
4491 } else {
Richard Smithb228a862012-02-15 02:18:13 +00004492 Result.set(SubExpr, Info.CurrentCall->Index);
4493 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
4494 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00004495 return false;
4496 }
Richard Smith96e0c102011-11-04 02:25:55 +00004497 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00004498 if (const ConstantArrayType *CAT
4499 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4500 Result.addArray(Info, E, CAT);
4501 else
4502 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00004503 return true;
Richard Smithdd785442011-10-31 20:57:44 +00004504
John McCalle3027922010-08-25 11:45:40 +00004505 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00004506 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004507 }
4508
Richard Smith11562c52011-10-28 17:51:58 +00004509 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00004510}
Chris Lattner05706e882008-07-11 18:11:29 +00004511
Peter Collingbournee9200682011-05-13 03:29:01 +00004512bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004513 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00004514 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00004515
Peter Collingbournee9200682011-05-13 03:29:01 +00004516 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004517}
Chris Lattner05706e882008-07-11 18:11:29 +00004518
4519//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004520// Member Pointer Evaluation
4521//===----------------------------------------------------------------------===//
4522
4523namespace {
4524class MemberPointerExprEvaluator
4525 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
4526 MemberPtr &Result;
4527
4528 bool Success(const ValueDecl *D) {
4529 Result = MemberPtr(D);
4530 return true;
4531 }
4532public:
4533
4534 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
4535 : ExprEvaluatorBaseTy(Info), Result(Result) {}
4536
Richard Smith2e312c82012-03-03 22:46:17 +00004537 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004538 Result.setFrom(V);
4539 return true;
4540 }
Richard Smithfddd3842011-12-30 21:15:51 +00004541 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004542 return Success((const ValueDecl*)0);
4543 }
4544
4545 bool VisitCastExpr(const CastExpr *E);
4546 bool VisitUnaryAddrOf(const UnaryOperator *E);
4547};
4548} // end anonymous namespace
4549
4550static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
4551 EvalInfo &Info) {
4552 assert(E->isRValue() && E->getType()->isMemberPointerType());
4553 return MemberPointerExprEvaluator(Info, Result).Visit(E);
4554}
4555
4556bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
4557 switch (E->getCastKind()) {
4558 default:
4559 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4560
4561 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004562 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004563 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004564
4565 case CK_BaseToDerivedMemberPointer: {
4566 if (!Visit(E->getSubExpr()))
4567 return false;
4568 if (E->path_empty())
4569 return true;
4570 // Base-to-derived member pointer casts store the path in derived-to-base
4571 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
4572 // the wrong end of the derived->base arc, so stagger the path by one class.
4573 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
4574 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
4575 PathI != PathE; ++PathI) {
4576 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4577 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
4578 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004579 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004580 }
4581 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
4582 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004583 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004584 return true;
4585 }
4586
4587 case CK_DerivedToBaseMemberPointer:
4588 if (!Visit(E->getSubExpr()))
4589 return false;
4590 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4591 PathE = E->path_end(); PathI != PathE; ++PathI) {
4592 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4593 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4594 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004595 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004596 }
4597 return true;
4598 }
4599}
4600
4601bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4602 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
4603 // member can be formed.
4604 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
4605}
4606
4607//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00004608// Record Evaluation
4609//===----------------------------------------------------------------------===//
4610
4611namespace {
4612 class RecordExprEvaluator
4613 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
4614 const LValue &This;
4615 APValue &Result;
4616 public:
4617
4618 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
4619 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
4620
Richard Smith2e312c82012-03-03 22:46:17 +00004621 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004622 Result = V;
4623 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00004624 }
Richard Smithfddd3842011-12-30 21:15:51 +00004625 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004626
Richard Smithe97cbd72011-11-11 04:05:33 +00004627 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004628 bool VisitInitListExpr(const InitListExpr *E);
4629 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc1b96d2013-06-12 22:31:48 +00004630 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004631 };
4632}
4633
Richard Smithfddd3842011-12-30 21:15:51 +00004634/// Perform zero-initialization on an object of non-union class type.
4635/// C++11 [dcl.init]p5:
4636/// To zero-initialize an object or reference of type T means:
4637/// [...]
4638/// -- if T is a (possibly cv-qualified) non-union class type,
4639/// each non-static data member and each base-class subobject is
4640/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00004641static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
4642 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00004643 const LValue &This, APValue &Result) {
4644 assert(!RD->isUnion() && "Expected non-union class type");
4645 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
4646 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
4647 std::distance(RD->field_begin(), RD->field_end()));
4648
John McCalld7bca762012-05-01 00:38:49 +00004649 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004650 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4651
4652 if (CD) {
4653 unsigned Index = 0;
4654 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00004655 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00004656 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4657 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004658 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4659 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004660 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00004661 Result.getStructBase(Index)))
4662 return false;
4663 }
4664 }
4665
Richard Smitha8105bc2012-01-06 16:39:00 +00004666 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
4667 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00004668 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004669 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00004670 continue;
4671
4672 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004673 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004674 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004675
David Blaikie2d7c57e2012-04-30 02:36:29 +00004676 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004677 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00004678 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004679 return false;
4680 }
4681
4682 return true;
4683}
4684
4685bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
4686 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004687 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004688 if (RD->isUnion()) {
4689 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4690 // object's first non-static named data member is zero-initialized
4691 RecordDecl::field_iterator I = RD->field_begin();
4692 if (I == RD->field_end()) {
4693 Result = APValue((const FieldDecl*)0);
4694 return true;
4695 }
4696
4697 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004698 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00004699 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00004700 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00004701 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004702 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004703 }
4704
Richard Smith5d108602012-02-17 00:44:16 +00004705 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004706 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00004707 return false;
4708 }
4709
Richard Smitha8105bc2012-01-06 16:39:00 +00004710 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00004711}
4712
Richard Smithe97cbd72011-11-11 04:05:33 +00004713bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
4714 switch (E->getCastKind()) {
4715 default:
4716 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4717
4718 case CK_ConstructorConversion:
4719 return Visit(E->getSubExpr());
4720
4721 case CK_DerivedToBase:
4722 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00004723 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004724 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00004725 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004726 if (!DerivedObject.isStruct())
4727 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00004728
4729 // Derived-to-base rvalue conversion: just slice off the derived part.
4730 APValue *Value = &DerivedObject;
4731 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
4732 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4733 PathE = E->path_end(); PathI != PathE; ++PathI) {
4734 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
4735 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4736 Value = &Value->getStructBase(getBaseIndex(RD, Base));
4737 RD = Base;
4738 }
4739 Result = *Value;
4740 return true;
4741 }
4742 }
4743}
4744
Richard Smithd62306a2011-11-10 06:34:14 +00004745bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
4746 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004747 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004748 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4749
4750 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00004751 const FieldDecl *Field = E->getInitializedFieldInUnion();
4752 Result = APValue(Field);
4753 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00004754 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00004755
4756 // If the initializer list for a union does not contain any elements, the
4757 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00004758 // FIXME: The element should be initialized from an initializer list.
4759 // Is this difference ever observable for initializer lists which
4760 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00004761 ImplicitValueInitExpr VIE(Field->getType());
4762 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
4763
Richard Smithd62306a2011-11-10 06:34:14 +00004764 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004765 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
4766 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00004767
4768 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4769 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4770 isa<CXXDefaultInitExpr>(InitExpr));
4771
Richard Smithb228a862012-02-15 02:18:13 +00004772 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00004773 }
4774
4775 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
4776 "initializer list for class with base classes");
4777 Result = APValue(APValue::UninitStruct(), 0,
4778 std::distance(RD->field_begin(), RD->field_end()));
4779 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00004780 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004781 for (RecordDecl::field_iterator Field = RD->field_begin(),
4782 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
4783 // Anonymous bit-fields are not considered members of the class for
4784 // purposes of aggregate initialization.
4785 if (Field->isUnnamedBitfield())
4786 continue;
4787
4788 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00004789
Richard Smith253c2a32012-01-27 01:14:48 +00004790 bool HaveInit = ElementNo < E->getNumInits();
4791
4792 // FIXME: Diagnostics here should point to the end of the initializer
4793 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00004794 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie40ed2972012-06-06 20:45:41 +00004795 Subobject, *Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004796 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004797
4798 // Perform an implicit value-initialization for members beyond the end of
4799 // the initializer list.
4800 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00004801 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00004802
Richard Smith852c9db2013-04-20 22:23:05 +00004803 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4804 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4805 isa<CXXDefaultInitExpr>(Init));
4806
4807 if (!EvaluateInPlace(Result.getStructField(Field->getFieldIndex()), Info,
4808 Subobject, Init)) {
Richard Smith253c2a32012-01-27 01:14:48 +00004809 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00004810 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004811 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00004812 }
4813 }
4814
Richard Smith253c2a32012-01-27 01:14:48 +00004815 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004816}
4817
4818bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
4819 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00004820 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
4821
Richard Smithfddd3842011-12-30 21:15:51 +00004822 bool ZeroInit = E->requiresZeroInitialization();
4823 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00004824 // If we've already performed zero-initialization, we're already done.
4825 if (!Result.isUninit())
4826 return true;
4827
Richard Smithfddd3842011-12-30 21:15:51 +00004828 if (ZeroInit)
4829 return ZeroInitialization(E);
4830
Richard Smithcc36f692011-12-22 02:22:31 +00004831 const CXXRecordDecl *RD = FD->getParent();
4832 if (RD->isUnion())
4833 Result = APValue((FieldDecl*)0);
4834 else
4835 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4836 std::distance(RD->field_begin(), RD->field_end()));
4837 return true;
4838 }
4839
Richard Smithd62306a2011-11-10 06:34:14 +00004840 const FunctionDecl *Definition = 0;
4841 FD->getBody(Definition);
4842
Richard Smith357362d2011-12-13 06:39:58 +00004843 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
4844 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004845
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004846 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00004847 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00004848 if (const MaterializeTemporaryExpr *ME
4849 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
4850 return Visit(ME->GetTemporaryExpr());
4851
Richard Smithfddd3842011-12-30 21:15:51 +00004852 if (ZeroInit && !ZeroInitialization(E))
4853 return false;
4854
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004855 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00004856 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004857 cast<CXXConstructorDecl>(Definition), Info,
4858 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00004859}
4860
Richard Smithcc1b96d2013-06-12 22:31:48 +00004861bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
4862 const CXXStdInitializerListExpr *E) {
4863 const ConstantArrayType *ArrayType =
4864 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
4865
4866 LValue Array;
4867 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
4868 return false;
4869
4870 // Get a pointer to the first element of the array.
4871 Array.addArray(Info, E, ArrayType);
4872
4873 // FIXME: Perform the checks on the field types in SemaInit.
4874 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
4875 RecordDecl::field_iterator Field = Record->field_begin();
4876 if (Field == Record->field_end())
4877 return Error(E);
4878
4879 // Start pointer.
4880 if (!Field->getType()->isPointerType() ||
4881 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
4882 ArrayType->getElementType()))
4883 return Error(E);
4884
4885 // FIXME: What if the initializer_list type has base classes, etc?
4886 Result = APValue(APValue::UninitStruct(), 0, 2);
4887 Array.moveInto(Result.getStructField(0));
4888
4889 if (++Field == Record->field_end())
4890 return Error(E);
4891
4892 if (Field->getType()->isPointerType() &&
4893 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
4894 ArrayType->getElementType())) {
4895 // End pointer.
4896 if (!HandleLValueArrayAdjustment(Info, E, Array,
4897 ArrayType->getElementType(),
4898 ArrayType->getSize().getZExtValue()))
4899 return false;
4900 Array.moveInto(Result.getStructField(1));
4901 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
4902 // Length.
4903 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
4904 else
4905 return Error(E);
4906
4907 if (++Field != Record->field_end())
4908 return Error(E);
4909
4910 return true;
4911}
4912
Richard Smithd62306a2011-11-10 06:34:14 +00004913static bool EvaluateRecord(const Expr *E, const LValue &This,
4914 APValue &Result, EvalInfo &Info) {
4915 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00004916 "can't evaluate expression as a record rvalue");
4917 return RecordExprEvaluator(Info, This, Result).Visit(E);
4918}
4919
4920//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004921// Temporary Evaluation
4922//
4923// Temporaries are represented in the AST as rvalues, but generally behave like
4924// lvalues. The full-object of which the temporary is a subobject is implicitly
4925// materialized so that a reference can bind to it.
4926//===----------------------------------------------------------------------===//
4927namespace {
4928class TemporaryExprEvaluator
4929 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
4930public:
4931 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
4932 LValueExprEvaluatorBaseTy(Info, Result) {}
4933
4934 /// Visit an expression which constructs the value of this temporary.
4935 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004936 Result.set(E, Info.CurrentCall->Index);
4937 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00004938 }
4939
4940 bool VisitCastExpr(const CastExpr *E) {
4941 switch (E->getCastKind()) {
4942 default:
4943 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
4944
4945 case CK_ConstructorConversion:
4946 return VisitConstructExpr(E->getSubExpr());
4947 }
4948 }
4949 bool VisitInitListExpr(const InitListExpr *E) {
4950 return VisitConstructExpr(E);
4951 }
4952 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
4953 return VisitConstructExpr(E);
4954 }
4955 bool VisitCallExpr(const CallExpr *E) {
4956 return VisitConstructExpr(E);
4957 }
4958};
4959} // end anonymous namespace
4960
4961/// Evaluate an expression of record type as a temporary.
4962static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004963 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00004964 return TemporaryExprEvaluator(Info, Result).Visit(E);
4965}
4966
4967//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004968// Vector Evaluation
4969//===----------------------------------------------------------------------===//
4970
4971namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004972 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00004973 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
4974 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004975 public:
Mike Stump11289f42009-09-09 15:08:12 +00004976
Richard Smith2d406342011-10-22 21:10:00 +00004977 VectorExprEvaluator(EvalInfo &info, APValue &Result)
4978 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004979
Richard Smith2d406342011-10-22 21:10:00 +00004980 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
4981 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
4982 // FIXME: remove this APValue copy.
4983 Result = APValue(V.data(), V.size());
4984 return true;
4985 }
Richard Smith2e312c82012-03-03 22:46:17 +00004986 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00004987 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00004988 Result = V;
4989 return true;
4990 }
Richard Smithfddd3842011-12-30 21:15:51 +00004991 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00004992
Richard Smith2d406342011-10-22 21:10:00 +00004993 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00004994 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00004995 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00004996 bool VisitInitListExpr(const InitListExpr *E);
4997 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004998 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00004999 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00005000 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005001 };
5002} // end anonymous namespace
5003
5004static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005005 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00005006 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005007}
5008
Richard Smith2d406342011-10-22 21:10:00 +00005009bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5010 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005011 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005012
Richard Smith161f09a2011-12-06 22:44:34 +00005013 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00005014 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005015
Eli Friedmanc757de22011-03-25 00:43:55 +00005016 switch (E->getCastKind()) {
5017 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00005018 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00005019 if (SETy->isIntegerType()) {
5020 APSInt IntResult;
5021 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005022 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005023 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00005024 } else if (SETy->isRealFloatingType()) {
5025 APFloat F(0.0);
5026 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005027 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005028 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00005029 } else {
Richard Smith2d406342011-10-22 21:10:00 +00005030 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005031 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005032
5033 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00005034 SmallVector<APValue, 4> Elts(NElts, Val);
5035 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00005036 }
Eli Friedman803acb32011-12-22 03:51:45 +00005037 case CK_BitCast: {
5038 // Evaluate the operand into an APInt we can extract from.
5039 llvm::APInt SValInt;
5040 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5041 return false;
5042 // Extract the elements
5043 QualType EltTy = VTy->getElementType();
5044 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5045 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5046 SmallVector<APValue, 4> Elts;
5047 if (EltTy->isRealFloatingType()) {
5048 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00005049 unsigned FloatEltSize = EltSize;
5050 if (&Sem == &APFloat::x87DoubleExtended)
5051 FloatEltSize = 80;
5052 for (unsigned i = 0; i < NElts; i++) {
5053 llvm::APInt Elt;
5054 if (BigEndian)
5055 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5056 else
5057 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00005058 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00005059 }
5060 } else if (EltTy->isIntegerType()) {
5061 for (unsigned i = 0; i < NElts; i++) {
5062 llvm::APInt Elt;
5063 if (BigEndian)
5064 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5065 else
5066 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5067 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5068 }
5069 } else {
5070 return Error(E);
5071 }
5072 return Success(Elts, E);
5073 }
Eli Friedmanc757de22011-03-25 00:43:55 +00005074 default:
Richard Smith11562c52011-10-28 17:51:58 +00005075 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005076 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005077}
5078
Richard Smith2d406342011-10-22 21:10:00 +00005079bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005080VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005081 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005082 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00005083 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005084
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005085 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005086 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005087
Eli Friedmanb9c71292012-01-03 23:24:20 +00005088 // The number of initializers can be less than the number of
5089 // vector elements. For OpenCL, this can be due to nested vector
5090 // initialization. For GCC compatibility, missing trailing elements
5091 // should be initialized with zeroes.
5092 unsigned CountInits = 0, CountElts = 0;
5093 while (CountElts < NumElements) {
5094 // Handle nested vector initialization.
5095 if (CountInits < NumInits
5096 && E->getInit(CountInits)->getType()->isExtVectorType()) {
5097 APValue v;
5098 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5099 return Error(E);
5100 unsigned vlen = v.getVectorLength();
5101 for (unsigned j = 0; j < vlen; j++)
5102 Elements.push_back(v.getVectorElt(j));
5103 CountElts += vlen;
5104 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005105 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005106 if (CountInits < NumInits) {
5107 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005108 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005109 } else // trailing integer zero.
5110 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5111 Elements.push_back(APValue(sInt));
5112 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005113 } else {
5114 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005115 if (CountInits < NumInits) {
5116 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005117 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005118 } else // trailing float zero.
5119 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5120 Elements.push_back(APValue(f));
5121 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00005122 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00005123 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005124 }
Richard Smith2d406342011-10-22 21:10:00 +00005125 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005126}
5127
Richard Smith2d406342011-10-22 21:10:00 +00005128bool
Richard Smithfddd3842011-12-30 21:15:51 +00005129VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005130 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00005131 QualType EltTy = VT->getElementType();
5132 APValue ZeroElement;
5133 if (EltTy->isIntegerType())
5134 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5135 else
5136 ZeroElement =
5137 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5138
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005139 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00005140 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005141}
5142
Richard Smith2d406342011-10-22 21:10:00 +00005143bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00005144 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005145 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005146}
5147
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005148//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00005149// Array Evaluation
5150//===----------------------------------------------------------------------===//
5151
5152namespace {
5153 class ArrayExprEvaluator
5154 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00005155 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00005156 APValue &Result;
5157 public:
5158
Richard Smithd62306a2011-11-10 06:34:14 +00005159 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5160 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00005161
5162 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00005163 assert((V.isArray() || V.isLValue()) &&
5164 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00005165 Result = V;
5166 return true;
5167 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005168
Richard Smithfddd3842011-12-30 21:15:51 +00005169 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005170 const ConstantArrayType *CAT =
5171 Info.Ctx.getAsConstantArrayType(E->getType());
5172 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005173 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005174
5175 Result = APValue(APValue::UninitArray(), 0,
5176 CAT->getSize().getZExtValue());
5177 if (!Result.hasArrayFiller()) return true;
5178
Richard Smithfddd3842011-12-30 21:15:51 +00005179 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00005180 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005181 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00005182 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00005183 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00005184 }
5185
Richard Smithf3e9e432011-11-07 09:22:26 +00005186 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00005187 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00005188 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5189 const LValue &Subobject,
5190 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00005191 };
5192} // end anonymous namespace
5193
Richard Smithd62306a2011-11-10 06:34:14 +00005194static bool EvaluateArray(const Expr *E, const LValue &This,
5195 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00005196 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00005197 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005198}
5199
5200bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5201 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5202 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005203 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005204
Richard Smithca2cfbf2011-12-22 01:07:19 +00005205 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5206 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00005207 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00005208 LValue LV;
5209 if (!EvaluateLValue(E->getInit(0), LV, Info))
5210 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005211 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00005212 LV.moveInto(Val);
5213 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00005214 }
5215
Richard Smith253c2a32012-01-27 01:14:48 +00005216 bool Success = true;
5217
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005218 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5219 "zero-initialized array shouldn't have any initialized elts");
5220 APValue Filler;
5221 if (Result.isArray() && Result.hasArrayFiller())
5222 Filler = Result.getArrayFiller();
5223
Richard Smith9543c5e2013-04-22 14:44:29 +00005224 unsigned NumEltsToInit = E->getNumInits();
5225 unsigned NumElts = CAT->getSize().getZExtValue();
5226 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
5227
5228 // If the initializer might depend on the array index, run it for each
5229 // array element. For now, just whitelist non-class value-initialization.
5230 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5231 NumEltsToInit = NumElts;
5232
5233 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005234
5235 // If the array was previously zero-initialized, preserve the
5236 // zero-initialized values.
5237 if (!Filler.isUninit()) {
5238 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5239 Result.getArrayInitializedElt(I) = Filler;
5240 if (Result.hasArrayFiller())
5241 Result.getArrayFiller() = Filler;
5242 }
5243
Richard Smithd62306a2011-11-10 06:34:14 +00005244 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005245 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00005246 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5247 const Expr *Init =
5248 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00005249 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00005250 Info, Subobject, Init) ||
5251 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00005252 CAT->getElementType(), 1)) {
5253 if (!Info.keepEvaluatingAfterFailure())
5254 return false;
5255 Success = false;
5256 }
Richard Smithd62306a2011-11-10 06:34:14 +00005257 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005258
Richard Smith9543c5e2013-04-22 14:44:29 +00005259 if (!Result.hasArrayFiller())
5260 return Success;
5261
5262 // If we get here, we have a trivial filler, which we can just evaluate
5263 // once and splat over the rest of the array elements.
5264 assert(FillerExpr && "no array filler for incomplete init list");
5265 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5266 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00005267}
5268
Richard Smith027bf112011-11-17 22:56:20 +00005269bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005270 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5271}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005272
Richard Smith9543c5e2013-04-22 14:44:29 +00005273bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5274 const LValue &Subobject,
5275 APValue *Value,
5276 QualType Type) {
5277 bool HadZeroInit = !Value->isUninit();
5278
5279 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5280 unsigned N = CAT->getSize().getZExtValue();
5281
5282 // Preserve the array filler if we had prior zero-initialization.
5283 APValue Filler =
5284 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5285 : APValue();
5286
5287 *Value = APValue(APValue::UninitArray(), N, N);
5288
5289 if (HadZeroInit)
5290 for (unsigned I = 0; I != N; ++I)
5291 Value->getArrayInitializedElt(I) = Filler;
5292
5293 // Initialize the elements.
5294 LValue ArrayElt = Subobject;
5295 ArrayElt.addArray(Info, E, CAT);
5296 for (unsigned I = 0; I != N; ++I)
5297 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5298 CAT->getElementType()) ||
5299 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5300 CAT->getElementType(), 1))
5301 return false;
5302
5303 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005304 }
Richard Smith027bf112011-11-17 22:56:20 +00005305
Richard Smith9543c5e2013-04-22 14:44:29 +00005306 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00005307 return Error(E);
5308
Richard Smith027bf112011-11-17 22:56:20 +00005309 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00005310
Richard Smithfddd3842011-12-30 21:15:51 +00005311 bool ZeroInit = E->requiresZeroInitialization();
5312 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005313 if (HadZeroInit)
5314 return true;
5315
Richard Smithfddd3842011-12-30 21:15:51 +00005316 if (ZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005317 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005318 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005319 }
5320
Richard Smithcc36f692011-12-22 02:22:31 +00005321 const CXXRecordDecl *RD = FD->getParent();
5322 if (RD->isUnion())
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005323 *Value = APValue((FieldDecl*)0);
Richard Smithcc36f692011-12-22 02:22:31 +00005324 else
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005325 *Value =
Richard Smithcc36f692011-12-22 02:22:31 +00005326 APValue(APValue::UninitStruct(), RD->getNumBases(),
5327 std::distance(RD->field_begin(), RD->field_end()));
5328 return true;
5329 }
5330
Richard Smith027bf112011-11-17 22:56:20 +00005331 const FunctionDecl *Definition = 0;
5332 FD->getBody(Definition);
5333
Richard Smith357362d2011-12-13 06:39:58 +00005334 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5335 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005336
Richard Smith9eae7232012-01-12 18:54:33 +00005337 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005338 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005339 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005340 return false;
5341 }
5342
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005343 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005344 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00005345 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005346 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00005347}
5348
Richard Smithf3e9e432011-11-07 09:22:26 +00005349//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005350// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005351//
5352// As a GNU extension, we support casting pointers to sufficiently-wide integer
5353// types and back in constant folding. Integer values are thus represented
5354// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00005355//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005356
5357namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005358class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00005359 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith2e312c82012-03-03 22:46:17 +00005360 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005361public:
Richard Smith2e312c82012-03-03 22:46:17 +00005362 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005363 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005364
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005365 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005366 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005367 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005368 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005369 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005370 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005371 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005372 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005373 return true;
5374 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005375 bool Success(const llvm::APSInt &SI, const Expr *E) {
5376 return Success(SI, E, Result);
5377 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005378
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005379 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005380 assert(E->getType()->isIntegralOrEnumerationType() &&
5381 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005382 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005383 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005384 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005385 Result.getInt().setIsUnsigned(
5386 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005387 return true;
5388 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005389 bool Success(const llvm::APInt &I, const Expr *E) {
5390 return Success(I, E, Result);
5391 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005392
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005393 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005394 assert(E->getType()->isIntegralOrEnumerationType() &&
5395 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005396 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005397 return true;
5398 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005399 bool Success(uint64_t Value, const Expr *E) {
5400 return Success(Value, E, Result);
5401 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005402
Ken Dyckdbc01912011-03-11 02:13:43 +00005403 bool Success(CharUnits Size, const Expr *E) {
5404 return Success(Size.getQuantity(), E);
5405 }
5406
Richard Smith2e312c82012-03-03 22:46:17 +00005407 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005408 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00005409 Result = V;
5410 return true;
5411 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005412 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00005413 }
Mike Stump11289f42009-09-09 15:08:12 +00005414
Richard Smithfddd3842011-12-30 21:15:51 +00005415 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00005416
Peter Collingbournee9200682011-05-13 03:29:01 +00005417 //===--------------------------------------------------------------------===//
5418 // Visitor Methods
5419 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005420
Chris Lattner7174bf32008-07-12 00:38:25 +00005421 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005422 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005423 }
5424 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005425 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005426 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005427
5428 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5429 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005430 if (CheckReferencedDecl(E, E->getDecl()))
5431 return true;
5432
5433 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005434 }
5435 bool VisitMemberExpr(const MemberExpr *E) {
5436 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00005437 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005438 return true;
5439 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005440
5441 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005442 }
5443
Peter Collingbournee9200682011-05-13 03:29:01 +00005444 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005445 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00005446 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005447 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00005448
Peter Collingbournee9200682011-05-13 03:29:01 +00005449 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005450 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00005451
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005452 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005453 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005454 }
Mike Stump11289f42009-09-09 15:08:12 +00005455
Ted Kremeneke65b0862012-03-06 20:05:56 +00005456 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5457 return Success(E->getValue(), E);
5458 }
5459
Richard Smith4ce706a2011-10-11 21:43:33 +00005460 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00005461 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005462 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005463 }
5464
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005465 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005466 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005467 }
5468
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005469 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
5470 return Success(E->getValue(), E);
5471 }
5472
Douglas Gregor29c42f22012-02-24 07:38:34 +00005473 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5474 return Success(E->getValue(), E);
5475 }
5476
John Wiegley6242b6a2011-04-28 00:16:57 +00005477 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5478 return Success(E->getValue(), E);
5479 }
5480
John Wiegleyf9f65842011-04-25 06:54:41 +00005481 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5482 return Success(E->getValue(), E);
5483 }
5484
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005485 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005486 bool VisitUnaryImag(const UnaryOperator *E);
5487
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005488 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005489 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00005490
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005491private:
Ken Dyck160146e2010-01-27 17:10:57 +00005492 CharUnits GetAlignOfExpr(const Expr *E);
5493 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00005494 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00005495 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005496 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00005497};
Chris Lattner05706e882008-07-11 18:11:29 +00005498} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005499
Richard Smith11562c52011-10-28 17:51:58 +00005500/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
5501/// produce either the integer value or a pointer.
5502///
5503/// GCC has a heinous extension which folds casts between pointer types and
5504/// pointer-sized integral types. We support this by allowing the evaluation of
5505/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
5506/// Some simple arithmetic on such values is supported (they are treated much
5507/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00005508static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00005509 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005510 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005511 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00005512}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005513
Richard Smithf57d8cb2011-12-09 22:58:01 +00005514static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00005515 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005516 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00005517 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005518 if (!Val.isInt()) {
5519 // FIXME: It would be better to produce the diagnostic for casting
5520 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00005521 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005522 return false;
5523 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005524 Result = Val.getInt();
5525 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005526}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005527
Richard Smithf57d8cb2011-12-09 22:58:01 +00005528/// Check whether the given declaration can be directly converted to an integral
5529/// rvalue. If not, no diagnostic is produced; there are other things we can
5530/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005531bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00005532 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005533 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005534 // Check for signedness/width mismatches between E type and ECD value.
5535 bool SameSign = (ECD->getInitVal().isSigned()
5536 == E->getType()->isSignedIntegerOrEnumerationType());
5537 bool SameWidth = (ECD->getInitVal().getBitWidth()
5538 == Info.Ctx.getIntWidth(E->getType()));
5539 if (SameSign && SameWidth)
5540 return Success(ECD->getInitVal(), E);
5541 else {
5542 // Get rid of mismatch (otherwise Success assertions will fail)
5543 // by computing a new value matching the type of E.
5544 llvm::APSInt Val = ECD->getInitVal();
5545 if (!SameSign)
5546 Val.setIsSigned(!ECD->getInitVal().isSigned());
5547 if (!SameWidth)
5548 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
5549 return Success(Val, E);
5550 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005551 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005552 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00005553}
5554
Chris Lattner86ee2862008-10-06 06:40:35 +00005555/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
5556/// as GCC.
5557static int EvaluateBuiltinClassifyType(const CallExpr *E) {
5558 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005559 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00005560 enum gcc_type_class {
5561 no_type_class = -1,
5562 void_type_class, integer_type_class, char_type_class,
5563 enumeral_type_class, boolean_type_class,
5564 pointer_type_class, reference_type_class, offset_type_class,
5565 real_type_class, complex_type_class,
5566 function_type_class, method_type_class,
5567 record_type_class, union_type_class,
5568 array_type_class, string_type_class,
5569 lang_type_class
5570 };
Mike Stump11289f42009-09-09 15:08:12 +00005571
5572 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00005573 // ideal, however it is what gcc does.
5574 if (E->getNumArgs() == 0)
5575 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00005576
Chris Lattner86ee2862008-10-06 06:40:35 +00005577 QualType ArgTy = E->getArg(0)->getType();
5578 if (ArgTy->isVoidType())
5579 return void_type_class;
5580 else if (ArgTy->isEnumeralType())
5581 return enumeral_type_class;
5582 else if (ArgTy->isBooleanType())
5583 return boolean_type_class;
5584 else if (ArgTy->isCharType())
5585 return string_type_class; // gcc doesn't appear to use char_type_class
5586 else if (ArgTy->isIntegerType())
5587 return integer_type_class;
5588 else if (ArgTy->isPointerType())
5589 return pointer_type_class;
5590 else if (ArgTy->isReferenceType())
5591 return reference_type_class;
5592 else if (ArgTy->isRealType())
5593 return real_type_class;
5594 else if (ArgTy->isComplexType())
5595 return complex_type_class;
5596 else if (ArgTy->isFunctionType())
5597 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00005598 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00005599 return record_type_class;
5600 else if (ArgTy->isUnionType())
5601 return union_type_class;
5602 else if (ArgTy->isArrayType())
5603 return array_type_class;
5604 else if (ArgTy->isUnionType())
5605 return union_type_class;
5606 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00005607 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00005608}
5609
Richard Smith5fab0c92011-12-28 19:48:30 +00005610/// EvaluateBuiltinConstantPForLValue - Determine the result of
5611/// __builtin_constant_p when applied to the given lvalue.
5612///
5613/// An lvalue is only "constant" if it is a pointer or reference to the first
5614/// character of a string literal.
5615template<typename LValue>
5616static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00005617 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00005618 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
5619}
5620
5621/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
5622/// GCC as we can manage.
5623static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
5624 QualType ArgType = Arg->getType();
5625
5626 // __builtin_constant_p always has one operand. The rules which gcc follows
5627 // are not precisely documented, but are as follows:
5628 //
5629 // - If the operand is of integral, floating, complex or enumeration type,
5630 // and can be folded to a known value of that type, it returns 1.
5631 // - If the operand and can be folded to a pointer to the first character
5632 // of a string literal (or such a pointer cast to an integral type), it
5633 // returns 1.
5634 //
5635 // Otherwise, it returns 0.
5636 //
5637 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
5638 // its support for this does not currently work.
5639 if (ArgType->isIntegralOrEnumerationType()) {
5640 Expr::EvalResult Result;
5641 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
5642 return false;
5643
5644 APValue &V = Result.Val;
5645 if (V.getKind() == APValue::Int)
5646 return true;
5647
5648 return EvaluateBuiltinConstantPForLValue(V);
5649 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
5650 return Arg->isEvaluatable(Ctx);
5651 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
5652 LValue LV;
5653 Expr::EvalStatus Status;
5654 EvalInfo Info(Ctx, Status);
5655 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
5656 : EvaluatePointer(Arg, LV, Info)) &&
5657 !Status.HasSideEffects)
5658 return EvaluateBuiltinConstantPForLValue(LV);
5659 }
5660
5661 // Anything else isn't considered to be sufficiently constant.
5662 return false;
5663}
5664
John McCall95007602010-05-10 23:27:23 +00005665/// Retrieves the "underlying object type" of the given expression,
5666/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00005667QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
5668 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
5669 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00005670 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00005671 } else if (const Expr *E = B.get<const Expr*>()) {
5672 if (isa<CompoundLiteralExpr>(E))
5673 return E->getType();
John McCall95007602010-05-10 23:27:23 +00005674 }
5675
5676 return QualType();
5677}
5678
Peter Collingbournee9200682011-05-13 03:29:01 +00005679bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00005680 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00005681
5682 {
5683 // The operand of __builtin_object_size is never evaluated for side-effects.
5684 // If there are any, but we can determine the pointed-to object anyway, then
5685 // ignore the side-effects.
5686 SpeculativeEvaluationRAII SpeculativeEval(Info);
5687 if (!EvaluatePointer(E->getArg(0), Base, Info))
5688 return false;
5689 }
John McCall95007602010-05-10 23:27:23 +00005690
5691 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00005692 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00005693
Richard Smithce40ad62011-11-12 22:28:03 +00005694 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00005695 if (T.isNull() ||
5696 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00005697 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00005698 T->isVariablyModifiedType() ||
5699 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005700 return Error(E);
John McCall95007602010-05-10 23:27:23 +00005701
5702 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
5703 CharUnits Offset = Base.getLValueOffset();
5704
5705 if (!Offset.isNegative() && Offset <= Size)
5706 Size -= Offset;
5707 else
5708 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00005709 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00005710}
5711
Peter Collingbournee9200682011-05-13 03:29:01 +00005712bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith01ba47d2012-04-13 00:45:38 +00005713 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005714 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00005715 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005716
5717 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00005718 if (TryEvaluateBuiltinObjectSize(E))
5719 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00005720
Richard Smith0421ce72012-08-07 04:16:51 +00005721 // If evaluating the argument has side-effects, we can't determine the size
5722 // of the object, and so we lower it to unknown now. CodeGen relies on us to
5723 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005724 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00005725 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00005726 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00005727 return Success(0, E);
5728 }
Mike Stump876387b2009-10-27 22:09:17 +00005729
Richard Smith01ade172012-05-23 04:13:20 +00005730 // Expression had no side effects, but we couldn't statically determine the
5731 // size of the referenced object.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005732 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005733 }
5734
Benjamin Kramera801f4a2012-10-06 14:42:22 +00005735 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00005736 case Builtin::BI__builtin_bswap32:
5737 case Builtin::BI__builtin_bswap64: {
5738 APSInt Val;
5739 if (!EvaluateInteger(E->getArg(0), Val, Info))
5740 return false;
5741
5742 return Success(Val.byteSwap(), E);
5743 }
5744
Richard Smith8889a3d2013-06-13 06:26:32 +00005745 case Builtin::BI__builtin_classify_type:
5746 return Success(EvaluateBuiltinClassifyType(E), E);
5747
5748 // FIXME: BI__builtin_clrsb
5749 // FIXME: BI__builtin_clrsbl
5750 // FIXME: BI__builtin_clrsbll
5751
Richard Smith80b3c8e2013-06-13 05:04:16 +00005752 case Builtin::BI__builtin_clz:
5753 case Builtin::BI__builtin_clzl:
5754 case Builtin::BI__builtin_clzll: {
5755 APSInt Val;
5756 if (!EvaluateInteger(E->getArg(0), Val, Info))
5757 return false;
5758 if (!Val)
5759 return Error(E);
5760
5761 return Success(Val.countLeadingZeros(), E);
5762 }
5763
Richard Smith8889a3d2013-06-13 06:26:32 +00005764 case Builtin::BI__builtin_constant_p:
5765 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
5766
Richard Smith80b3c8e2013-06-13 05:04:16 +00005767 case Builtin::BI__builtin_ctz:
5768 case Builtin::BI__builtin_ctzl:
5769 case Builtin::BI__builtin_ctzll: {
5770 APSInt Val;
5771 if (!EvaluateInteger(E->getArg(0), Val, Info))
5772 return false;
5773 if (!Val)
5774 return Error(E);
5775
5776 return Success(Val.countTrailingZeros(), E);
5777 }
5778
Richard Smith8889a3d2013-06-13 06:26:32 +00005779 case Builtin::BI__builtin_eh_return_data_regno: {
5780 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
5781 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
5782 return Success(Operand, E);
5783 }
5784
5785 case Builtin::BI__builtin_expect:
5786 return Visit(E->getArg(0));
5787
5788 case Builtin::BI__builtin_ffs:
5789 case Builtin::BI__builtin_ffsl:
5790 case Builtin::BI__builtin_ffsll: {
5791 APSInt Val;
5792 if (!EvaluateInteger(E->getArg(0), Val, Info))
5793 return false;
5794
5795 unsigned N = Val.countTrailingZeros();
5796 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
5797 }
5798
5799 case Builtin::BI__builtin_fpclassify: {
5800 APFloat Val(0.0);
5801 if (!EvaluateFloat(E->getArg(5), Val, Info))
5802 return false;
5803 unsigned Arg;
5804 switch (Val.getCategory()) {
5805 case APFloat::fcNaN: Arg = 0; break;
5806 case APFloat::fcInfinity: Arg = 1; break;
5807 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
5808 case APFloat::fcZero: Arg = 4; break;
5809 }
5810 return Visit(E->getArg(Arg));
5811 }
5812
5813 case Builtin::BI__builtin_isinf_sign: {
5814 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00005815 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00005816 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
5817 }
5818
5819 case Builtin::BI__builtin_parity:
5820 case Builtin::BI__builtin_parityl:
5821 case Builtin::BI__builtin_parityll: {
5822 APSInt Val;
5823 if (!EvaluateInteger(E->getArg(0), Val, Info))
5824 return false;
5825
5826 return Success(Val.countPopulation() % 2, E);
5827 }
5828
Richard Smith80b3c8e2013-06-13 05:04:16 +00005829 case Builtin::BI__builtin_popcount:
5830 case Builtin::BI__builtin_popcountl:
5831 case Builtin::BI__builtin_popcountll: {
5832 APSInt Val;
5833 if (!EvaluateInteger(E->getArg(0), Val, Info))
5834 return false;
5835
5836 return Success(Val.countPopulation(), E);
5837 }
5838
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005839 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00005840 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005841 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00005842 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00005843 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
5844 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00005845 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00005846 // Fall through.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005847 case Builtin::BI__builtin_strlen:
5848 // As an extension, we support strlen() and __builtin_strlen() as constant
5849 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00005850 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005851 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
5852 // The string literal may have embedded null characters. Find the first
5853 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005854 StringRef Str = S->getString();
5855 StringRef::size_type Pos = Str.find(0);
5856 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005857 Str = Str.substr(0, Pos);
5858
5859 return Success(Str.size(), E);
5860 }
5861
Richard Smithf57d8cb2011-12-09 22:58:01 +00005862 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005863
Richard Smith01ba47d2012-04-13 00:45:38 +00005864 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00005865 case Builtin::BI__atomic_is_lock_free:
5866 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00005867 APSInt SizeVal;
5868 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
5869 return false;
5870
5871 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
5872 // of two less than the maximum inline atomic width, we know it is
5873 // lock-free. If the size isn't a power of two, or greater than the
5874 // maximum alignment where we promote atomics, we know it is not lock-free
5875 // (at least not in the sense of atomic_is_lock_free). Otherwise,
5876 // the answer can only be determined at runtime; for example, 16-byte
5877 // atomics have lock-free implementations on some, but not all,
5878 // x86-64 processors.
5879
5880 // Check power-of-two.
5881 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00005882 if (Size.isPowerOfTwo()) {
5883 // Check against inlining width.
5884 unsigned InlineWidthBits =
5885 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
5886 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
5887 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
5888 Size == CharUnits::One() ||
5889 E->getArg(1)->isNullPointerConstant(Info.Ctx,
5890 Expr::NPC_NeverValueDependent))
5891 // OK, we will inline appropriately-aligned operations of this size,
5892 // and _Atomic(T) is appropriately-aligned.
5893 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005894
Richard Smith01ba47d2012-04-13 00:45:38 +00005895 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
5896 castAs<PointerType>()->getPointeeType();
5897 if (!PointeeType->isIncompleteType() &&
5898 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
5899 // OK, we will inline operations on this object.
5900 return Success(1, E);
5901 }
5902 }
5903 }
Eli Friedmana4c26022011-10-17 21:44:23 +00005904
Richard Smith01ba47d2012-04-13 00:45:38 +00005905 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
5906 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005907 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005908 }
Chris Lattner7174bf32008-07-12 00:38:25 +00005909}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005910
Richard Smith8b3497e2011-10-31 01:37:14 +00005911static bool HasSameBase(const LValue &A, const LValue &B) {
5912 if (!A.getLValueBase())
5913 return !B.getLValueBase();
5914 if (!B.getLValueBase())
5915 return false;
5916
Richard Smithce40ad62011-11-12 22:28:03 +00005917 if (A.getLValueBase().getOpaqueValue() !=
5918 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00005919 const Decl *ADecl = GetLValueBaseDecl(A);
5920 if (!ADecl)
5921 return false;
5922 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00005923 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00005924 return false;
5925 }
5926
5927 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00005928 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00005929}
5930
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005931namespace {
Richard Smith11562c52011-10-28 17:51:58 +00005932
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005933/// \brief Data recursive integer evaluator of certain binary operators.
5934///
5935/// We use a data recursive algorithm for binary operators so that we are able
5936/// to handle extreme cases of chained binary operators without causing stack
5937/// overflow.
5938class DataRecursiveIntBinOpEvaluator {
5939 struct EvalResult {
5940 APValue Val;
5941 bool Failed;
5942
5943 EvalResult() : Failed(false) { }
5944
5945 void swap(EvalResult &RHS) {
5946 Val.swap(RHS.Val);
5947 Failed = RHS.Failed;
5948 RHS.Failed = false;
5949 }
5950 };
5951
5952 struct Job {
5953 const Expr *E;
5954 EvalResult LHSResult; // meaningful only for binary operator expression.
5955 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
5956
5957 Job() : StoredInfo(0) { }
5958 void startSpeculativeEval(EvalInfo &Info) {
5959 OldEvalStatus = Info.EvalStatus;
5960 Info.EvalStatus.Diag = 0;
5961 StoredInfo = &Info;
5962 }
5963 ~Job() {
5964 if (StoredInfo) {
5965 StoredInfo->EvalStatus = OldEvalStatus;
5966 }
5967 }
5968 private:
5969 EvalInfo *StoredInfo; // non-null if status changed.
5970 Expr::EvalStatus OldEvalStatus;
5971 };
5972
5973 SmallVector<Job, 16> Queue;
5974
5975 IntExprEvaluator &IntEval;
5976 EvalInfo &Info;
5977 APValue &FinalResult;
5978
5979public:
5980 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
5981 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
5982
5983 /// \brief True if \param E is a binary operator that we are going to handle
5984 /// data recursively.
5985 /// We handle binary operators that are comma, logical, or that have operands
5986 /// with integral or enumeration type.
5987 static bool shouldEnqueue(const BinaryOperator *E) {
5988 return E->getOpcode() == BO_Comma ||
5989 E->isLogicalOp() ||
5990 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5991 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00005992 }
5993
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005994 bool Traverse(const BinaryOperator *E) {
5995 enqueue(E);
5996 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00005997 while (!Queue.empty())
5998 process(PrevResult);
5999
6000 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006001
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006002 FinalResult.swap(PrevResult.Val);
6003 return true;
6004 }
6005
6006private:
6007 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6008 return IntEval.Success(Value, E, Result);
6009 }
6010 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6011 return IntEval.Success(Value, E, Result);
6012 }
6013 bool Error(const Expr *E) {
6014 return IntEval.Error(E);
6015 }
6016 bool Error(const Expr *E, diag::kind D) {
6017 return IntEval.Error(E, D);
6018 }
6019
6020 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6021 return Info.CCEDiag(E, D);
6022 }
6023
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006024 // \brief Returns true if visiting the RHS is necessary, false otherwise.
6025 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006026 bool &SuppressRHSDiags);
6027
6028 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6029 const BinaryOperator *E, APValue &Result);
6030
6031 void EvaluateExpr(const Expr *E, EvalResult &Result) {
6032 Result.Failed = !Evaluate(Result.Val, Info, E);
6033 if (Result.Failed)
6034 Result.Val = APValue();
6035 }
6036
Richard Trieuba4d0872012-03-21 23:30:30 +00006037 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006038
6039 void enqueue(const Expr *E) {
6040 E = E->IgnoreParens();
6041 Queue.resize(Queue.size()+1);
6042 Queue.back().E = E;
6043 Queue.back().Kind = Job::AnyExprKind;
6044 }
6045};
6046
6047}
6048
6049bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006050 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006051 bool &SuppressRHSDiags) {
6052 if (E->getOpcode() == BO_Comma) {
6053 // Ignore LHS but note if we could not evaluate it.
6054 if (LHSResult.Failed)
6055 Info.EvalStatus.HasSideEffects = true;
6056 return true;
6057 }
6058
6059 if (E->isLogicalOp()) {
6060 bool lhsResult;
6061 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006062 // We were able to evaluate the LHS, see if we can get away with not
6063 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006064 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006065 Success(lhsResult, E, LHSResult.Val);
6066 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006067 }
6068 } else {
6069 // Since we weren't able to evaluate the left hand side, it
6070 // must have had side effects.
6071 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006072
6073 // We can't evaluate the LHS; however, sometimes the result
6074 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6075 // Don't ignore RHS and suppress diagnostics from this arm.
6076 SuppressRHSDiags = true;
6077 }
6078
6079 return true;
6080 }
6081
6082 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6083 E->getRHS()->getType()->isIntegralOrEnumerationType());
6084
6085 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006086 return false; // Ignore RHS;
6087
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006088 return true;
6089}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006090
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006091bool DataRecursiveIntBinOpEvaluator::
6092 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6093 const BinaryOperator *E, APValue &Result) {
6094 if (E->getOpcode() == BO_Comma) {
6095 if (RHSResult.Failed)
6096 return false;
6097 Result = RHSResult.Val;
6098 return true;
6099 }
6100
6101 if (E->isLogicalOp()) {
6102 bool lhsResult, rhsResult;
6103 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
6104 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
6105
6106 if (LHSIsOK) {
6107 if (RHSIsOK) {
6108 if (E->getOpcode() == BO_LOr)
6109 return Success(lhsResult || rhsResult, E, Result);
6110 else
6111 return Success(lhsResult && rhsResult, E, Result);
6112 }
6113 } else {
6114 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006115 // We can't evaluate the LHS; however, sometimes the result
6116 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6117 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006118 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006119 }
6120 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006121
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006122 return false;
6123 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006124
6125 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6126 E->getRHS()->getType()->isIntegralOrEnumerationType());
6127
6128 if (LHSResult.Failed || RHSResult.Failed)
6129 return false;
6130
6131 const APValue &LHSVal = LHSResult.Val;
6132 const APValue &RHSVal = RHSResult.Val;
6133
6134 // Handle cases like (unsigned long)&a + 4.
6135 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
6136 Result = LHSVal;
6137 CharUnits AdditionalOffset = CharUnits::fromQuantity(
6138 RHSVal.getInt().getZExtValue());
6139 if (E->getOpcode() == BO_Add)
6140 Result.getLValueOffset() += AdditionalOffset;
6141 else
6142 Result.getLValueOffset() -= AdditionalOffset;
6143 return true;
6144 }
6145
6146 // Handle cases like 4 + (unsigned long)&a
6147 if (E->getOpcode() == BO_Add &&
6148 RHSVal.isLValue() && LHSVal.isInt()) {
6149 Result = RHSVal;
6150 Result.getLValueOffset() += CharUnits::fromQuantity(
6151 LHSVal.getInt().getZExtValue());
6152 return true;
6153 }
6154
6155 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
6156 // Handle (intptr_t)&&A - (intptr_t)&&B.
6157 if (!LHSVal.getLValueOffset().isZero() ||
6158 !RHSVal.getLValueOffset().isZero())
6159 return false;
6160 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
6161 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
6162 if (!LHSExpr || !RHSExpr)
6163 return false;
6164 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6165 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6166 if (!LHSAddrExpr || !RHSAddrExpr)
6167 return false;
6168 // Make sure both labels come from the same function.
6169 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6170 RHSAddrExpr->getLabel()->getDeclContext())
6171 return false;
6172 Result = APValue(LHSAddrExpr, RHSAddrExpr);
6173 return true;
6174 }
Richard Smith43e77732013-05-07 04:50:00 +00006175
6176 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006177 if (!LHSVal.isInt() || !RHSVal.isInt())
6178 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00006179
6180 // Set up the width and signedness manually, in case it can't be deduced
6181 // from the operation we're performing.
6182 // FIXME: Don't do this in the cases where we can deduce it.
6183 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
6184 E->getType()->isUnsignedIntegerOrEnumerationType());
6185 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
6186 RHSVal.getInt(), Value))
6187 return false;
6188 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006189}
6190
Richard Trieuba4d0872012-03-21 23:30:30 +00006191void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006192 Job &job = Queue.back();
6193
6194 switch (job.Kind) {
6195 case Job::AnyExprKind: {
6196 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
6197 if (shouldEnqueue(Bop)) {
6198 job.Kind = Job::BinOpKind;
6199 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006200 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006201 }
6202 }
6203
6204 EvaluateExpr(job.E, Result);
6205 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006206 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006207 }
6208
6209 case Job::BinOpKind: {
6210 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006211 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006212 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006213 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006214 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006215 }
6216 if (SuppressRHSDiags)
6217 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006218 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006219 job.Kind = Job::BinOpVisitedLHSKind;
6220 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006221 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006222 }
6223
6224 case Job::BinOpVisitedLHSKind: {
6225 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6226 EvalResult RHS;
6227 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00006228 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006229 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006230 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006231 }
6232 }
6233
6234 llvm_unreachable("Invalid Job::Kind!");
6235}
6236
6237bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6238 if (E->isAssignmentOp())
6239 return Error(E);
6240
6241 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
6242 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006243
Anders Carlssonacc79812008-11-16 07:17:21 +00006244 QualType LHSTy = E->getLHS()->getType();
6245 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006246
6247 if (LHSTy->isAnyComplexType()) {
6248 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00006249 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006250
Richard Smith253c2a32012-01-27 01:14:48 +00006251 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
6252 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006253 return false;
6254
Richard Smith253c2a32012-01-27 01:14:48 +00006255 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006256 return false;
6257
6258 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00006259 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006260 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00006261 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006262 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
6263
John McCalle3027922010-08-25 11:45:40 +00006264 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006265 return Success((CR_r == APFloat::cmpEqual &&
6266 CR_i == APFloat::cmpEqual), E);
6267 else {
John McCalle3027922010-08-25 11:45:40 +00006268 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006269 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00006270 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006271 CR_r == APFloat::cmpLessThan ||
6272 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00006273 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006274 CR_i == APFloat::cmpLessThan ||
6275 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006276 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006277 } else {
John McCalle3027922010-08-25 11:45:40 +00006278 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006279 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
6280 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
6281 else {
John McCalle3027922010-08-25 11:45:40 +00006282 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006283 "Invalid compex comparison.");
6284 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
6285 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
6286 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006287 }
6288 }
Mike Stump11289f42009-09-09 15:08:12 +00006289
Anders Carlssonacc79812008-11-16 07:17:21 +00006290 if (LHSTy->isRealFloatingType() &&
6291 RHSTy->isRealFloatingType()) {
6292 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00006293
Richard Smith253c2a32012-01-27 01:14:48 +00006294 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
6295 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00006296 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006297
Richard Smith253c2a32012-01-27 01:14:48 +00006298 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00006299 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006300
Anders Carlssonacc79812008-11-16 07:17:21 +00006301 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00006302
Anders Carlssonacc79812008-11-16 07:17:21 +00006303 switch (E->getOpcode()) {
6304 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006305 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00006306 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006307 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00006308 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006309 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00006310 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006311 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006312 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00006313 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006314 E);
John McCalle3027922010-08-25 11:45:40 +00006315 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006316 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006317 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00006318 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00006319 || CR == APFloat::cmpLessThan
6320 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00006321 }
Anders Carlssonacc79812008-11-16 07:17:21 +00006322 }
Mike Stump11289f42009-09-09 15:08:12 +00006323
Eli Friedmana38da572009-04-28 19:17:36 +00006324 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006325 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00006326 LValue LHSValue, RHSValue;
6327
6328 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6329 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006330 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006331
Richard Smith253c2a32012-01-27 01:14:48 +00006332 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006333 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006334
Richard Smith8b3497e2011-10-31 01:37:14 +00006335 // Reject differing bases from the normal codepath; we special-case
6336 // comparisons to null.
6337 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006338 if (E->getOpcode() == BO_Sub) {
6339 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006340 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6341 return false;
6342 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00006343 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006344 if (!LHSExpr || !RHSExpr)
6345 return false;
6346 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6347 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6348 if (!LHSAddrExpr || !RHSAddrExpr)
6349 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006350 // Make sure both labels come from the same function.
6351 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6352 RHSAddrExpr->getLabel()->getDeclContext())
6353 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006354 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006355 return true;
6356 }
Richard Smith83c68212011-10-31 05:11:32 +00006357 // Inequalities and subtractions between unrelated pointers have
6358 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00006359 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006360 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006361 // A constant address may compare equal to the address of a symbol.
6362 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00006363 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006364 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6365 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006366 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006367 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00006368 // distinct addresses. In clang, the result of such a comparison is
6369 // unspecified, so it is not a constant expression. However, we do know
6370 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00006371 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6372 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006373 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006374 // We can't tell whether weak symbols will end up pointing to the same
6375 // object.
6376 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006377 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006378 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00006379 // (Note that clang defaults to -fmerge-all-constants, which can
6380 // lead to inconsistent results for comparisons involving the address
6381 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00006382 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00006383 }
Eli Friedman64004332009-03-23 04:38:34 +00006384
Richard Smith1b470412012-02-01 08:10:20 +00006385 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
6386 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
6387
Richard Smith84f6dcf2012-02-02 01:16:57 +00006388 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
6389 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
6390
John McCalle3027922010-08-25 11:45:40 +00006391 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00006392 // C++11 [expr.add]p6:
6393 // Unless both pointers point to elements of the same array object, or
6394 // one past the last element of the array object, the behavior is
6395 // undefined.
6396 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6397 !AreElementsOfSameArray(getType(LHSValue.Base),
6398 LHSDesignator, RHSDesignator))
6399 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
6400
Chris Lattner882bdf22010-04-20 17:13:14 +00006401 QualType Type = E->getLHS()->getType();
6402 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006403
Richard Smithd62306a2011-11-10 06:34:14 +00006404 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00006405 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00006406 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006407
Richard Smith1b470412012-02-01 08:10:20 +00006408 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
6409 // and produce incorrect results when it overflows. Such behavior
6410 // appears to be non-conforming, but is common, so perhaps we should
6411 // assume the standard intended for such cases to be undefined behavior
6412 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00006413
Richard Smith1b470412012-02-01 08:10:20 +00006414 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
6415 // overflow in the final conversion to ptrdiff_t.
6416 APSInt LHS(
6417 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
6418 APSInt RHS(
6419 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
6420 APSInt ElemSize(
6421 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
6422 APSInt TrueResult = (LHS - RHS) / ElemSize;
6423 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
6424
6425 if (Result.extend(65) != TrueResult)
6426 HandleOverflow(Info, E, TrueResult, E->getType());
6427 return Success(Result, E);
6428 }
Richard Smithde21b242012-01-31 06:41:30 +00006429
6430 // C++11 [expr.rel]p3:
6431 // Pointers to void (after pointer conversions) can be compared, with a
6432 // result defined as follows: If both pointers represent the same
6433 // address or are both the null pointer value, the result is true if the
6434 // operator is <= or >= and false otherwise; otherwise the result is
6435 // unspecified.
6436 // We interpret this as applying to pointers to *cv* void.
6437 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00006438 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00006439 CCEDiag(E, diag::note_constexpr_void_comparison);
6440
Richard Smith84f6dcf2012-02-02 01:16:57 +00006441 // C++11 [expr.rel]p2:
6442 // - If two pointers point to non-static data members of the same object,
6443 // or to subobjects or array elements fo such members, recursively, the
6444 // pointer to the later declared member compares greater provided the
6445 // two members have the same access control and provided their class is
6446 // not a union.
6447 // [...]
6448 // - Otherwise pointer comparisons are unspecified.
6449 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6450 E->isRelationalOp()) {
6451 bool WasArrayIndex;
6452 unsigned Mismatch =
6453 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
6454 RHSDesignator, WasArrayIndex);
6455 // At the point where the designators diverge, the comparison has a
6456 // specified value if:
6457 // - we are comparing array indices
6458 // - we are comparing fields of a union, or fields with the same access
6459 // Otherwise, the result is unspecified and thus the comparison is not a
6460 // constant expression.
6461 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
6462 Mismatch < RHSDesignator.Entries.size()) {
6463 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
6464 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
6465 if (!LF && !RF)
6466 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
6467 else if (!LF)
6468 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6469 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
6470 << RF->getParent() << RF;
6471 else if (!RF)
6472 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6473 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
6474 << LF->getParent() << LF;
6475 else if (!LF->getParent()->isUnion() &&
6476 LF->getAccess() != RF->getAccess())
6477 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
6478 << LF << LF->getAccess() << RF << RF->getAccess()
6479 << LF->getParent();
6480 }
6481 }
6482
Eli Friedman6c31cb42012-04-16 04:30:08 +00006483 // The comparison here must be unsigned, and performed with the same
6484 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00006485 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
6486 uint64_t CompareLHS = LHSOffset.getQuantity();
6487 uint64_t CompareRHS = RHSOffset.getQuantity();
6488 assert(PtrSize <= 64 && "Unexpected pointer width");
6489 uint64_t Mask = ~0ULL >> (64 - PtrSize);
6490 CompareLHS &= Mask;
6491 CompareRHS &= Mask;
6492
Eli Friedman2f5b7c52012-04-16 19:23:57 +00006493 // If there is a base and this is a relational operator, we can only
6494 // compare pointers within the object in question; otherwise, the result
6495 // depends on where the object is located in memory.
6496 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
6497 QualType BaseTy = getType(LHSValue.Base);
6498 if (BaseTy->isIncompleteType())
6499 return Error(E);
6500 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
6501 uint64_t OffsetLimit = Size.getQuantity();
6502 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
6503 return Error(E);
6504 }
6505
Richard Smith8b3497e2011-10-31 01:37:14 +00006506 switch (E->getOpcode()) {
6507 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00006508 case BO_LT: return Success(CompareLHS < CompareRHS, E);
6509 case BO_GT: return Success(CompareLHS > CompareRHS, E);
6510 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
6511 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
6512 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
6513 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00006514 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006515 }
6516 }
Richard Smith7bb00672012-02-01 01:42:44 +00006517
6518 if (LHSTy->isMemberPointerType()) {
6519 assert(E->isEqualityOp() && "unexpected member pointer operation");
6520 assert(RHSTy->isMemberPointerType() && "invalid comparison");
6521
6522 MemberPtr LHSValue, RHSValue;
6523
6524 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
6525 if (!LHSOK && Info.keepEvaluatingAfterFailure())
6526 return false;
6527
6528 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6529 return false;
6530
6531 // C++11 [expr.eq]p2:
6532 // If both operands are null, they compare equal. Otherwise if only one is
6533 // null, they compare unequal.
6534 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
6535 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
6536 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6537 }
6538
6539 // Otherwise if either is a pointer to a virtual member function, the
6540 // result is unspecified.
6541 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
6542 if (MD->isVirtual())
6543 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6544 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
6545 if (MD->isVirtual())
6546 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6547
6548 // Otherwise they compare equal if and only if they would refer to the
6549 // same member of the same most derived object or the same subobject if
6550 // they were dereferenced with a hypothetical object of the associated
6551 // class type.
6552 bool Equal = LHSValue == RHSValue;
6553 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6554 }
6555
Richard Smithab44d9b2012-02-14 22:35:28 +00006556 if (LHSTy->isNullPtrType()) {
6557 assert(E->isComparisonOp() && "unexpected nullptr operation");
6558 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
6559 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
6560 // are compared, the result is true of the operator is <=, >= or ==, and
6561 // false otherwise.
6562 BinaryOperator::Opcode Opcode = E->getOpcode();
6563 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
6564 }
6565
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006566 assert((!LHSTy->isIntegralOrEnumerationType() ||
6567 !RHSTy->isIntegralOrEnumerationType()) &&
6568 "DataRecursiveIntBinOpEvaluator should have handled integral types");
6569 // We can't continue from here for non-integral types.
6570 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00006571}
6572
Ken Dyck160146e2010-01-27 17:10:57 +00006573CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00006574 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
6575 // result shall be the alignment of the referenced type."
6576 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6577 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00006578
6579 // __alignof is defined to return the preferred alignment.
6580 return Info.Ctx.toCharUnitsFromBits(
6581 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00006582}
6583
Ken Dyck160146e2010-01-27 17:10:57 +00006584CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00006585 E = E->IgnoreParens();
6586
John McCall768439e2013-05-06 07:40:34 +00006587 // The kinds of expressions that we have special-case logic here for
6588 // should be kept up to date with the special checks for those
6589 // expressions in Sema.
6590
Chris Lattner68061312009-01-24 21:53:27 +00006591 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00006592 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00006593 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006594 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6595 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00006596
Chris Lattner68061312009-01-24 21:53:27 +00006597 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006598 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6599 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00006600
Chris Lattner24aeeab2009-01-24 21:09:06 +00006601 return GetAlignOfType(E->getType());
6602}
6603
6604
Peter Collingbournee190dee2011-03-11 19:24:49 +00006605/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
6606/// a result as the expression's type.
6607bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
6608 const UnaryExprOrTypeTraitExpr *E) {
6609 switch(E->getKind()) {
6610 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00006611 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00006612 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006613 else
Ken Dyckdbc01912011-03-11 02:13:43 +00006614 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006615 }
Eli Friedman64004332009-03-23 04:38:34 +00006616
Peter Collingbournee190dee2011-03-11 19:24:49 +00006617 case UETT_VecStep: {
6618 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00006619
Peter Collingbournee190dee2011-03-11 19:24:49 +00006620 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00006621 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00006622
Peter Collingbournee190dee2011-03-11 19:24:49 +00006623 // The vec_step built-in functions that take a 3-component
6624 // vector return 4. (OpenCL 1.1 spec 6.11.12)
6625 if (n == 3)
6626 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00006627
Peter Collingbournee190dee2011-03-11 19:24:49 +00006628 return Success(n, E);
6629 } else
6630 return Success(1, E);
6631 }
6632
6633 case UETT_SizeOf: {
6634 QualType SrcTy = E->getTypeOfArgument();
6635 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
6636 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00006637 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
6638 SrcTy = Ref->getPointeeType();
6639
Richard Smithd62306a2011-11-10 06:34:14 +00006640 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00006641 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00006642 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006643 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006644 }
6645 }
6646
6647 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006648}
6649
Peter Collingbournee9200682011-05-13 03:29:01 +00006650bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00006651 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00006652 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00006653 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006654 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00006655 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00006656 for (unsigned i = 0; i != n; ++i) {
6657 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
6658 switch (ON.getKind()) {
6659 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00006660 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00006661 APSInt IdxResult;
6662 if (!EvaluateInteger(Idx, IdxResult, Info))
6663 return false;
6664 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
6665 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006666 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006667 CurrentType = AT->getElementType();
6668 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
6669 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00006670 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00006671 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006672
Douglas Gregor882211c2010-04-28 22:16:22 +00006673 case OffsetOfExpr::OffsetOfNode::Field: {
6674 FieldDecl *MemberDecl = ON.getField();
6675 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006676 if (!RT)
6677 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006678 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006679 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00006680 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00006681 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00006682 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00006683 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00006684 CurrentType = MemberDecl->getType().getNonReferenceType();
6685 break;
6686 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006687
Douglas Gregor882211c2010-04-28 22:16:22 +00006688 case OffsetOfExpr::OffsetOfNode::Identifier:
6689 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00006690
Douglas Gregord1702062010-04-29 00:18:15 +00006691 case OffsetOfExpr::OffsetOfNode::Base: {
6692 CXXBaseSpecifier *BaseSpec = ON.getBase();
6693 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006694 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006695
6696 // Find the layout of the class whose base we are looking into.
6697 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006698 if (!RT)
6699 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006700 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006701 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00006702 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
6703
6704 // Find the base class itself.
6705 CurrentType = BaseSpec->getType();
6706 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
6707 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006708 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006709
6710 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00006711 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00006712 break;
6713 }
Douglas Gregor882211c2010-04-28 22:16:22 +00006714 }
6715 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006716 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006717}
6718
Chris Lattnere13042c2008-07-11 19:10:17 +00006719bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006720 switch (E->getOpcode()) {
6721 default:
6722 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
6723 // See C99 6.6p3.
6724 return Error(E);
6725 case UO_Extension:
6726 // FIXME: Should extension allow i-c-e extension expressions in its scope?
6727 // If so, we could clear the diagnostic ID.
6728 return Visit(E->getSubExpr());
6729 case UO_Plus:
6730 // The result is just the value.
6731 return Visit(E->getSubExpr());
6732 case UO_Minus: {
6733 if (!Visit(E->getSubExpr()))
6734 return false;
6735 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00006736 const APSInt &Value = Result.getInt();
6737 if (Value.isSigned() && Value.isMinSignedValue())
6738 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
6739 E->getType());
6740 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006741 }
6742 case UO_Not: {
6743 if (!Visit(E->getSubExpr()))
6744 return false;
6745 if (!Result.isInt()) return Error(E);
6746 return Success(~Result.getInt(), E);
6747 }
6748 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00006749 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00006750 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00006751 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006752 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006753 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006754 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006755}
Mike Stump11289f42009-09-09 15:08:12 +00006756
Chris Lattner477c4be2008-07-12 01:15:53 +00006757/// HandleCast - This is used to evaluate implicit or explicit casts where the
6758/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00006759bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
6760 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006761 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00006762 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006763
Eli Friedmanc757de22011-03-25 00:43:55 +00006764 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00006765 case CK_BaseToDerived:
6766 case CK_DerivedToBase:
6767 case CK_UncheckedDerivedToBase:
6768 case CK_Dynamic:
6769 case CK_ToUnion:
6770 case CK_ArrayToPointerDecay:
6771 case CK_FunctionToPointerDecay:
6772 case CK_NullToPointer:
6773 case CK_NullToMemberPointer:
6774 case CK_BaseToDerivedMemberPointer:
6775 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00006776 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00006777 case CK_ConstructorConversion:
6778 case CK_IntegralToPointer:
6779 case CK_ToVoid:
6780 case CK_VectorSplat:
6781 case CK_IntegralToFloating:
6782 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00006783 case CK_CPointerToObjCPointerCast:
6784 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006785 case CK_AnyPointerToBlockPointerCast:
6786 case CK_ObjCObjectLValueCast:
6787 case CK_FloatingRealToComplex:
6788 case CK_FloatingComplexToReal:
6789 case CK_FloatingComplexCast:
6790 case CK_FloatingComplexToIntegralComplex:
6791 case CK_IntegralRealToComplex:
6792 case CK_IntegralComplexCast:
6793 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00006794 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006795 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00006796 case CK_NonAtomicToAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00006797 llvm_unreachable("invalid cast kind for integral value");
6798
Eli Friedman9faf2f92011-03-25 19:07:11 +00006799 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006800 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006801 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00006802 case CK_ARCProduceObject:
6803 case CK_ARCConsumeObject:
6804 case CK_ARCReclaimReturnedObject:
6805 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00006806 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006807 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006808
Richard Smith4ef685b2012-01-17 21:17:26 +00006809 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00006810 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006811 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00006812 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00006813 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006814
6815 case CK_MemberPointerToBoolean:
6816 case CK_PointerToBoolean:
6817 case CK_IntegralToBoolean:
6818 case CK_FloatingToBoolean:
6819 case CK_FloatingComplexToBoolean:
6820 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006821 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00006822 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00006823 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006824 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006825 }
6826
Eli Friedmanc757de22011-03-25 00:43:55 +00006827 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00006828 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00006829 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00006830
Eli Friedman742421e2009-02-20 01:15:07 +00006831 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006832 // Allow casts of address-of-label differences if they are no-ops
6833 // or narrowing. (The narrowing case isn't actually guaranteed to
6834 // be constant-evaluatable except in some narrow cases which are hard
6835 // to detect here. We let it through on the assumption the user knows
6836 // what they are doing.)
6837 if (Result.isAddrLabelDiff())
6838 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00006839 // Only allow casts of lvalues if they are lossless.
6840 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
6841 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006842
Richard Smith911e1422012-01-30 22:27:01 +00006843 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
6844 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00006845 }
Mike Stump11289f42009-09-09 15:08:12 +00006846
Eli Friedmanc757de22011-03-25 00:43:55 +00006847 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00006848 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6849
John McCall45d55e42010-05-07 21:00:08 +00006850 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00006851 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00006852 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00006853
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006854 if (LV.getLValueBase()) {
6855 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00006856 // FIXME: Allow a larger integer size than the pointer size, and allow
6857 // narrowing back down to pointer width in subsequent integral casts.
6858 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006859 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006860 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006861
Richard Smithcf74da72011-11-16 07:18:12 +00006862 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00006863 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006864 return true;
6865 }
6866
Ken Dyck02990832010-01-15 12:37:54 +00006867 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
6868 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00006869 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006870 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006871
Eli Friedmanc757de22011-03-25 00:43:55 +00006872 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00006873 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006874 if (!EvaluateComplex(SubExpr, C, Info))
6875 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00006876 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006877 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00006878
Eli Friedmanc757de22011-03-25 00:43:55 +00006879 case CK_FloatingToIntegral: {
6880 APFloat F(0.0);
6881 if (!EvaluateFloat(SubExpr, F, Info))
6882 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00006883
Richard Smith357362d2011-12-13 06:39:58 +00006884 APSInt Value;
6885 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
6886 return false;
6887 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006888 }
6889 }
Mike Stump11289f42009-09-09 15:08:12 +00006890
Eli Friedmanc757de22011-03-25 00:43:55 +00006891 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00006892}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006893
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006894bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6895 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00006896 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006897 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
6898 return false;
6899 if (!LV.isComplexInt())
6900 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006901 return Success(LV.getComplexIntReal(), E);
6902 }
6903
6904 return Visit(E->getSubExpr());
6905}
6906
Eli Friedman4e7a2412009-02-27 04:45:43 +00006907bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006908 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00006909 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006910 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
6911 return false;
6912 if (!LV.isComplexInt())
6913 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006914 return Success(LV.getComplexIntImag(), E);
6915 }
6916
Richard Smith4a678122011-10-24 18:44:57 +00006917 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00006918 return Success(0, E);
6919}
6920
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006921bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
6922 return Success(E->getPackLength(), E);
6923}
6924
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006925bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
6926 return Success(E->getValue(), E);
6927}
6928
Chris Lattner05706e882008-07-11 18:11:29 +00006929//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00006930// Float Evaluation
6931//===----------------------------------------------------------------------===//
6932
6933namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006934class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00006935 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00006936 APFloat &Result;
6937public:
6938 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006939 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00006940
Richard Smith2e312c82012-03-03 22:46:17 +00006941 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006942 Result = V.getFloat();
6943 return true;
6944 }
Eli Friedman24c01542008-08-22 00:06:13 +00006945
Richard Smithfddd3842011-12-30 21:15:51 +00006946 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00006947 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
6948 return true;
6949 }
6950
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006951 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00006952
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006953 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00006954 bool VisitBinaryOperator(const BinaryOperator *E);
6955 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006956 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00006957
John McCallb1fb0d32010-05-07 22:08:54 +00006958 bool VisitUnaryReal(const UnaryOperator *E);
6959 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00006960
Richard Smithfddd3842011-12-30 21:15:51 +00006961 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00006962};
6963} // end anonymous namespace
6964
6965static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006966 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006967 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00006968}
6969
Jay Foad39c79802011-01-12 09:06:06 +00006970static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00006971 QualType ResultTy,
6972 const Expr *Arg,
6973 bool SNaN,
6974 llvm::APFloat &Result) {
6975 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
6976 if (!S) return false;
6977
6978 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
6979
6980 llvm::APInt fill;
6981
6982 // Treat empty strings as if they were zero.
6983 if (S->getString().empty())
6984 fill = llvm::APInt(32, 0);
6985 else if (S->getString().getAsInteger(0, fill))
6986 return false;
6987
6988 if (SNaN)
6989 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
6990 else
6991 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
6992 return true;
6993}
6994
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006995bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006996 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006997 default:
6998 return ExprEvaluatorBaseTy::VisitCallExpr(E);
6999
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007000 case Builtin::BI__builtin_huge_val:
7001 case Builtin::BI__builtin_huge_valf:
7002 case Builtin::BI__builtin_huge_vall:
7003 case Builtin::BI__builtin_inf:
7004 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007005 case Builtin::BI__builtin_infl: {
7006 const llvm::fltSemantics &Sem =
7007 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00007008 Result = llvm::APFloat::getInf(Sem);
7009 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007010 }
Mike Stump11289f42009-09-09 15:08:12 +00007011
John McCall16291492010-02-28 13:00:19 +00007012 case Builtin::BI__builtin_nans:
7013 case Builtin::BI__builtin_nansf:
7014 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007015 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7016 true, Result))
7017 return Error(E);
7018 return true;
John McCall16291492010-02-28 13:00:19 +00007019
Chris Lattner0b7282e2008-10-06 06:31:58 +00007020 case Builtin::BI__builtin_nan:
7021 case Builtin::BI__builtin_nanf:
7022 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00007023 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00007024 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00007025 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7026 false, Result))
7027 return Error(E);
7028 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007029
7030 case Builtin::BI__builtin_fabs:
7031 case Builtin::BI__builtin_fabsf:
7032 case Builtin::BI__builtin_fabsl:
7033 if (!EvaluateFloat(E->getArg(0), Result, Info))
7034 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007035
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007036 if (Result.isNegative())
7037 Result.changeSign();
7038 return true;
7039
Richard Smith8889a3d2013-06-13 06:26:32 +00007040 // FIXME: Builtin::BI__builtin_powi
7041 // FIXME: Builtin::BI__builtin_powif
7042 // FIXME: Builtin::BI__builtin_powil
7043
Mike Stump11289f42009-09-09 15:08:12 +00007044 case Builtin::BI__builtin_copysign:
7045 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007046 case Builtin::BI__builtin_copysignl: {
7047 APFloat RHS(0.);
7048 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
7049 !EvaluateFloat(E->getArg(1), RHS, Info))
7050 return false;
7051 Result.copySign(RHS);
7052 return true;
7053 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007054 }
7055}
7056
John McCallb1fb0d32010-05-07 22:08:54 +00007057bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007058 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7059 ComplexValue CV;
7060 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7061 return false;
7062 Result = CV.FloatReal;
7063 return true;
7064 }
7065
7066 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00007067}
7068
7069bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007070 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7071 ComplexValue CV;
7072 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7073 return false;
7074 Result = CV.FloatImag;
7075 return true;
7076 }
7077
Richard Smith4a678122011-10-24 18:44:57 +00007078 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00007079 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
7080 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00007081 return true;
7082}
7083
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007084bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007085 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007086 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007087 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00007088 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00007089 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00007090 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
7091 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007092 Result.changeSign();
7093 return true;
7094 }
7095}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007096
Eli Friedman24c01542008-08-22 00:06:13 +00007097bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007098 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7099 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00007100
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007101 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00007102 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
7103 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00007104 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00007105 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
7106 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00007107}
7108
7109bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
7110 Result = E->getValue();
7111 return true;
7112}
7113
Peter Collingbournee9200682011-05-13 03:29:01 +00007114bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
7115 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00007116
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007117 switch (E->getCastKind()) {
7118 default:
Richard Smith11562c52011-10-28 17:51:58 +00007119 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007120
7121 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007122 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00007123 return EvaluateInteger(SubExpr, IntResult, Info) &&
7124 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
7125 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007126 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007127
7128 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007129 if (!Visit(SubExpr))
7130 return false;
Richard Smith357362d2011-12-13 06:39:58 +00007131 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
7132 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007133 }
John McCalld7646252010-11-14 08:17:51 +00007134
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007135 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00007136 ComplexValue V;
7137 if (!EvaluateComplex(SubExpr, V, Info))
7138 return false;
7139 Result = V.getComplexFloatReal();
7140 return true;
7141 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007142 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007143}
7144
Eli Friedman24c01542008-08-22 00:06:13 +00007145//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007146// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00007147//===----------------------------------------------------------------------===//
7148
7149namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007150class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00007151 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00007152 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00007153
Anders Carlsson537969c2008-11-16 20:27:53 +00007154public:
John McCall93d91dc2010-05-07 17:22:02 +00007155 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007156 : ExprEvaluatorBaseTy(info), Result(Result) {}
7157
Richard Smith2e312c82012-03-03 22:46:17 +00007158 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007159 Result.setFrom(V);
7160 return true;
7161 }
Mike Stump11289f42009-09-09 15:08:12 +00007162
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007163 bool ZeroInitialization(const Expr *E);
7164
Anders Carlsson537969c2008-11-16 20:27:53 +00007165 //===--------------------------------------------------------------------===//
7166 // Visitor Methods
7167 //===--------------------------------------------------------------------===//
7168
Peter Collingbournee9200682011-05-13 03:29:01 +00007169 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007170 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00007171 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007172 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007173 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007174};
7175} // end anonymous namespace
7176
John McCall93d91dc2010-05-07 17:22:02 +00007177static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
7178 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007179 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007180 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007181}
7182
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007183bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00007184 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007185 if (ElemTy->isRealFloatingType()) {
7186 Result.makeComplexFloat();
7187 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
7188 Result.FloatReal = Zero;
7189 Result.FloatImag = Zero;
7190 } else {
7191 Result.makeComplexInt();
7192 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
7193 Result.IntReal = Zero;
7194 Result.IntImag = Zero;
7195 }
7196 return true;
7197}
7198
Peter Collingbournee9200682011-05-13 03:29:01 +00007199bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
7200 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007201
7202 if (SubExpr->getType()->isRealFloatingType()) {
7203 Result.makeComplexFloat();
7204 APFloat &Imag = Result.FloatImag;
7205 if (!EvaluateFloat(SubExpr, Imag, Info))
7206 return false;
7207
7208 Result.FloatReal = APFloat(Imag.getSemantics());
7209 return true;
7210 } else {
7211 assert(SubExpr->getType()->isIntegerType() &&
7212 "Unexpected imaginary literal.");
7213
7214 Result.makeComplexInt();
7215 APSInt &Imag = Result.IntImag;
7216 if (!EvaluateInteger(SubExpr, Imag, Info))
7217 return false;
7218
7219 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
7220 return true;
7221 }
7222}
7223
Peter Collingbournee9200682011-05-13 03:29:01 +00007224bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007225
John McCallfcef3cf2010-12-14 17:51:41 +00007226 switch (E->getCastKind()) {
7227 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007228 case CK_BaseToDerived:
7229 case CK_DerivedToBase:
7230 case CK_UncheckedDerivedToBase:
7231 case CK_Dynamic:
7232 case CK_ToUnion:
7233 case CK_ArrayToPointerDecay:
7234 case CK_FunctionToPointerDecay:
7235 case CK_NullToPointer:
7236 case CK_NullToMemberPointer:
7237 case CK_BaseToDerivedMemberPointer:
7238 case CK_DerivedToBaseMemberPointer:
7239 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00007240 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00007241 case CK_ConstructorConversion:
7242 case CK_IntegralToPointer:
7243 case CK_PointerToIntegral:
7244 case CK_PointerToBoolean:
7245 case CK_ToVoid:
7246 case CK_VectorSplat:
7247 case CK_IntegralCast:
7248 case CK_IntegralToBoolean:
7249 case CK_IntegralToFloating:
7250 case CK_FloatingToIntegral:
7251 case CK_FloatingToBoolean:
7252 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007253 case CK_CPointerToObjCPointerCast:
7254 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007255 case CK_AnyPointerToBlockPointerCast:
7256 case CK_ObjCObjectLValueCast:
7257 case CK_FloatingComplexToReal:
7258 case CK_FloatingComplexToBoolean:
7259 case CK_IntegralComplexToReal:
7260 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00007261 case CK_ARCProduceObject:
7262 case CK_ARCConsumeObject:
7263 case CK_ARCReclaimReturnedObject:
7264 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007265 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00007266 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007267 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007268 case CK_NonAtomicToAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00007269 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00007270
John McCallfcef3cf2010-12-14 17:51:41 +00007271 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007272 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00007273 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007274 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007275
7276 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007277 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007278 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007279 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007280
7281 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007282 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00007283 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007284 return false;
7285
John McCallfcef3cf2010-12-14 17:51:41 +00007286 Result.makeComplexFloat();
7287 Result.FloatImag = APFloat(Real.getSemantics());
7288 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007289 }
7290
John McCallfcef3cf2010-12-14 17:51:41 +00007291 case CK_FloatingComplexCast: {
7292 if (!Visit(E->getSubExpr()))
7293 return false;
7294
7295 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7296 QualType From
7297 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7298
Richard Smith357362d2011-12-13 06:39:58 +00007299 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
7300 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007301 }
7302
7303 case CK_FloatingComplexToIntegralComplex: {
7304 if (!Visit(E->getSubExpr()))
7305 return false;
7306
7307 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7308 QualType From
7309 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7310 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00007311 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
7312 To, Result.IntReal) &&
7313 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
7314 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007315 }
7316
7317 case CK_IntegralRealToComplex: {
7318 APSInt &Real = Result.IntReal;
7319 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
7320 return false;
7321
7322 Result.makeComplexInt();
7323 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
7324 return true;
7325 }
7326
7327 case CK_IntegralComplexCast: {
7328 if (!Visit(E->getSubExpr()))
7329 return false;
7330
7331 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7332 QualType From
7333 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7334
Richard Smith911e1422012-01-30 22:27:01 +00007335 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7336 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007337 return true;
7338 }
7339
7340 case CK_IntegralComplexToFloatingComplex: {
7341 if (!Visit(E->getSubExpr()))
7342 return false;
7343
Ted Kremenek28831752012-08-23 20:46:57 +00007344 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007345 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00007346 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007347 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00007348 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7349 To, Result.FloatReal) &&
7350 HandleIntToFloatCast(Info, E, From, Result.IntImag,
7351 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007352 }
7353 }
7354
7355 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007356}
7357
John McCall93d91dc2010-05-07 17:22:02 +00007358bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007359 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00007360 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7361
Richard Smith253c2a32012-01-27 01:14:48 +00007362 bool LHSOK = Visit(E->getLHS());
7363 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00007364 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007365
John McCall93d91dc2010-05-07 17:22:02 +00007366 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00007367 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00007368 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007369
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007370 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
7371 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007372 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007373 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007374 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007375 if (Result.isComplexFloat()) {
7376 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
7377 APFloat::rmNearestTiesToEven);
7378 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
7379 APFloat::rmNearestTiesToEven);
7380 } else {
7381 Result.getComplexIntReal() += RHS.getComplexIntReal();
7382 Result.getComplexIntImag() += RHS.getComplexIntImag();
7383 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007384 break;
John McCalle3027922010-08-25 11:45:40 +00007385 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007386 if (Result.isComplexFloat()) {
7387 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
7388 APFloat::rmNearestTiesToEven);
7389 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
7390 APFloat::rmNearestTiesToEven);
7391 } else {
7392 Result.getComplexIntReal() -= RHS.getComplexIntReal();
7393 Result.getComplexIntImag() -= RHS.getComplexIntImag();
7394 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007395 break;
John McCalle3027922010-08-25 11:45:40 +00007396 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007397 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00007398 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007399 APFloat &LHS_r = LHS.getComplexFloatReal();
7400 APFloat &LHS_i = LHS.getComplexFloatImag();
7401 APFloat &RHS_r = RHS.getComplexFloatReal();
7402 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00007403
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007404 APFloat Tmp = LHS_r;
7405 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7406 Result.getComplexFloatReal() = Tmp;
7407 Tmp = LHS_i;
7408 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7409 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
7410
7411 Tmp = LHS_r;
7412 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7413 Result.getComplexFloatImag() = Tmp;
7414 Tmp = LHS_i;
7415 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7416 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
7417 } else {
John McCall93d91dc2010-05-07 17:22:02 +00007418 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00007419 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007420 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
7421 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00007422 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007423 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
7424 LHS.getComplexIntImag() * RHS.getComplexIntReal());
7425 }
7426 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007427 case BO_Div:
7428 if (Result.isComplexFloat()) {
7429 ComplexValue LHS = Result;
7430 APFloat &LHS_r = LHS.getComplexFloatReal();
7431 APFloat &LHS_i = LHS.getComplexFloatImag();
7432 APFloat &RHS_r = RHS.getComplexFloatReal();
7433 APFloat &RHS_i = RHS.getComplexFloatImag();
7434 APFloat &Res_r = Result.getComplexFloatReal();
7435 APFloat &Res_i = Result.getComplexFloatImag();
7436
7437 APFloat Den = RHS_r;
7438 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7439 APFloat Tmp = RHS_i;
7440 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7441 Den.add(Tmp, APFloat::rmNearestTiesToEven);
7442
7443 Res_r = LHS_r;
7444 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7445 Tmp = LHS_i;
7446 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7447 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
7448 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
7449
7450 Res_i = LHS_i;
7451 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7452 Tmp = LHS_r;
7453 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7454 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
7455 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
7456 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007457 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
7458 return Error(E, diag::note_expr_divide_by_zero);
7459
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007460 ComplexValue LHS = Result;
7461 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
7462 RHS.getComplexIntImag() * RHS.getComplexIntImag();
7463 Result.getComplexIntReal() =
7464 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
7465 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
7466 Result.getComplexIntImag() =
7467 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
7468 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
7469 }
7470 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007471 }
7472
John McCall93d91dc2010-05-07 17:22:02 +00007473 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007474}
7475
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007476bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7477 // Get the operand value into 'Result'.
7478 if (!Visit(E->getSubExpr()))
7479 return false;
7480
7481 switch (E->getOpcode()) {
7482 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007483 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007484 case UO_Extension:
7485 return true;
7486 case UO_Plus:
7487 // The result is always just the subexpr.
7488 return true;
7489 case UO_Minus:
7490 if (Result.isComplexFloat()) {
7491 Result.getComplexFloatReal().changeSign();
7492 Result.getComplexFloatImag().changeSign();
7493 }
7494 else {
7495 Result.getComplexIntReal() = -Result.getComplexIntReal();
7496 Result.getComplexIntImag() = -Result.getComplexIntImag();
7497 }
7498 return true;
7499 case UO_Not:
7500 if (Result.isComplexFloat())
7501 Result.getComplexFloatImag().changeSign();
7502 else
7503 Result.getComplexIntImag() = -Result.getComplexIntImag();
7504 return true;
7505 }
7506}
7507
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007508bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7509 if (E->getNumInits() == 2) {
7510 if (E->getType()->isComplexType()) {
7511 Result.makeComplexFloat();
7512 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
7513 return false;
7514 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
7515 return false;
7516 } else {
7517 Result.makeComplexInt();
7518 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
7519 return false;
7520 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
7521 return false;
7522 }
7523 return true;
7524 }
7525 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
7526}
7527
Anders Carlsson537969c2008-11-16 20:27:53 +00007528//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00007529// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
7530// implicit conversion.
7531//===----------------------------------------------------------------------===//
7532
7533namespace {
7534class AtomicExprEvaluator :
7535 public ExprEvaluatorBase<AtomicExprEvaluator, bool> {
7536 APValue &Result;
7537public:
7538 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
7539 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7540
7541 bool Success(const APValue &V, const Expr *E) {
7542 Result = V;
7543 return true;
7544 }
7545
7546 bool ZeroInitialization(const Expr *E) {
7547 ImplicitValueInitExpr VIE(
7548 E->getType()->castAs<AtomicType>()->getValueType());
7549 return Evaluate(Result, Info, &VIE);
7550 }
7551
7552 bool VisitCastExpr(const CastExpr *E) {
7553 switch (E->getCastKind()) {
7554 default:
7555 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7556 case CK_NonAtomicToAtomic:
7557 return Evaluate(Result, Info, E->getSubExpr());
7558 }
7559 }
7560};
7561} // end anonymous namespace
7562
7563static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
7564 assert(E->isRValue() && E->getType()->isAtomicType());
7565 return AtomicExprEvaluator(Info, Result).Visit(E);
7566}
7567
7568//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00007569// Void expression evaluation, primarily for a cast to void on the LHS of a
7570// comma operator
7571//===----------------------------------------------------------------------===//
7572
7573namespace {
7574class VoidExprEvaluator
7575 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
7576public:
7577 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
7578
Richard Smith2e312c82012-03-03 22:46:17 +00007579 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00007580
7581 bool VisitCastExpr(const CastExpr *E) {
7582 switch (E->getCastKind()) {
7583 default:
7584 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7585 case CK_ToVoid:
7586 VisitIgnoredValue(E->getSubExpr());
7587 return true;
7588 }
7589 }
7590};
7591} // end anonymous namespace
7592
7593static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
7594 assert(E->isRValue() && E->getType()->isVoidType());
7595 return VoidExprEvaluator(Info).Visit(E);
7596}
7597
7598//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00007599// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00007600//===----------------------------------------------------------------------===//
7601
Richard Smith2e312c82012-03-03 22:46:17 +00007602static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007603 // In C, function designators are not lvalues, but we evaluate them as if they
7604 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00007605 QualType T = E->getType();
7606 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00007607 LValue LV;
7608 if (!EvaluateLValue(E, LV, Info))
7609 return false;
7610 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007611 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007612 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007613 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007614 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007615 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007616 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007617 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00007618 LValue LV;
7619 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007620 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007621 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007622 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00007623 llvm::APFloat F(0.0);
7624 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007625 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007626 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00007627 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00007628 ComplexValue C;
7629 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007630 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007631 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007632 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00007633 MemberPtr P;
7634 if (!EvaluateMemberPointer(E, P, Info))
7635 return false;
7636 P.moveInto(Result);
7637 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00007638 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007639 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007640 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00007641 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00007642 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007643 Result = Info.CurrentCall->Temporaries[E];
Richard Smitha23ab512013-05-23 00:30:41 +00007644 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007645 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007646 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00007647 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
7648 return false;
7649 Result = Info.CurrentCall->Temporaries[E];
Richard Smitha23ab512013-05-23 00:30:41 +00007650 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007651 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007652 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00007653 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00007654 if (!EvaluateVoid(E, Info))
7655 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007656 } else if (T->isAtomicType()) {
7657 if (!EvaluateAtomic(E, Result, Info))
7658 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007659 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007660 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00007661 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007662 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007663 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00007664 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007665 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007666
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00007667 return true;
7668}
7669
Richard Smithb228a862012-02-15 02:18:13 +00007670/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
7671/// cases, the in-place evaluation is essential, since later initializers for
7672/// an object can indirectly refer to subobjects which were initialized earlier.
7673static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00007674 const Expr *E, bool AllowNonLiteralTypes) {
7675 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00007676 return false;
7677
7678 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00007679 // Evaluate arrays and record types in-place, so that later initializers can
7680 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00007681 if (E->getType()->isArrayType())
7682 return EvaluateArray(E, This, Result, Info);
7683 else if (E->getType()->isRecordType())
7684 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00007685 }
7686
7687 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00007688 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00007689}
7690
Richard Smithf57d8cb2011-12-09 22:58:01 +00007691/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
7692/// lvalue-to-rvalue cast if it is an lvalue.
7693static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00007694 if (!CheckLiteralType(Info, E))
7695 return false;
7696
Richard Smith2e312c82012-03-03 22:46:17 +00007697 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007698 return false;
7699
7700 if (E->isGLValue()) {
7701 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00007702 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00007703 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007704 return false;
7705 }
7706
Richard Smith2e312c82012-03-03 22:46:17 +00007707 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00007708 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007709}
Richard Smith11562c52011-10-28 17:51:58 +00007710
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007711static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
7712 const ASTContext &Ctx, bool &IsConst) {
7713 // Fast-path evaluations of integer literals, since we sometimes see files
7714 // containing vast quantities of these.
7715 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
7716 Result.Val = APValue(APSInt(L->getValue(),
7717 L->getType()->isUnsignedIntegerType()));
7718 IsConst = true;
7719 return true;
7720 }
7721
7722 // FIXME: Evaluating values of large array and record types can cause
7723 // performance problems. Only do so in C++11 for now.
7724 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
7725 Exp->getType()->isRecordType()) &&
7726 !Ctx.getLangOpts().CPlusPlus11) {
7727 IsConst = false;
7728 return true;
7729 }
7730 return false;
7731}
7732
7733
Richard Smith7b553f12011-10-29 00:50:52 +00007734/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00007735/// any crazy technique (that has nothing to do with language standards) that
7736/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00007737/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
7738/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00007739bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007740 bool IsConst;
7741 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
7742 return IsConst;
7743
Richard Smithf57d8cb2011-12-09 22:58:01 +00007744 EvalInfo Info(Ctx, Result);
7745 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00007746}
7747
Jay Foad39c79802011-01-12 09:06:06 +00007748bool Expr::EvaluateAsBooleanCondition(bool &Result,
7749 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00007750 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00007751 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00007752 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00007753}
7754
Richard Smith5fab0c92011-12-28 19:48:30 +00007755bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
7756 SideEffectsKind AllowSideEffects) const {
7757 if (!getType()->isIntegralOrEnumerationType())
7758 return false;
7759
Richard Smith11562c52011-10-28 17:51:58 +00007760 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00007761 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
7762 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00007763 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007764
Richard Smith11562c52011-10-28 17:51:58 +00007765 Result = ExprResult.Val.getInt();
7766 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00007767}
7768
Jay Foad39c79802011-01-12 09:06:06 +00007769bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00007770 EvalInfo Info(Ctx, Result);
7771
John McCall45d55e42010-05-07 21:00:08 +00007772 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007773 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
7774 !CheckLValueConstantExpression(Info, getExprLoc(),
7775 Ctx.getLValueReferenceType(getType()), LV))
7776 return false;
7777
Richard Smith2e312c82012-03-03 22:46:17 +00007778 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00007779 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00007780}
7781
Richard Smithd0b4dd62011-12-19 06:19:21 +00007782bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
7783 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007784 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00007785 // FIXME: Evaluating initializers for large array and record types can cause
7786 // performance problems. Only do so in C++11 for now.
7787 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007788 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00007789 return false;
7790
Richard Smithd0b4dd62011-12-19 06:19:21 +00007791 Expr::EvalStatus EStatus;
7792 EStatus.Diag = &Notes;
7793
7794 EvalInfo InitInfo(Ctx, EStatus);
7795 InitInfo.setEvaluatingDecl(VD, Value);
7796
7797 LValue LVal;
7798 LVal.set(VD);
7799
Richard Smithfddd3842011-12-30 21:15:51 +00007800 // C++11 [basic.start.init]p2:
7801 // Variables with static storage duration or thread storage duration shall be
7802 // zero-initialized before any other initialization takes place.
7803 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007804 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00007805 !VD->getType()->isReferenceType()) {
7806 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00007807 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00007808 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00007809 return false;
7810 }
7811
Richard Smith7525ff62013-05-09 07:14:00 +00007812 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
7813 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00007814 EStatus.HasSideEffects)
7815 return false;
7816
7817 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
7818 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00007819}
7820
Richard Smith7b553f12011-10-29 00:50:52 +00007821/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
7822/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00007823bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00007824 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00007825 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00007826}
Anders Carlsson59689ed2008-11-22 21:04:56 +00007827
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007828APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007829 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007830 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007831 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00007832 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00007833 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00007834 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007835 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00007836
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007837 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00007838}
John McCall864e3962010-05-07 05:32:02 +00007839
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007840void Expr::EvaluateForOverflow(const ASTContext &Ctx,
7841 SmallVectorImpl<PartialDiagnosticAt> *Diags) const {
7842 bool IsConst;
7843 EvalResult EvalResult;
7844 EvalResult.Diag = Diags;
7845 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
7846 EvalInfo Info(Ctx, EvalResult, true);
7847 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
7848 }
7849}
7850
Richard Smithe6c01442013-06-05 00:46:14 +00007851bool Expr::EvalResult::isGlobalLValue() const {
7852 assert(Val.isLValue());
7853 return IsGlobalLValue(Val.getLValueBase());
7854}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00007855
7856
John McCall864e3962010-05-07 05:32:02 +00007857/// isIntegerConstantExpr - this recursive routine will test if an expression is
7858/// an integer constant expression.
7859
7860/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
7861/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00007862
7863// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00007864// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
7865// and a (possibly null) SourceLocation indicating the location of the problem.
7866//
John McCall864e3962010-05-07 05:32:02 +00007867// Note that to reduce code duplication, this helper does no evaluation
7868// itself; the caller checks whether the expression is evaluatable, and
7869// in the rare cases where CheckICE actually cares about the evaluated
7870// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00007871
Dan Gohman28ade552010-07-26 21:25:24 +00007872namespace {
7873
Richard Smith9e575da2012-12-28 13:25:52 +00007874enum ICEKind {
7875 /// This expression is an ICE.
7876 IK_ICE,
7877 /// This expression is not an ICE, but if it isn't evaluated, it's
7878 /// a legal subexpression for an ICE. This return value is used to handle
7879 /// the comma operator in C99 mode, and non-constant subexpressions.
7880 IK_ICEIfUnevaluated,
7881 /// This expression is not an ICE, and is not a legal subexpression for one.
7882 IK_NotICE
7883};
7884
John McCall864e3962010-05-07 05:32:02 +00007885struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00007886 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00007887 SourceLocation Loc;
7888
Richard Smith9e575da2012-12-28 13:25:52 +00007889 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00007890};
7891
Dan Gohman28ade552010-07-26 21:25:24 +00007892}
7893
Richard Smith9e575da2012-12-28 13:25:52 +00007894static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
7895
7896static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00007897
7898static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
7899 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00007900 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00007901 !EVResult.Val.isInt())
7902 return ICEDiag(IK_NotICE, E->getLocStart());
7903
John McCall864e3962010-05-07 05:32:02 +00007904 return NoDiag();
7905}
7906
7907static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
7908 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00007909 if (!E->getType()->isIntegralOrEnumerationType())
7910 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007911
7912 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00007913#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00007914#define STMT(Node, Base) case Expr::Node##Class:
7915#define EXPR(Node, Base)
7916#include "clang/AST/StmtNodes.inc"
7917 case Expr::PredefinedExprClass:
7918 case Expr::FloatingLiteralClass:
7919 case Expr::ImaginaryLiteralClass:
7920 case Expr::StringLiteralClass:
7921 case Expr::ArraySubscriptExprClass:
7922 case Expr::MemberExprClass:
7923 case Expr::CompoundAssignOperatorClass:
7924 case Expr::CompoundLiteralExprClass:
7925 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00007926 case Expr::DesignatedInitExprClass:
7927 case Expr::ImplicitValueInitExprClass:
7928 case Expr::ParenListExprClass:
7929 case Expr::VAArgExprClass:
7930 case Expr::AddrLabelExprClass:
7931 case Expr::StmtExprClass:
7932 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00007933 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00007934 case Expr::CXXDynamicCastExprClass:
7935 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00007936 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00007937 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00007938 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00007939 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00007940 case Expr::CXXThisExprClass:
7941 case Expr::CXXThrowExprClass:
7942 case Expr::CXXNewExprClass:
7943 case Expr::CXXDeleteExprClass:
7944 case Expr::CXXPseudoDestructorExprClass:
7945 case Expr::UnresolvedLookupExprClass:
7946 case Expr::DependentScopeDeclRefExprClass:
7947 case Expr::CXXConstructExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00007948 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00007949 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00007950 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00007951 case Expr::CXXTemporaryObjectExprClass:
7952 case Expr::CXXUnresolvedConstructExprClass:
7953 case Expr::CXXDependentScopeMemberExprClass:
7954 case Expr::UnresolvedMemberExprClass:
7955 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00007956 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007957 case Expr::ObjCArrayLiteralClass:
7958 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00007959 case Expr::ObjCEncodeExprClass:
7960 case Expr::ObjCMessageExprClass:
7961 case Expr::ObjCSelectorExprClass:
7962 case Expr::ObjCProtocolExprClass:
7963 case Expr::ObjCIvarRefExprClass:
7964 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007965 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00007966 case Expr::ObjCIsaExprClass:
7967 case Expr::ShuffleVectorExprClass:
7968 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00007969 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00007970 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00007971 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00007972 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00007973 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00007974 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00007975 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00007976 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00007977 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00007978 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00007979 case Expr::InitListExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00007980 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00007981 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00007982
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007983 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00007984 case Expr::GNUNullExprClass:
7985 // GCC considers the GNU __null value to be an integral constant expression.
7986 return NoDiag();
7987
John McCall7c454bb2011-07-15 05:09:51 +00007988 case Expr::SubstNonTypeTemplateParmExprClass:
7989 return
7990 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
7991
John McCall864e3962010-05-07 05:32:02 +00007992 case Expr::ParenExprClass:
7993 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00007994 case Expr::GenericSelectionExprClass:
7995 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007996 case Expr::IntegerLiteralClass:
7997 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007998 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00007999 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00008000 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00008001 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00008002 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00008003 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00008004 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00008005 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00008006 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00008007 return NoDiag();
8008 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00008009 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00008010 // C99 6.6/3 allows function calls within unevaluated subexpressions of
8011 // constant expressions, but they can never be ICEs because an ICE cannot
8012 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00008013 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00008014 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00008015 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008016 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008017 }
Richard Smith6365c912012-02-24 22:12:32 +00008018 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008019 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
8020 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00008021 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008022 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00008023 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00008024 // Parameter variables are never constants. Without this check,
8025 // getAnyInitializer() can find a default argument, which leads
8026 // to chaos.
8027 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00008028 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008029
8030 // C++ 7.1.5.1p2
8031 // A variable of non-volatile const-qualified integral or enumeration
8032 // type initialized by an ICE can be used in ICEs.
8033 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00008034 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00008035 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00008036
Richard Smithd0b4dd62011-12-19 06:19:21 +00008037 const VarDecl *VD;
8038 // Look for a declaration of this variable that has an initializer, and
8039 // check whether it is an ICE.
8040 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
8041 return NoDiag();
8042 else
Richard Smith9e575da2012-12-28 13:25:52 +00008043 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008044 }
8045 }
Richard Smith9e575da2012-12-28 13:25:52 +00008046 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00008047 }
John McCall864e3962010-05-07 05:32:02 +00008048 case Expr::UnaryOperatorClass: {
8049 const UnaryOperator *Exp = cast<UnaryOperator>(E);
8050 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008051 case UO_PostInc:
8052 case UO_PostDec:
8053 case UO_PreInc:
8054 case UO_PreDec:
8055 case UO_AddrOf:
8056 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00008057 // C99 6.6/3 allows increment and decrement within unevaluated
8058 // subexpressions of constant expressions, but they can never be ICEs
8059 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008060 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00008061 case UO_Extension:
8062 case UO_LNot:
8063 case UO_Plus:
8064 case UO_Minus:
8065 case UO_Not:
8066 case UO_Real:
8067 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00008068 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008069 }
Richard Smith9e575da2012-12-28 13:25:52 +00008070
John McCall864e3962010-05-07 05:32:02 +00008071 // OffsetOf falls through here.
8072 }
8073 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00008074 // Note that per C99, offsetof must be an ICE. And AFAIK, using
8075 // EvaluateAsRValue matches the proposed gcc behavior for cases like
8076 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
8077 // compliance: we should warn earlier for offsetof expressions with
8078 // array subscripts that aren't ICEs, and if the array subscripts
8079 // are ICEs, the value of the offsetof must be an integer constant.
8080 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008081 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00008082 case Expr::UnaryExprOrTypeTraitExprClass: {
8083 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
8084 if ((Exp->getKind() == UETT_SizeOf) &&
8085 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00008086 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008087 return NoDiag();
8088 }
8089 case Expr::BinaryOperatorClass: {
8090 const BinaryOperator *Exp = cast<BinaryOperator>(E);
8091 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008092 case BO_PtrMemD:
8093 case BO_PtrMemI:
8094 case BO_Assign:
8095 case BO_MulAssign:
8096 case BO_DivAssign:
8097 case BO_RemAssign:
8098 case BO_AddAssign:
8099 case BO_SubAssign:
8100 case BO_ShlAssign:
8101 case BO_ShrAssign:
8102 case BO_AndAssign:
8103 case BO_XorAssign:
8104 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00008105 // C99 6.6/3 allows assignments within unevaluated subexpressions of
8106 // constant expressions, but they can never be ICEs because an ICE cannot
8107 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008108 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008109
John McCalle3027922010-08-25 11:45:40 +00008110 case BO_Mul:
8111 case BO_Div:
8112 case BO_Rem:
8113 case BO_Add:
8114 case BO_Sub:
8115 case BO_Shl:
8116 case BO_Shr:
8117 case BO_LT:
8118 case BO_GT:
8119 case BO_LE:
8120 case BO_GE:
8121 case BO_EQ:
8122 case BO_NE:
8123 case BO_And:
8124 case BO_Xor:
8125 case BO_Or:
8126 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00008127 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8128 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00008129 if (Exp->getOpcode() == BO_Div ||
8130 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00008131 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00008132 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00008133 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00008134 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008135 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00008136 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008137 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00008138 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008139 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00008140 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008141 }
8142 }
8143 }
John McCalle3027922010-08-25 11:45:40 +00008144 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008145 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00008146 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
8147 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00008148 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
8149 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008150 } else {
8151 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00008152 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008153 }
8154 }
Richard Smith9e575da2012-12-28 13:25:52 +00008155 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008156 }
John McCalle3027922010-08-25 11:45:40 +00008157 case BO_LAnd:
8158 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00008159 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8160 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008161 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00008162 // Rare case where the RHS has a comma "side-effect"; we need
8163 // to actually check the condition to see whether the side
8164 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00008165 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00008166 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00008167 return RHSResult;
8168 return NoDiag();
8169 }
8170
Richard Smith9e575da2012-12-28 13:25:52 +00008171 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008172 }
8173 }
8174 }
8175 case Expr::ImplicitCastExprClass:
8176 case Expr::CStyleCastExprClass:
8177 case Expr::CXXFunctionalCastExprClass:
8178 case Expr::CXXStaticCastExprClass:
8179 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00008180 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00008181 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008182 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00008183 if (isa<ExplicitCastExpr>(E)) {
8184 if (const FloatingLiteral *FL
8185 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
8186 unsigned DestWidth = Ctx.getIntWidth(E->getType());
8187 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
8188 APSInt IgnoredVal(DestWidth, !DestSigned);
8189 bool Ignored;
8190 // If the value does not fit in the destination type, the behavior is
8191 // undefined, so we are not required to treat it as a constant
8192 // expression.
8193 if (FL->getValue().convertToInteger(IgnoredVal,
8194 llvm::APFloat::rmTowardZero,
8195 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00008196 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00008197 return NoDiag();
8198 }
8199 }
Eli Friedman76d4e432011-09-29 21:49:34 +00008200 switch (cast<CastExpr>(E)->getCastKind()) {
8201 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008202 case CK_AtomicToNonAtomic:
8203 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00008204 case CK_NoOp:
8205 case CK_IntegralToBoolean:
8206 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00008207 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00008208 default:
Richard Smith9e575da2012-12-28 13:25:52 +00008209 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00008210 }
John McCall864e3962010-05-07 05:32:02 +00008211 }
John McCallc07a0c72011-02-17 10:25:35 +00008212 case Expr::BinaryConditionalOperatorClass: {
8213 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
8214 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008215 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00008216 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008217 if (FalseResult.Kind == IK_NotICE) return FalseResult;
8218 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
8219 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00008220 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00008221 return FalseResult;
8222 }
John McCall864e3962010-05-07 05:32:02 +00008223 case Expr::ConditionalOperatorClass: {
8224 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
8225 // If the condition (ignoring parens) is a __builtin_constant_p call,
8226 // then only the true side is actually considered in an integer constant
8227 // expression, and it is fully evaluated. This is an important GNU
8228 // extension. See GCC PR38377 for discussion.
8229 if (const CallExpr *CallCE
8230 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00008231 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
8232 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008233 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008234 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008235 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008236
Richard Smithf57d8cb2011-12-09 22:58:01 +00008237 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
8238 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008239
Richard Smith9e575da2012-12-28 13:25:52 +00008240 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008241 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008242 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008243 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008244 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00008245 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008246 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00008247 return NoDiag();
8248 // Rare case where the diagnostics depend on which side is evaluated
8249 // Note that if we get here, CondResult is 0, and at least one of
8250 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00008251 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00008252 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00008253 return TrueResult;
8254 }
8255 case Expr::CXXDefaultArgExprClass:
8256 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00008257 case Expr::CXXDefaultInitExprClass:
8258 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008259 case Expr::ChooseExprClass: {
8260 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
8261 }
8262 }
8263
David Blaikiee4d798f2012-01-20 21:50:17 +00008264 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00008265}
8266
Richard Smithf57d8cb2011-12-09 22:58:01 +00008267/// Evaluate an expression as a C++11 integral constant expression.
8268static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
8269 const Expr *E,
8270 llvm::APSInt *Value,
8271 SourceLocation *Loc) {
8272 if (!E->getType()->isIntegralOrEnumerationType()) {
8273 if (Loc) *Loc = E->getExprLoc();
8274 return false;
8275 }
8276
Richard Smith66e05fe2012-01-18 05:21:49 +00008277 APValue Result;
8278 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00008279 return false;
8280
Richard Smith66e05fe2012-01-18 05:21:49 +00008281 assert(Result.isInt() && "pointer cast to int is not an ICE");
8282 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00008283 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008284}
8285
Richard Smith92b1ce02011-12-12 09:28:41 +00008286bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008287 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008288 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
8289
Richard Smith9e575da2012-12-28 13:25:52 +00008290 ICEDiag D = CheckICE(this, Ctx);
8291 if (D.Kind != IK_ICE) {
8292 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00008293 return false;
8294 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008295 return true;
8296}
8297
8298bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
8299 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008300 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008301 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
8302
8303 if (!isIntegerConstantExpr(Ctx, Loc))
8304 return false;
8305 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00008306 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00008307 return true;
8308}
Richard Smith66e05fe2012-01-18 05:21:49 +00008309
Richard Smith98a0a492012-02-14 21:38:30 +00008310bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00008311 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00008312}
8313
Richard Smith66e05fe2012-01-18 05:21:49 +00008314bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
8315 SourceLocation *Loc) const {
8316 // We support this checking in C++98 mode in order to diagnose compatibility
8317 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008318 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00008319
Richard Smith98a0a492012-02-14 21:38:30 +00008320 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00008321 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008322 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00008323 Status.Diag = &Diags;
8324 EvalInfo Info(Ctx, Status);
8325
8326 APValue Scratch;
8327 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
8328
8329 if (!Diags.empty()) {
8330 IsConstExpr = false;
8331 if (Loc) *Loc = Diags[0].first;
8332 } else if (!IsConstExpr) {
8333 // FIXME: This shouldn't happen.
8334 if (Loc) *Loc = getExprLoc();
8335 }
8336
8337 return IsConstExpr;
8338}
Richard Smith253c2a32012-01-27 01:14:48 +00008339
8340bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008341 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00008342 PartialDiagnosticAt> &Diags) {
8343 // FIXME: It would be useful to check constexpr function templates, but at the
8344 // moment the constant expression evaluator cannot cope with the non-rigorous
8345 // ASTs which we build for dependent expressions.
8346 if (FD->isDependentContext())
8347 return true;
8348
8349 Expr::EvalStatus Status;
8350 Status.Diag = &Diags;
8351
8352 EvalInfo Info(FD->getASTContext(), Status);
8353 Info.CheckingPotentialConstantExpression = true;
8354
8355 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8356 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
8357
Richard Smith7525ff62013-05-09 07:14:00 +00008358 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00008359 // is a temporary being used as the 'this' pointer.
8360 LValue This;
8361 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00008362 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00008363
Richard Smith253c2a32012-01-27 01:14:48 +00008364 ArrayRef<const Expr*> Args;
8365
8366 SourceLocation Loc = FD->getLocation();
8367
Richard Smith2e312c82012-03-03 22:46:17 +00008368 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00008369 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
8370 // Evaluate the call as a constant initializer, to allow the construction
8371 // of objects of non-literal types.
8372 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00008373 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00008374 } else
Richard Smith253c2a32012-01-27 01:14:48 +00008375 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
8376 Args, FD->getBody(), Info, Scratch);
8377
8378 return Diags.empty();
8379}