blob: fea78835b31d9e9f1371e89361f09b4d393ec985 [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
Richard Smith745f5142012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
Richard Smitha49a7fe2013-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 Smith745f5142012-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 Carlssonc44eec62008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Benjamin Kramera93d0f22012-12-01 17:12:56 +000038#include "clang/AST/ASTDiagnostic.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000039#include "clang/AST/CharUnits.h"
Benjamin Kramera93d0f22012-12-01 17:12:56 +000040#include "clang/AST/Expr.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000041#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000042#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000043#include "clang/AST/TypeLoc.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000044#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000045#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000046#include "llvm/ADT/SmallString.h"
Benjamin Kramera93d0f22012-12-01 17:12:56 +000047#include "llvm/Support/raw_ostream.h"
Mike Stump4572bab2009-05-30 03:56:50 +000048#include <cstring>
Richard Smith7b48a292012-02-01 05:53:12 +000049#include <functional>
Mike Stump4572bab2009-05-30 03:56:50 +000050
Anders Carlssonc44eec62008-07-03 04:20:39 +000051using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000052using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000053using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000054
Richard Smith83587db2012-02-15 02:18:13 +000055static bool IsGlobalLValue(APValue::LValueBase B);
56
John McCallf4cf1a12010-05-07 17:22:02 +000057namespace {
Richard Smith180f4792011-11-10 06:34:14 +000058 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000059 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000060 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000061
Richard Smith83587db2012-02-15 02:18:13 +000062 static QualType getType(APValue::LValueBase B) {
Richard Smith1bf9a9e2011-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 Smith8a66bf72013-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 Smith1bf9a9e2011-11-12 22:28:03 +000085 }
86
Richard Smith180f4792011-11-10 06:34:14 +000087 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smithf15fda02012-02-02 01:16:57 +000088 /// field or base class.
Richard Smith83587db2012-02-15 02:18:13 +000089 static
Richard Smithf15fda02012-02-02 01:16:57 +000090 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smith180f4792011-11-10 06:34:14 +000091 APValue::BaseOrMemberType Value;
92 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smithf15fda02012-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 Smith83587db2012-02-15 02:18:13 +000098 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000099 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-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 Smith83587db2012-02-15 02:18:13 +0000103 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +0000104 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +0000105 }
106 /// Determine whether this LValue path entry for a base class names a virtual
107 /// base class.
Richard Smith83587db2012-02-15 02:18:13 +0000108 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +0000109 return getAsBaseOrMember(E).getInt();
Richard Smith180f4792011-11-10 06:34:14 +0000110 }
111
Richard Smithb4e85ed2012-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 Smith9a17a682011-11-07 05:07:52 +0000120 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smithb4e85ed2012-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 Smith86024012012-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 Smithb4e85ed2012-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 Smith9a17a682011-11-07 05:07:52 +0000137 // Path[I] describes a base class.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000138 ArraySize = 0;
139 }
Richard Smith9a17a682011-11-07 05:07:52 +0000140 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000141 return MostDerivedLength;
Richard Smith9a17a682011-11-07 05:07:52 +0000142 }
143
Richard Smithb4e85ed2012-01-06 16:39:00 +0000144 // The order of this enum is important for diagnostics.
145 enum CheckSubobjectKind {
Richard Smithb04035a2012-02-01 02:39:43 +0000146 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith86024012012-02-18 22:04:06 +0000147 CSK_This, CSK_Real, CSK_Imag
Richard Smithb4e85ed2012-01-06 16:39:00 +0000148 };
149
Richard Smith0a3bdb62011-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 Smithb4e85ed2012-01-06 16:39:00 +0000157 /// Is this a pointer one past the end of an object?
158 bool IsOnePastTheEnd : 1;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000159
Richard Smithb4e85ed2012-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 Smith0a3bdb62011-11-04 02:25:55 +0000170
Richard Smith9a17a682011-11-07 05:07:52 +0000171 typedef APValue::LValuePathEntry PathEntry;
172
Richard Smith0a3bdb62011-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 Smithb4e85ed2012-01-06 16:39:00 +0000176 SubobjectDesignator() : Invalid(true) {}
Richard Smith0a3bdb62011-11-04 02:25:55 +0000177
Richard Smithb4e85ed2012-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 Smith9a17a682011-11-07 05:07:52 +0000185 if (!Invalid) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000186 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-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 Smithb4e85ed2012-01-06 16:39:00 +0000190 MostDerivedPathLength =
191 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
192 V.getLValuePath(), MostDerivedArraySize,
193 MostDerivedType);
Richard Smith9a17a682011-11-07 05:07:52 +0000194 }
195 }
196
Richard Smith0a3bdb62011-11-04 02:25:55 +0000197 void setInvalid() {
198 Invalid = true;
199 Entries.clear();
200 }
Richard Smithb4e85ed2012-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 Smith0a3bdb62011-11-04 02:25:55 +0000224 PathEntry Entry;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000225 Entry.ArrayIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000226 Entries.push_back(Entry);
Richard Smithb4e85ed2012-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 Smith0a3bdb62011-11-04 02:25:55 +0000232 }
233 /// Update this designator to refer to the given base or member of this
234 /// object.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000235 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000236 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000237 APValue::BaseOrMemberType Value(D, Virtual);
238 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000239 Entries.push_back(Entry);
Richard Smithb4e85ed2012-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 Smith0a3bdb62011-11-04 02:25:55 +0000247 }
Richard Smith86024012012-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 Smithb4e85ed2012-01-06 16:39:00 +0000260 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000261 /// Add N to the address of this subobject.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000262 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000263 if (Invalid) return;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000264 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith9a17a682011-11-07 05:07:52 +0000265 Entries.back().ArrayIndex += N;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000266 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
267 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
268 setInvalid();
269 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000270 return;
271 }
Richard Smithb4e85ed2012-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 Smith0a3bdb62011-11-04 02:25:55 +0000281 setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000282 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000283 }
284 };
285
Richard Smithd0dccea2011-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 Smithbd552ef2011-10-31 05:52:43 +0000291 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000292
Richard Smith08d6e032011-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 Smith83587db2012-02-15 02:18:13 +0000299 /// Index - The call index of this call.
300 unsigned Index;
301
Richard Smith180f4792011-11-10 06:34:14 +0000302 /// This - The binding for the this pointer in this call, if any.
303 const LValue *This;
304
Richard Smithd0dccea2011-10-28 22:34:42 +0000305 /// ParmBindings - Parameter bindings for this function call, indexed by
306 /// parameters' function scope indices.
Richard Smithbebf5b12013-04-26 14:36:30 +0000307 APValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000308
Eli Friedmanf6172ae2012-06-25 21:21:08 +0000309 // Note that we intentionally use std::map here so that references to
310 // values are stable.
Richard Smitha10b9782013-04-22 15:31:51 +0000311 typedef std::map<const void*, APValue> MapTy;
Richard Smithbd552ef2011-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 Smith08d6e032011-12-16 19:06:07 +0000316 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
317 const FunctionDecl *Callee, const LValue *This,
Richard Smithbebf5b12013-04-26 14:36:30 +0000318 APValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000319 ~CallStackFrame();
Richard Smith03ce5f82013-07-24 07:11:57 +0000320
321 APValue *getTemporary(const void *Key) {
322 MapTy::iterator I = Temporaries.find(Key);
323 return I == Temporaries.end() ? 0 : &I->second;
324 }
325 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smithd0dccea2011-10-28 22:34:42 +0000326 };
327
Richard Smithc3bf52c2013-04-20 22:23:05 +0000328 /// Temporarily override 'this'.
329 class ThisOverrideRAII {
330 public:
331 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
332 : Frame(Frame), OldThis(Frame.This) {
333 if (Enable)
334 Frame.This = NewThis;
335 }
336 ~ThisOverrideRAII() {
337 Frame.This = OldThis;
338 }
339 private:
340 CallStackFrame &Frame;
341 const LValue *OldThis;
342 };
343
Richard Smithdd1f29b2011-12-12 09:28:41 +0000344 /// A partial diagnostic which we might know in advance that we are not going
345 /// to emit.
346 class OptionalDiagnostic {
347 PartialDiagnostic *Diag;
348
349 public:
350 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
351
352 template<typename T>
353 OptionalDiagnostic &operator<<(const T &v) {
354 if (Diag)
355 *Diag << v;
356 return *this;
357 }
Richard Smith789f9b62012-01-31 04:08:20 +0000358
359 OptionalDiagnostic &operator<<(const APSInt &I) {
360 if (Diag) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000361 SmallVector<char, 32> Buffer;
Richard Smith789f9b62012-01-31 04:08:20 +0000362 I.toString(Buffer);
363 *Diag << StringRef(Buffer.data(), Buffer.size());
364 }
365 return *this;
366 }
367
368 OptionalDiagnostic &operator<<(const APFloat &F) {
369 if (Diag) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000370 SmallVector<char, 32> Buffer;
Richard Smith789f9b62012-01-31 04:08:20 +0000371 F.toString(Buffer);
372 *Diag << StringRef(Buffer.data(), Buffer.size());
373 }
374 return *this;
375 }
Richard Smithdd1f29b2011-12-12 09:28:41 +0000376 };
377
Richard Smith03ce5f82013-07-24 07:11:57 +0000378 /// A cleanup, and a flag indicating whether it is lifetime-extended.
379 class Cleanup {
380 llvm::PointerIntPair<APValue*, 1, bool> Value;
381
382 public:
383 Cleanup(APValue *Val, bool IsLifetimeExtended)
384 : Value(Val, IsLifetimeExtended) {}
385
386 bool isLifetimeExtended() const { return Value.getInt(); }
387 void endLifetime() {
388 *Value.getPointer() = APValue();
389 }
390 };
391
Richard Smith83587db2012-02-15 02:18:13 +0000392 /// EvalInfo - This is a private struct used by the evaluator to capture
393 /// information about a subexpression as it is folded. It retains information
394 /// about the AST context, but also maintains information about the folded
395 /// expression.
396 ///
397 /// If an expression could be evaluated, it is still possible it is not a C
398 /// "integer constant expression" or constant expression. If not, this struct
399 /// captures information about how and why not.
400 ///
401 /// One bit of information passed *into* the request for constant folding
402 /// indicates whether the subexpression is "evaluated" or not according to C
403 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
404 /// evaluate the expression regardless of what the RHS is, but C only allows
405 /// certain things in certain situations.
Richard Smithbd552ef2011-10-31 05:52:43 +0000406 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000407 ASTContext &Ctx;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +0000408
Richard Smithbd552ef2011-10-31 05:52:43 +0000409 /// EvalStatus - Contains information about the evaluation.
410 Expr::EvalStatus &EvalStatus;
411
412 /// CurrentCall - The top of the constexpr call stack.
413 CallStackFrame *CurrentCall;
414
Richard Smithbd552ef2011-10-31 05:52:43 +0000415 /// CallStackDepth - The number of calls in the call stack right now.
416 unsigned CallStackDepth;
417
Richard Smith83587db2012-02-15 02:18:13 +0000418 /// NextCallIndex - The next call index to assign.
419 unsigned NextCallIndex;
420
Richard Smithe7565632013-05-08 02:12:03 +0000421 /// StepsLeft - The remaining number of evaluation steps we're permitted
422 /// to perform. This is essentially a limit for the number of statements
423 /// we will evaluate.
424 unsigned StepsLeft;
425
Richard Smithbd552ef2011-10-31 05:52:43 +0000426 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000427 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000428 CallStackFrame BottomFrame;
429
Richard Smith03ce5f82013-07-24 07:11:57 +0000430 /// A stack of values whose lifetimes end at the end of some surrounding
431 /// evaluation frame.
432 llvm::SmallVector<Cleanup, 16> CleanupStack;
433
Richard Smith180f4792011-11-10 06:34:14 +0000434 /// EvaluatingDecl - This is the declaration whose initializer is being
435 /// evaluated, if any.
Richard Smith6391ea22013-05-09 07:14:00 +0000436 APValue::LValueBase EvaluatingDecl;
Richard Smith180f4792011-11-10 06:34:14 +0000437
438 /// EvaluatingDeclValue - This is the value being constructed for the
439 /// declaration whose initializer is being evaluated, if any.
440 APValue *EvaluatingDeclValue;
441
Richard Smithc1c5f272011-12-13 06:39:58 +0000442 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
443 /// notes attached to it will also be stored, otherwise they will not be.
444 bool HasActiveDiagnostic;
445
Richard Smith745f5142012-01-27 01:14:48 +0000446 /// CheckingPotentialConstantExpression - Are we checking whether the
447 /// expression is a potential constant expression? If so, some diagnostics
448 /// are suppressed.
449 bool CheckingPotentialConstantExpression;
Richard Smith03ce5f82013-07-24 07:11:57 +0000450
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000451 bool IntOverflowCheckMode;
Richard Smith745f5142012-01-27 01:14:48 +0000452
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000453 EvalInfo(const ASTContext &C, Expr::EvalStatus &S,
Richard Smithe7565632013-05-08 02:12:03 +0000454 bool OverflowCheckMode = false)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000455 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith83587db2012-02-15 02:18:13 +0000456 CallStackDepth(0), NextCallIndex(1),
Richard Smithe7565632013-05-08 02:12:03 +0000457 StepsLeft(getLangOpts().ConstexprStepLimit),
Richard Smith83587db2012-02-15 02:18:13 +0000458 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith6391ea22013-05-09 07:14:00 +0000459 EvaluatingDecl((const ValueDecl*)0), EvaluatingDeclValue(0),
460 HasActiveDiagnostic(false), CheckingPotentialConstantExpression(false),
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000461 IntOverflowCheckMode(OverflowCheckMode) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000462
Richard Smith6391ea22013-05-09 07:14:00 +0000463 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
464 EvaluatingDecl = Base;
Richard Smith180f4792011-11-10 06:34:14 +0000465 EvaluatingDeclValue = &Value;
466 }
467
David Blaikie4e4d0842012-03-11 07:00:24 +0000468 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smithc18c4232011-11-21 19:36:32 +0000469
Richard Smithc1c5f272011-12-13 06:39:58 +0000470 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000471 // Don't perform any constexpr calls (other than the call we're checking)
472 // when checking a potential constant expression.
473 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
474 return false;
Richard Smith83587db2012-02-15 02:18:13 +0000475 if (NextCallIndex == 0) {
476 // NextCallIndex has wrapped around.
477 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
478 return false;
479 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000480 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
481 return true;
482 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
483 << getLangOpts().ConstexprCallDepth;
484 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000485 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000486
Richard Smith83587db2012-02-15 02:18:13 +0000487 CallStackFrame *getCallFrame(unsigned CallIndex) {
488 assert(CallIndex && "no call index in getCallFrame");
489 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
490 // be null in this loop.
491 CallStackFrame *Frame = CurrentCall;
492 while (Frame->Index > CallIndex)
493 Frame = Frame->Caller;
494 return (Frame->Index == CallIndex) ? Frame : 0;
495 }
496
Richard Smithe7565632013-05-08 02:12:03 +0000497 bool nextStep(const Stmt *S) {
498 if (!StepsLeft) {
499 Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
500 return false;
501 }
502 --StepsLeft;
503 return true;
504 }
505
Richard Smithc1c5f272011-12-13 06:39:58 +0000506 private:
507 /// Add a diagnostic to the diagnostics list.
508 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
509 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
510 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
511 return EvalStatus.Diag->back().second;
512 }
513
Richard Smith08d6e032011-12-16 19:06:07 +0000514 /// Add notes containing a call stack to the current point of evaluation.
515 void addCallStack(unsigned Limit);
516
Richard Smithc1c5f272011-12-13 06:39:58 +0000517 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000518 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000519 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
520 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000521 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000522 // If we have a prior diagnostic, it will be noting that the expression
523 // isn't a constant expression. This diagnostic is more important.
524 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000525 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000526 unsigned CallStackNotes = CallStackDepth - 1;
527 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
528 if (Limit)
529 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000530 if (CheckingPotentialConstantExpression)
531 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000532
Richard Smithc1c5f272011-12-13 06:39:58 +0000533 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000534 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000535 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
536 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000537 if (!CheckingPotentialConstantExpression)
538 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000539 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000540 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000541 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000542 return OptionalDiagnostic();
543 }
544
Richard Smith5cfc7d82012-03-15 04:53:45 +0000545 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
546 = diag::note_invalid_subexpr_in_const_expr,
547 unsigned ExtraNotes = 0) {
548 if (EvalStatus.Diag)
549 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
550 HasActiveDiagnostic = false;
551 return OptionalDiagnostic();
552 }
553
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000554 bool getIntOverflowCheckMode() { return IntOverflowCheckMode; }
555
Richard Smithdd1f29b2011-12-12 09:28:41 +0000556 /// Diagnose that the evaluation does not produce a C++11 core constant
557 /// expression.
Richard Smith5cfc7d82012-03-15 04:53:45 +0000558 template<typename LocArg>
559 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smith7098cbd2011-12-21 05:04:46 +0000560 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000561 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000562 // Don't override a previous diagnostic.
Eli Friedman51e47df2012-02-21 22:41:33 +0000563 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
564 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000565 return OptionalDiagnostic();
Eli Friedman51e47df2012-02-21 22:41:33 +0000566 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000567 return Diag(Loc, DiagId, ExtraNotes);
568 }
569
570 /// Add a note to a prior diagnostic.
571 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
572 if (!HasActiveDiagnostic)
573 return OptionalDiagnostic();
574 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000575 }
Richard Smith099e7f62011-12-19 06:19:21 +0000576
577 /// Add a stack of notes to a prior diagnostic.
578 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
579 if (HasActiveDiagnostic) {
580 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
581 Diags.begin(), Diags.end());
582 }
583 }
Richard Smith745f5142012-01-27 01:14:48 +0000584
585 /// Should we continue evaluation as much as possible after encountering a
586 /// construct which can't be folded?
587 bool keepEvaluatingAfterFailure() {
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000588 // Should return true in IntOverflowCheckMode, so that we check for
589 // overflow even if some subexpressions can't be evaluated as constants.
Richard Smithe7565632013-05-08 02:12:03 +0000590 return StepsLeft && (IntOverflowCheckMode ||
591 (CheckingPotentialConstantExpression &&
592 EvalStatus.Diag && EvalStatus.Diag->empty()));
Richard Smith745f5142012-01-27 01:14:48 +0000593 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000594 };
Richard Smithf15fda02012-02-02 01:16:57 +0000595
596 /// Object used to treat all foldable expressions as constant expressions.
597 struct FoldConstant {
598 bool Enabled;
599
600 explicit FoldConstant(EvalInfo &Info)
601 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
602 !Info.EvalStatus.HasSideEffects) {
603 }
604 // Treat the value we've computed since this object was created as constant.
605 void Fold(EvalInfo &Info) {
606 if (Enabled && !Info.EvalStatus.Diag->empty() &&
607 !Info.EvalStatus.HasSideEffects)
608 Info.EvalStatus.Diag->clear();
609 }
610 };
Richard Smith74e1ad92012-02-16 02:46:34 +0000611
612 /// RAII object used to suppress diagnostics and side-effects from a
613 /// speculative evaluation.
614 class SpeculativeEvaluationRAII {
615 EvalInfo &Info;
616 Expr::EvalStatus Old;
617
618 public:
619 SpeculativeEvaluationRAII(EvalInfo &Info,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000620 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = 0)
Richard Smith74e1ad92012-02-16 02:46:34 +0000621 : Info(Info), Old(Info.EvalStatus) {
622 Info.EvalStatus.Diag = NewDiag;
623 }
624 ~SpeculativeEvaluationRAII() {
625 Info.EvalStatus = Old;
626 }
627 };
Richard Smith03ce5f82013-07-24 07:11:57 +0000628
629 /// RAII object wrapping a full-expression or block scope, and handling
630 /// the ending of the lifetime of temporaries created within it.
631 template<bool IsFullExpression>
632 class ScopeRAII {
633 EvalInfo &Info;
634 unsigned OldStackSize;
635 public:
636 ScopeRAII(EvalInfo &Info)
637 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
638 ~ScopeRAII() {
639 // Body moved to a static method to encourage the compiler to inline away
640 // instances of this class.
641 cleanup(Info, OldStackSize);
642 }
643 private:
644 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
645 unsigned NewEnd = OldStackSize;
646 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
647 I != N; ++I) {
648 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
649 // Full-expression cleanup of a lifetime-extended temporary: nothing
650 // to do, just move this cleanup to the right place in the stack.
651 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
652 ++NewEnd;
653 } else {
654 // End the lifetime of the object.
655 Info.CleanupStack[I].endLifetime();
656 }
657 }
658 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
659 Info.CleanupStack.end());
660 }
661 };
662 typedef ScopeRAII<false> BlockScopeRAII;
663 typedef ScopeRAII<true> FullExpressionRAII;
Richard Smith08d6e032011-12-16 19:06:07 +0000664}
Richard Smithbd552ef2011-10-31 05:52:43 +0000665
Richard Smithb4e85ed2012-01-06 16:39:00 +0000666bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
667 CheckSubobjectKind CSK) {
668 if (Invalid)
669 return false;
670 if (isOnePastTheEnd()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000671 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000672 << CSK;
673 setInvalid();
674 return false;
675 }
676 return true;
677}
678
679void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
680 const Expr *E, uint64_t N) {
681 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smith5cfc7d82012-03-15 04:53:45 +0000682 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000683 << static_cast<int>(N) << /*array*/ 0
684 << static_cast<unsigned>(MostDerivedArraySize);
685 else
Richard Smith5cfc7d82012-03-15 04:53:45 +0000686 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000687 << static_cast<int>(N) << /*non-array*/ 1;
688 setInvalid();
689}
690
Richard Smith08d6e032011-12-16 19:06:07 +0000691CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
692 const FunctionDecl *Callee, const LValue *This,
Richard Smithbebf5b12013-04-26 14:36:30 +0000693 APValue *Arguments)
Richard Smith08d6e032011-12-16 19:06:07 +0000694 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smith83587db2012-02-15 02:18:13 +0000695 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smith08d6e032011-12-16 19:06:07 +0000696 Info.CurrentCall = this;
697 ++Info.CallStackDepth;
698}
699
700CallStackFrame::~CallStackFrame() {
701 assert(Info.CurrentCall == this && "calls retired out of order");
702 --Info.CallStackDepth;
703 Info.CurrentCall = Caller;
704}
705
Richard Smith03ce5f82013-07-24 07:11:57 +0000706APValue &CallStackFrame::createTemporary(const void *Key,
707 bool IsLifetimeExtended) {
708 APValue &Result = Temporaries[Key];
709 assert(Result.isUninit() && "temporary created multiple times");
710 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
711 return Result;
712}
713
Richard Smith8a66bf72013-06-03 05:03:02 +0000714static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smith08d6e032011-12-16 19:06:07 +0000715
716void EvalInfo::addCallStack(unsigned Limit) {
717 // Determine which calls to skip, if any.
718 unsigned ActiveCalls = CallStackDepth - 1;
719 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
720 if (Limit && Limit < ActiveCalls) {
721 SkipStart = Limit / 2 + Limit % 2;
722 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000723 }
724
Richard Smith08d6e032011-12-16 19:06:07 +0000725 // Walk the call stack and add the diagnostics.
726 unsigned CallIdx = 0;
727 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
728 Frame = Frame->Caller, ++CallIdx) {
729 // Skip this call?
730 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
731 if (CallIdx == SkipStart) {
732 // Note that we're skipping calls.
733 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
734 << unsigned(ActiveCalls - Limit);
735 }
736 continue;
737 }
738
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000739 SmallVector<char, 128> Buffer;
Richard Smith08d6e032011-12-16 19:06:07 +0000740 llvm::raw_svector_ostream Out(Buffer);
741 describeCall(Frame, Out);
742 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
743 }
744}
745
746namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000747 struct ComplexValue {
748 private:
749 bool IsInt;
750
751 public:
752 APSInt IntReal, IntImag;
753 APFloat FloatReal, FloatImag;
754
755 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
756
757 void makeComplexFloat() { IsInt = false; }
758 bool isComplexFloat() const { return !IsInt; }
759 APFloat &getComplexFloatReal() { return FloatReal; }
760 APFloat &getComplexFloatImag() { return FloatImag; }
761
762 void makeComplexInt() { IsInt = true; }
763 bool isComplexInt() const { return IsInt; }
764 APSInt &getComplexIntReal() { return IntReal; }
765 APSInt &getComplexIntImag() { return IntImag; }
766
Richard Smith1aa0be82012-03-03 22:46:17 +0000767 void moveInto(APValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000768 if (isComplexFloat())
Richard Smith1aa0be82012-03-03 22:46:17 +0000769 v = APValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000770 else
Richard Smith1aa0be82012-03-03 22:46:17 +0000771 v = APValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000772 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000773 void setFrom(const APValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000774 assert(v.isComplexFloat() || v.isComplexInt());
775 if (v.isComplexFloat()) {
776 makeComplexFloat();
777 FloatReal = v.getComplexFloatReal();
778 FloatImag = v.getComplexFloatImag();
779 } else {
780 makeComplexInt();
781 IntReal = v.getComplexIntReal();
782 IntImag = v.getComplexIntImag();
783 }
784 }
John McCallf4cf1a12010-05-07 17:22:02 +0000785 };
John McCallefdb83e2010-05-07 21:00:08 +0000786
787 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000788 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000789 CharUnits Offset;
Richard Smith83587db2012-02-15 02:18:13 +0000790 unsigned CallIndex;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000791 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000792
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000793 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000794 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000795 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith83587db2012-02-15 02:18:13 +0000796 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000797 SubobjectDesignator &getLValueDesignator() { return Designator; }
798 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000799
Richard Smith1aa0be82012-03-03 22:46:17 +0000800 void moveInto(APValue &V) const {
801 if (Designator.Invalid)
802 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
803 else
804 V = APValue(Base, Offset, Designator.Entries,
805 Designator.IsOnePastTheEnd, CallIndex);
John McCallefdb83e2010-05-07 21:00:08 +0000806 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000807 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith47a1eed2011-10-29 20:57:55 +0000808 assert(V.isLValue());
809 Base = V.getLValueBase();
810 Offset = V.getLValueOffset();
Richard Smith83587db2012-02-15 02:18:13 +0000811 CallIndex = V.getLValueCallIndex();
Richard Smith1aa0be82012-03-03 22:46:17 +0000812 Designator = SubobjectDesignator(Ctx, V);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000813 }
814
Richard Smith83587db2012-02-15 02:18:13 +0000815 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000816 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000817 Offset = CharUnits::Zero();
Richard Smith83587db2012-02-15 02:18:13 +0000818 CallIndex = I;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000819 Designator = SubobjectDesignator(getType(B));
820 }
821
822 // Check that this LValue is not based on a null pointer. If it is, produce
823 // a diagnostic and mark the designator as invalid.
824 bool checkNullPointer(EvalInfo &Info, const Expr *E,
825 CheckSubobjectKind CSK) {
826 if (Designator.Invalid)
827 return false;
828 if (!Base) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000829 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000830 << CSK;
831 Designator.setInvalid();
832 return false;
833 }
834 return true;
835 }
836
837 // Check this LValue refers to an object. If not, set the designator to be
838 // invalid and emit a diagnostic.
839 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000840 // Outside C++11, do not build a designator referring to a subobject of
841 // any object: we won't use such a designator for anything.
Richard Smith80ad52f2013-01-02 11:42:31 +0000842 if (!Info.getLangOpts().CPlusPlus11)
Richard Smith5cfc7d82012-03-15 04:53:45 +0000843 Designator.setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000844 return checkNullPointer(Info, E, CSK) &&
845 Designator.checkSubobject(Info, E, CSK);
846 }
847
848 void addDecl(EvalInfo &Info, const Expr *E,
849 const Decl *D, bool Virtual = false) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000850 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
851 Designator.addDeclUnchecked(D, Virtual);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000852 }
853 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000854 if (checkSubobject(Info, E, CSK_ArrayToPointer))
855 Designator.addArrayUnchecked(CAT);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000856 }
Richard Smith86024012012-02-18 22:04:06 +0000857 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000858 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
859 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith86024012012-02-18 22:04:06 +0000860 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000861 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000862 if (checkNullPointer(Info, E, CSK_ArrayIndex))
863 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000864 }
John McCallefdb83e2010-05-07 21:00:08 +0000865 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000866
867 struct MemberPtr {
868 MemberPtr() {}
869 explicit MemberPtr(const ValueDecl *Decl) :
870 DeclAndIsDerivedMember(Decl, false), Path() {}
871
872 /// The member or (direct or indirect) field referred to by this member
873 /// pointer, or 0 if this is a null member pointer.
874 const ValueDecl *getDecl() const {
875 return DeclAndIsDerivedMember.getPointer();
876 }
877 /// Is this actually a member of some type derived from the relevant class?
878 bool isDerivedMember() const {
879 return DeclAndIsDerivedMember.getInt();
880 }
881 /// Get the class which the declaration actually lives in.
882 const CXXRecordDecl *getContainingRecord() const {
883 return cast<CXXRecordDecl>(
884 DeclAndIsDerivedMember.getPointer()->getDeclContext());
885 }
886
Richard Smith1aa0be82012-03-03 22:46:17 +0000887 void moveInto(APValue &V) const {
888 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000889 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000890 void setFrom(const APValue &V) {
Richard Smithe24f5fc2011-11-17 22:56:20 +0000891 assert(V.isMemberPointer());
892 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
893 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
894 Path.clear();
895 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
896 Path.insert(Path.end(), P.begin(), P.end());
897 }
898
899 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
900 /// whether the member is a member of some class derived from the class type
901 /// of the member pointer.
902 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
903 /// Path - The path of base/derived classes from the member declaration's
904 /// class (exclusive) to the class type of the member pointer (inclusive).
905 SmallVector<const CXXRecordDecl*, 4> Path;
906
907 /// Perform a cast towards the class of the Decl (either up or down the
908 /// hierarchy).
909 bool castBack(const CXXRecordDecl *Class) {
910 assert(!Path.empty());
911 const CXXRecordDecl *Expected;
912 if (Path.size() >= 2)
913 Expected = Path[Path.size() - 2];
914 else
915 Expected = getContainingRecord();
916 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
917 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
918 // if B does not contain the original member and is not a base or
919 // derived class of the class containing the original member, the result
920 // of the cast is undefined.
921 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
922 // (D::*). We consider that to be a language defect.
923 return false;
924 }
925 Path.pop_back();
926 return true;
927 }
928 /// Perform a base-to-derived member pointer cast.
929 bool castToDerived(const CXXRecordDecl *Derived) {
930 if (!getDecl())
931 return true;
932 if (!isDerivedMember()) {
933 Path.push_back(Derived);
934 return true;
935 }
936 if (!castBack(Derived))
937 return false;
938 if (Path.empty())
939 DeclAndIsDerivedMember.setInt(false);
940 return true;
941 }
942 /// Perform a derived-to-base member pointer cast.
943 bool castToBase(const CXXRecordDecl *Base) {
944 if (!getDecl())
945 return true;
946 if (Path.empty())
947 DeclAndIsDerivedMember.setInt(true);
948 if (isDerivedMember()) {
949 Path.push_back(Base);
950 return true;
951 }
952 return castBack(Base);
953 }
954 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000955
Richard Smithb02e4622012-02-01 01:42:44 +0000956 /// Compare two member pointers, which are assumed to be of the same type.
957 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
958 if (!LHS.getDecl() || !RHS.getDecl())
959 return !LHS.getDecl() && !RHS.getDecl();
960 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
961 return false;
962 return LHS.Path == RHS.Path;
963 }
John McCallf4cf1a12010-05-07 17:22:02 +0000964}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000965
Richard Smith1aa0be82012-03-03 22:46:17 +0000966static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith83587db2012-02-15 02:18:13 +0000967static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
968 const LValue &This, const Expr *E,
Richard Smith83587db2012-02-15 02:18:13 +0000969 bool AllowNonLiteralTypes = false);
John McCallefdb83e2010-05-07 21:00:08 +0000970static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
971static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000972static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
973 EvalInfo &Info);
974static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000975static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith1aa0be82012-03-03 22:46:17 +0000976static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000977 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000978static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000979static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith5705f212013-05-23 00:30:41 +0000980static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000981
982//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000983// Misc utilities
984//===----------------------------------------------------------------------===//
985
Richard Smith8a66bf72013-06-03 05:03:02 +0000986/// Produce a string describing the given constexpr call.
987static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
988 unsigned ArgIndex = 0;
989 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
990 !isa<CXXConstructorDecl>(Frame->Callee) &&
991 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
992
993 if (!IsMemberCall)
994 Out << *Frame->Callee << '(';
995
996 if (Frame->This && IsMemberCall) {
997 APValue Val;
998 Frame->This->moveInto(Val);
999 Val.printPretty(Out, Frame->Info.Ctx,
1000 Frame->This->Designator.MostDerivedType);
1001 // FIXME: Add parens around Val if needed.
1002 Out << "->" << *Frame->Callee << '(';
1003 IsMemberCall = false;
1004 }
1005
1006 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1007 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1008 if (ArgIndex > (unsigned)IsMemberCall)
1009 Out << ", ";
1010
1011 const ParmVarDecl *Param = *I;
1012 const APValue &Arg = Frame->Arguments[ArgIndex];
1013 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1014
1015 if (ArgIndex == 0 && IsMemberCall)
1016 Out << "->" << *Frame->Callee << '(';
1017 }
1018
1019 Out << ')';
1020}
1021
Richard Smitha10b9782013-04-22 15:31:51 +00001022/// Evaluate an expression to see if it had side-effects, and discard its
1023/// result.
Richard Smithce617152013-05-06 05:56:11 +00001024/// \return \c true if the caller should keep evaluating.
1025static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smitha10b9782013-04-22 15:31:51 +00001026 APValue Scratch;
Richard Smithce617152013-05-06 05:56:11 +00001027 if (!Evaluate(Scratch, Info, E)) {
Richard Smitha10b9782013-04-22 15:31:51 +00001028 Info.EvalStatus.HasSideEffects = true;
Richard Smithce617152013-05-06 05:56:11 +00001029 return Info.keepEvaluatingAfterFailure();
1030 }
1031 return true;
Richard Smitha10b9782013-04-22 15:31:51 +00001032}
1033
Richard Smitha49a7fe2013-05-07 23:34:45 +00001034/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1035/// return its existing value.
1036static int64_t getExtValue(const APSInt &Value) {
1037 return Value.isSigned() ? Value.getSExtValue()
1038 : static_cast<int64_t>(Value.getZExtValue());
1039}
1040
Richard Smith180f4792011-11-10 06:34:14 +00001041/// Should this call expression be treated as a string literal?
1042static bool IsStringLiteralCall(const CallExpr *E) {
1043 unsigned Builtin = E->isBuiltinCall();
1044 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1045 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1046}
1047
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001048static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +00001049 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1050 // constant expression of pointer type that evaluates to...
1051
1052 // ... a null pointer value, or a prvalue core constant expression of type
1053 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001054 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +00001055
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001056 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1057 // ... the address of an object with static storage duration,
1058 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1059 return VD->hasGlobalStorage();
1060 // ... the address of a function,
1061 return isa<FunctionDecl>(D);
1062 }
1063
1064 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +00001065 switch (E->getStmtClass()) {
1066 default:
1067 return false;
Richard Smithb78ae972012-02-18 04:58:18 +00001068 case Expr::CompoundLiteralExprClass: {
1069 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1070 return CLE->isFileScope() && CLE->isLValue();
1071 }
Richard Smith211c8dd2013-06-05 00:46:14 +00001072 case Expr::MaterializeTemporaryExprClass:
1073 // A materialized temporary might have been lifetime-extended to static
1074 // storage duration.
1075 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smith180f4792011-11-10 06:34:14 +00001076 // A string literal has static storage duration.
1077 case Expr::StringLiteralClass:
1078 case Expr::PredefinedExprClass:
1079 case Expr::ObjCStringLiteralClass:
1080 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +00001081 case Expr::CXXTypeidExprClass:
Francois Pichete275a182012-04-16 04:08:35 +00001082 case Expr::CXXUuidofExprClass:
Richard Smith180f4792011-11-10 06:34:14 +00001083 return true;
1084 case Expr::CallExprClass:
1085 return IsStringLiteralCall(cast<CallExpr>(E));
1086 // For GCC compatibility, &&label has static storage duration.
1087 case Expr::AddrLabelExprClass:
1088 return true;
1089 // A Block literal expression may be used as the initialization value for
1090 // Block variables at global or local static scope.
1091 case Expr::BlockExprClass:
1092 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +00001093 case Expr::ImplicitValueInitExprClass:
1094 // FIXME:
1095 // We can never form an lvalue with an implicit value initialization as its
1096 // base through expression evaluation, so these only appear in one case: the
1097 // implicit variable declaration we invent when checking whether a constexpr
1098 // constructor can produce a constant expression. We must assume that such
1099 // an expression might be a global lvalue.
1100 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001101 }
John McCall42c8f872010-05-10 23:27:23 +00001102}
1103
Richard Smith83587db2012-02-15 02:18:13 +00001104static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1105 assert(Base && "no location for a null lvalue");
1106 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1107 if (VD)
1108 Info.Note(VD->getLocation(), diag::note_declared_at);
1109 else
Ted Kremenek890f0f12012-08-23 20:46:57 +00001110 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smith83587db2012-02-15 02:18:13 +00001111 diag::note_constexpr_temporary_here);
1112}
1113
Richard Smith9a17a682011-11-07 05:07:52 +00001114/// Check that this reference or pointer core constant expression is a valid
Richard Smith1aa0be82012-03-03 22:46:17 +00001115/// value for an address or reference constant expression. Return true if we
1116/// can fold this expression, whether or not it's a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +00001117static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1118 QualType Type, const LValue &LVal) {
1119 bool IsReferenceType = Type->isReferenceType();
1120
Richard Smithc1c5f272011-12-13 06:39:58 +00001121 APValue::LValueBase Base = LVal.getLValueBase();
1122 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1123
Richard Smithb78ae972012-02-18 04:58:18 +00001124 // Check that the object is a global. Note that the fake 'this' object we
1125 // manufacture when checking potential constant expressions is conservatively
1126 // assumed to be global here.
Richard Smithc1c5f272011-12-13 06:39:58 +00001127 if (!IsGlobalLValue(Base)) {
Richard Smith80ad52f2013-01-02 11:42:31 +00001128 if (Info.getLangOpts().CPlusPlus11) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001129 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001130 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1131 << IsReferenceType << !Designator.Entries.empty()
1132 << !!VD << VD;
1133 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001134 } else {
Richard Smith83587db2012-02-15 02:18:13 +00001135 Info.Diag(Loc);
Richard Smithc1c5f272011-12-13 06:39:58 +00001136 }
Richard Smith61e61622012-01-12 06:08:57 +00001137 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +00001138 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001139 }
Richard Smith83587db2012-02-15 02:18:13 +00001140 assert((Info.CheckingPotentialConstantExpression ||
1141 LVal.getLValueCallIndex() == 0) &&
1142 "have call index for global lvalue");
Richard Smithb4e85ed2012-01-06 16:39:00 +00001143
Hans Wennborg48def652012-08-29 18:27:29 +00001144 // Check if this is a thread-local variable.
1145 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1146 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
Richard Smith38afbc72013-04-13 02:43:54 +00001147 if (Var->getTLSKind())
Hans Wennborg48def652012-08-29 18:27:29 +00001148 return false;
1149 }
1150 }
1151
Richard Smithb4e85ed2012-01-06 16:39:00 +00001152 // Allow address constant expressions to be past-the-end pointers. This is
1153 // an extension: the standard requires them to point to an object.
1154 if (!IsReferenceType)
1155 return true;
1156
1157 // A reference constant expression must refer to an object.
1158 if (!Base) {
1159 // FIXME: diagnostic
Richard Smith83587db2012-02-15 02:18:13 +00001160 Info.CCEDiag(Loc);
Richard Smith61e61622012-01-12 06:08:57 +00001161 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001162 }
1163
Richard Smithc1c5f272011-12-13 06:39:58 +00001164 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +00001165 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001166 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001167 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smithc1c5f272011-12-13 06:39:58 +00001168 << !Designator.Entries.empty() << !!VD << VD;
Richard Smith83587db2012-02-15 02:18:13 +00001169 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001170 }
1171
Richard Smith9a17a682011-11-07 05:07:52 +00001172 return true;
1173}
1174
Richard Smith51201882011-12-30 21:15:51 +00001175/// Check that this core constant expression is of literal type, and if not,
1176/// produce an appropriate diagnostic.
Richard Smith6391ea22013-05-09 07:14:00 +00001177static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1178 const LValue *This = 0) {
Richard Smitha10b9782013-04-22 15:31:51 +00001179 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smith51201882011-12-30 21:15:51 +00001180 return true;
1181
Richard Smith6391ea22013-05-09 07:14:00 +00001182 // C++1y: A constant initializer for an object o [...] may also invoke
1183 // constexpr constructors for o and its subobjects even if those objects
1184 // are of non-literal class types.
1185 if (Info.getLangOpts().CPlusPlus1y && This &&
Richard Smithc45c8dd2013-05-16 05:04:51 +00001186 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith6391ea22013-05-09 07:14:00 +00001187 return true;
1188
Richard Smith51201882011-12-30 21:15:51 +00001189 // Prvalue constant expressions must be of literal types.
Richard Smith80ad52f2013-01-02 11:42:31 +00001190 if (Info.getLangOpts().CPlusPlus11)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001191 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smith51201882011-12-30 21:15:51 +00001192 << E->getType();
1193 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001194 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith51201882011-12-30 21:15:51 +00001195 return false;
1196}
1197
Richard Smith47a1eed2011-10-29 20:57:55 +00001198/// Check that this core constant expression value is a valid value for a
Richard Smith83587db2012-02-15 02:18:13 +00001199/// constant expression. If not, report an appropriate diagnostic. Does not
1200/// check that the expression is of literal type.
1201static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1202 QualType Type, const APValue &Value) {
Richard Smith3ed4d1c2013-06-18 17:51:51 +00001203 if (Value.isUninit()) {
Richard Smith37a84f62013-06-20 03:00:05 +00001204 Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1205 << true << Type;
Richard Smith3ed4d1c2013-06-18 17:51:51 +00001206 return false;
1207 }
1208
Richard Smith83587db2012-02-15 02:18:13 +00001209 // Core issue 1454: For a literal constant expression of array or class type,
1210 // each subobject of its value shall have been initialized by a constant
1211 // expression.
1212 if (Value.isArray()) {
1213 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1214 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1215 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1216 Value.getArrayInitializedElt(I)))
1217 return false;
1218 }
1219 if (!Value.hasArrayFiller())
1220 return true;
1221 return CheckConstantExpression(Info, DiagLoc, EltTy,
1222 Value.getArrayFiller());
Richard Smith9a17a682011-11-07 05:07:52 +00001223 }
Richard Smith83587db2012-02-15 02:18:13 +00001224 if (Value.isUnion() && Value.getUnionField()) {
1225 return CheckConstantExpression(Info, DiagLoc,
1226 Value.getUnionField()->getType(),
1227 Value.getUnionValue());
1228 }
1229 if (Value.isStruct()) {
1230 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1231 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1232 unsigned BaseIndex = 0;
1233 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1234 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1235 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1236 Value.getStructBase(BaseIndex)))
1237 return false;
1238 }
1239 }
1240 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1241 I != E; ++I) {
David Blaikie262bc182012-04-30 02:36:29 +00001242 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1243 Value.getStructField(I->getFieldIndex())))
Richard Smith83587db2012-02-15 02:18:13 +00001244 return false;
1245 }
1246 }
1247
1248 if (Value.isLValue()) {
Richard Smith83587db2012-02-15 02:18:13 +00001249 LValue LVal;
Richard Smith1aa0be82012-03-03 22:46:17 +00001250 LVal.setFrom(Info.Ctx, Value);
Richard Smith83587db2012-02-15 02:18:13 +00001251 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1252 }
1253
1254 // Everything else is fine.
1255 return true;
Richard Smith47a1eed2011-10-29 20:57:55 +00001256}
1257
Richard Smith9e36b532011-10-31 05:11:32 +00001258const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001259 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001260}
1261
1262static bool IsLiteralLValue(const LValue &Value) {
Richard Smith211c8dd2013-06-05 00:46:14 +00001263 if (Value.CallIndex)
1264 return false;
1265 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1266 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith9e36b532011-10-31 05:11:32 +00001267}
1268
Richard Smith65ac5982011-11-01 21:06:14 +00001269static bool IsWeakLValue(const LValue &Value) {
1270 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001271 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001272}
1273
Richard Smith1aa0be82012-03-03 22:46:17 +00001274static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001275 // A null base expression indicates a null pointer. These are always
1276 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001277 if (!Value.getLValueBase()) {
1278 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001279 return true;
1280 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001281
Richard Smithe24f5fc2011-11-17 22:56:20 +00001282 // We have a non-null base. These are generally known to be true, but if it's
1283 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001284 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001285 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001286 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001287}
1288
Richard Smith1aa0be82012-03-03 22:46:17 +00001289static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001290 switch (Val.getKind()) {
1291 case APValue::Uninitialized:
1292 return false;
1293 case APValue::Int:
1294 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001295 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001296 case APValue::Float:
1297 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001298 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001299 case APValue::ComplexInt:
1300 Result = Val.getComplexIntReal().getBoolValue() ||
1301 Val.getComplexIntImag().getBoolValue();
1302 return true;
1303 case APValue::ComplexFloat:
1304 Result = !Val.getComplexFloatReal().isZero() ||
1305 !Val.getComplexFloatImag().isZero();
1306 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001307 case APValue::LValue:
1308 return EvalPointerValueAsBool(Val, Result);
1309 case APValue::MemberPointer:
1310 Result = Val.getMemberPointerDecl();
1311 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001312 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001313 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001314 case APValue::Struct:
1315 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001316 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001317 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001318 }
1319
Richard Smithc49bd112011-10-28 17:51:58 +00001320 llvm_unreachable("unknown APValue kind");
1321}
1322
1323static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1324 EvalInfo &Info) {
1325 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith1aa0be82012-03-03 22:46:17 +00001326 APValue Val;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001327 if (!Evaluate(Val, Info, E))
Richard Smithc49bd112011-10-28 17:51:58 +00001328 return false;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001329 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001330}
1331
Richard Smithc1c5f272011-12-13 06:39:58 +00001332template<typename T>
Eli Friedman26dc97c2012-07-17 21:03:05 +00001333static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +00001334 const T &SrcValue, QualType DestType) {
Eli Friedman26dc97c2012-07-17 21:03:05 +00001335 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001336 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001337}
1338
1339static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1340 QualType SrcType, const APFloat &Value,
1341 QualType DestType, APSInt &Result) {
1342 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001343 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001344 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001345
Richard Smithc1c5f272011-12-13 06:39:58 +00001346 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001347 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001348 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1349 & APFloat::opInvalidOp)
Eli Friedman26dc97c2012-07-17 21:03:05 +00001350 HandleOverflow(Info, E, Value, DestType);
Richard Smithc1c5f272011-12-13 06:39:58 +00001351 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001352}
1353
Richard Smithc1c5f272011-12-13 06:39:58 +00001354static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1355 QualType SrcType, QualType DestType,
1356 APFloat &Result) {
1357 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001358 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001359 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1360 APFloat::rmNearestTiesToEven, &ignored)
1361 & APFloat::opOverflow)
Eli Friedman26dc97c2012-07-17 21:03:05 +00001362 HandleOverflow(Info, E, Value, DestType);
Richard Smithc1c5f272011-12-13 06:39:58 +00001363 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001364}
1365
Richard Smithf72fccf2012-01-30 22:27:01 +00001366static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1367 QualType DestType, QualType SrcType,
1368 APSInt &Value) {
1369 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001370 APSInt Result = Value;
1371 // Figure out if this is a truncate, extend or noop cast.
1372 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001373 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001374 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001375 return Result;
1376}
1377
Richard Smithc1c5f272011-12-13 06:39:58 +00001378static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1379 QualType SrcType, const APSInt &Value,
1380 QualType DestType, APFloat &Result) {
1381 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1382 if (Result.convertFromAPInt(Value, Value.isSigned(),
1383 APFloat::rmNearestTiesToEven)
1384 & APFloat::opOverflow)
Eli Friedman26dc97c2012-07-17 21:03:05 +00001385 HandleOverflow(Info, E, Value, DestType);
Richard Smithc1c5f272011-12-13 06:39:58 +00001386 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001387}
1388
Richard Smith3835a4e2013-08-06 07:09:20 +00001389static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1390 APValue &Value, const FieldDecl *FD) {
1391 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1392
1393 if (!Value.isInt()) {
1394 // Trying to store a pointer-cast-to-integer into a bitfield.
1395 // FIXME: In this case, we should provide the diagnostic for casting
1396 // a pointer to an integer.
1397 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1398 Info.Diag(E);
1399 return false;
1400 }
1401
1402 APSInt &Int = Value.getInt();
1403 unsigned OldBitWidth = Int.getBitWidth();
1404 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1405 if (NewBitWidth < OldBitWidth)
1406 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1407 return true;
1408}
1409
Eli Friedmane6a24e82011-12-22 03:51:45 +00001410static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1411 llvm::APInt &Res) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001412 APValue SVal;
Eli Friedmane6a24e82011-12-22 03:51:45 +00001413 if (!Evaluate(SVal, Info, E))
1414 return false;
1415 if (SVal.isInt()) {
1416 Res = SVal.getInt();
1417 return true;
1418 }
1419 if (SVal.isFloat()) {
1420 Res = SVal.getFloat().bitcastToAPInt();
1421 return true;
1422 }
1423 if (SVal.isVector()) {
1424 QualType VecTy = E->getType();
1425 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1426 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1427 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1428 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1429 Res = llvm::APInt::getNullValue(VecSize);
1430 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1431 APValue &Elt = SVal.getVectorElt(i);
1432 llvm::APInt EltAsInt;
1433 if (Elt.isInt()) {
1434 EltAsInt = Elt.getInt();
1435 } else if (Elt.isFloat()) {
1436 EltAsInt = Elt.getFloat().bitcastToAPInt();
1437 } else {
1438 // Don't try to handle vectors of anything other than int or float
1439 // (not sure if it's possible to hit this case).
Richard Smith5cfc7d82012-03-15 04:53:45 +00001440 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001441 return false;
1442 }
1443 unsigned BaseEltSize = EltAsInt.getBitWidth();
1444 if (BigEndian)
1445 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1446 else
1447 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1448 }
1449 return true;
1450 }
1451 // Give up if the input isn't an int, float, or vector. For example, we
1452 // reject "(v4i16)(intptr_t)&a".
Richard Smith5cfc7d82012-03-15 04:53:45 +00001453 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001454 return false;
1455}
1456
Richard Smithd20afcb2013-05-07 04:50:00 +00001457/// Perform the given integer operation, which is known to need at most BitWidth
1458/// bits, and check for overflow in the original type (if that type was not an
1459/// unsigned type).
1460template<typename Operation>
1461static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1462 const APSInt &LHS, const APSInt &RHS,
1463 unsigned BitWidth, Operation Op) {
1464 if (LHS.isUnsigned())
1465 return Op(LHS, RHS);
1466
1467 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1468 APSInt Result = Value.trunc(LHS.getBitWidth());
1469 if (Result.extend(BitWidth) != Value) {
1470 if (Info.getIntOverflowCheckMode())
1471 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1472 diag::warn_integer_constant_overflow)
1473 << Result.toString(10) << E->getType();
1474 else
1475 HandleOverflow(Info, E, Value, E->getType());
1476 }
1477 return Result;
1478}
1479
1480/// Perform the given binary integer operation.
1481static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1482 BinaryOperatorKind Opcode, APSInt RHS,
1483 APSInt &Result) {
1484 switch (Opcode) {
1485 default:
1486 Info.Diag(E);
1487 return false;
1488 case BO_Mul:
1489 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1490 std::multiplies<APSInt>());
1491 return true;
1492 case BO_Add:
1493 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1494 std::plus<APSInt>());
1495 return true;
1496 case BO_Sub:
1497 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1498 std::minus<APSInt>());
1499 return true;
1500 case BO_And: Result = LHS & RHS; return true;
1501 case BO_Xor: Result = LHS ^ RHS; return true;
1502 case BO_Or: Result = LHS | RHS; return true;
1503 case BO_Div:
1504 case BO_Rem:
1505 if (RHS == 0) {
1506 Info.Diag(E, diag::note_expr_divide_by_zero);
1507 return false;
1508 }
1509 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1510 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1511 LHS.isSigned() && LHS.isMinSignedValue())
1512 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1513 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1514 return true;
1515 case BO_Shl: {
1516 if (Info.getLangOpts().OpenCL)
1517 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1518 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1519 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1520 RHS.isUnsigned());
1521 else if (RHS.isSigned() && RHS.isNegative()) {
1522 // During constant-folding, a negative shift is an opposite shift. Such
1523 // a shift is not a constant expression.
1524 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1525 RHS = -RHS;
1526 goto shift_right;
1527 }
1528 shift_left:
1529 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1530 // the shifted type.
1531 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1532 if (SA != RHS) {
1533 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1534 << RHS << E->getType() << LHS.getBitWidth();
1535 } else if (LHS.isSigned()) {
1536 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1537 // operand, and must not overflow the corresponding unsigned type.
1538 if (LHS.isNegative())
1539 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1540 else if (LHS.countLeadingZeros() < SA)
1541 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1542 }
1543 Result = LHS << SA;
1544 return true;
1545 }
1546 case BO_Shr: {
1547 if (Info.getLangOpts().OpenCL)
1548 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1549 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1550 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1551 RHS.isUnsigned());
1552 else if (RHS.isSigned() && RHS.isNegative()) {
1553 // During constant-folding, a negative shift is an opposite shift. Such a
1554 // shift is not a constant expression.
1555 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1556 RHS = -RHS;
1557 goto shift_left;
1558 }
1559 shift_right:
1560 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1561 // shifted type.
1562 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1563 if (SA != RHS)
1564 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1565 << RHS << E->getType() << LHS.getBitWidth();
1566 Result = LHS >> SA;
1567 return true;
1568 }
1569
1570 case BO_LT: Result = LHS < RHS; return true;
1571 case BO_GT: Result = LHS > RHS; return true;
1572 case BO_LE: Result = LHS <= RHS; return true;
1573 case BO_GE: Result = LHS >= RHS; return true;
1574 case BO_EQ: Result = LHS == RHS; return true;
1575 case BO_NE: Result = LHS != RHS; return true;
1576 }
1577}
1578
Richard Smitha49a7fe2013-05-07 23:34:45 +00001579/// Perform the given binary floating-point operation, in-place, on LHS.
1580static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1581 APFloat &LHS, BinaryOperatorKind Opcode,
1582 const APFloat &RHS) {
1583 switch (Opcode) {
1584 default:
1585 Info.Diag(E);
1586 return false;
1587 case BO_Mul:
1588 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1589 break;
1590 case BO_Add:
1591 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1592 break;
1593 case BO_Sub:
1594 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1595 break;
1596 case BO_Div:
1597 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1598 break;
1599 }
1600
1601 if (LHS.isInfinity() || LHS.isNaN())
1602 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1603 return true;
1604}
1605
Richard Smithb4e85ed2012-01-06 16:39:00 +00001606/// Cast an lvalue referring to a base subobject to a derived class, by
1607/// truncating the lvalue's path to the given length.
1608static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1609 const RecordDecl *TruncatedType,
1610 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001611 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001612
1613 // Check we actually point to a derived class object.
1614 if (TruncatedElements == D.Entries.size())
1615 return true;
1616 assert(TruncatedElements >= D.MostDerivedPathLength &&
1617 "not casting to a derived class");
1618 if (!Result.checkSubobject(Info, E, CSK_Derived))
1619 return false;
1620
1621 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001622 const RecordDecl *RD = TruncatedType;
1623 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCall8d59dee2012-05-01 00:38:49 +00001624 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001625 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1626 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001627 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001628 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001629 else
Richard Smith180f4792011-11-10 06:34:14 +00001630 Result.Offset -= Layout.getBaseClassOffset(Base);
1631 RD = Base;
1632 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001633 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001634 return true;
1635}
1636
John McCall8d59dee2012-05-01 00:38:49 +00001637static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001638 const CXXRecordDecl *Derived,
1639 const CXXRecordDecl *Base,
1640 const ASTRecordLayout *RL = 0) {
John McCall8d59dee2012-05-01 00:38:49 +00001641 if (!RL) {
1642 if (Derived->isInvalidDecl()) return false;
1643 RL = &Info.Ctx.getASTRecordLayout(Derived);
1644 }
1645
Richard Smith180f4792011-11-10 06:34:14 +00001646 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001647 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCall8d59dee2012-05-01 00:38:49 +00001648 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001649}
1650
Richard Smithb4e85ed2012-01-06 16:39:00 +00001651static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001652 const CXXRecordDecl *DerivedDecl,
1653 const CXXBaseSpecifier *Base) {
1654 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1655
John McCall8d59dee2012-05-01 00:38:49 +00001656 if (!Base->isVirtual())
1657 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001658
Richard Smithb4e85ed2012-01-06 16:39:00 +00001659 SubobjectDesignator &D = Obj.Designator;
1660 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001661 return false;
1662
Richard Smithb4e85ed2012-01-06 16:39:00 +00001663 // Extract most-derived object and corresponding type.
1664 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1665 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1666 return false;
1667
1668 // Find the virtual base class.
John McCall8d59dee2012-05-01 00:38:49 +00001669 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001670 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1671 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001672 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001673 return true;
1674}
1675
Richard Smith8a66bf72013-06-03 05:03:02 +00001676static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1677 QualType Type, LValue &Result) {
1678 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1679 PathE = E->path_end();
1680 PathI != PathE; ++PathI) {
1681 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1682 *PathI))
1683 return false;
1684 Type = (*PathI)->getType();
1685 }
1686 return true;
1687}
1688
Richard Smith180f4792011-11-10 06:34:14 +00001689/// Update LVal to refer to the given field, which must be a member of the type
1690/// currently described by LVal.
John McCall8d59dee2012-05-01 00:38:49 +00001691static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001692 const FieldDecl *FD,
1693 const ASTRecordLayout *RL = 0) {
John McCall8d59dee2012-05-01 00:38:49 +00001694 if (!RL) {
1695 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001696 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCall8d59dee2012-05-01 00:38:49 +00001697 }
Richard Smith180f4792011-11-10 06:34:14 +00001698
1699 unsigned I = FD->getFieldIndex();
1700 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001701 LVal.addDecl(Info, E, FD);
John McCall8d59dee2012-05-01 00:38:49 +00001702 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001703}
1704
Richard Smithd9b02e72012-01-25 22:15:11 +00001705/// Update LVal to refer to the given indirect field.
John McCall8d59dee2012-05-01 00:38:49 +00001706static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smithd9b02e72012-01-25 22:15:11 +00001707 LValue &LVal,
1708 const IndirectFieldDecl *IFD) {
1709 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1710 CE = IFD->chain_end(); C != CE; ++C)
John McCall8d59dee2012-05-01 00:38:49 +00001711 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1712 return false;
1713 return true;
Richard Smithd9b02e72012-01-25 22:15:11 +00001714}
1715
Richard Smith180f4792011-11-10 06:34:14 +00001716/// Get the size of the given type in char units.
Richard Smith74e1ad92012-02-16 02:46:34 +00001717static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1718 QualType Type, CharUnits &Size) {
Richard Smith180f4792011-11-10 06:34:14 +00001719 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1720 // extension.
1721 if (Type->isVoidType() || Type->isFunctionType()) {
1722 Size = CharUnits::One();
1723 return true;
1724 }
1725
1726 if (!Type->isConstantSizeType()) {
1727 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith74e1ad92012-02-16 02:46:34 +00001728 // FIXME: Better diagnostic.
1729 Info.Diag(Loc);
Richard Smith180f4792011-11-10 06:34:14 +00001730 return false;
1731 }
1732
1733 Size = Info.Ctx.getTypeSizeInChars(Type);
1734 return true;
1735}
1736
1737/// Update a pointer value to model pointer arithmetic.
1738/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001739/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001740/// \param LVal - The pointer value to be updated.
1741/// \param EltTy - The pointee type represented by LVal.
1742/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001743static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1744 LValue &LVal, QualType EltTy,
1745 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001746 CharUnits SizeOfPointee;
Richard Smith74e1ad92012-02-16 02:46:34 +00001747 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smith180f4792011-11-10 06:34:14 +00001748 return false;
1749
1750 // Compute the new offset in the appropriate width.
1751 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001752 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001753 return true;
1754}
1755
Richard Smith86024012012-02-18 22:04:06 +00001756/// Update an lvalue to refer to a component of a complex number.
1757/// \param Info - Information about the ongoing evaluation.
1758/// \param LVal - The lvalue to be updated.
1759/// \param EltTy - The complex number's component type.
1760/// \param Imag - False for the real component, true for the imaginary.
1761static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1762 LValue &LVal, QualType EltTy,
1763 bool Imag) {
1764 if (Imag) {
1765 CharUnits SizeOfComponent;
1766 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1767 return false;
1768 LVal.Offset += SizeOfComponent;
1769 }
1770 LVal.addComplex(Info, E, EltTy, Imag);
1771 return true;
1772}
1773
Richard Smith03f96112011-10-24 17:54:18 +00001774/// Try to evaluate the initializer for a variable declaration.
Richard Smithb476a142013-05-05 21:17:10 +00001775///
1776/// \param Info Information about the ongoing evaluation.
1777/// \param E An expression to be used when printing diagnostics.
1778/// \param VD The variable whose initializer should be obtained.
1779/// \param Frame The frame in which the variable was created. Must be null
1780/// if this variable is not local to the evaluation.
1781/// \param Result Filled in with a pointer to the value of the variable.
1782static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1783 const VarDecl *VD, CallStackFrame *Frame,
1784 APValue *&Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001785 // If this is a parameter to an active constexpr function call, perform
1786 // argument substitution.
1787 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001788 // Assume arguments of a potential constant expression are unknown
1789 // constant expressions.
1790 if (Info.CheckingPotentialConstantExpression)
1791 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001792 if (!Frame || !Frame->Arguments) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001793 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001794 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001795 }
Richard Smithb476a142013-05-05 21:17:10 +00001796 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smith177dce72011-11-01 16:57:24 +00001797 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001798 }
Richard Smith03f96112011-10-24 17:54:18 +00001799
Richard Smitha10b9782013-04-22 15:31:51 +00001800 // If this is a local variable, dig out its value.
Richard Smithb476a142013-05-05 21:17:10 +00001801 if (Frame) {
Richard Smith03ce5f82013-07-24 07:11:57 +00001802 Result = Frame->getTemporary(VD);
1803 assert(Result && "missing value for local variable");
1804 return true;
Richard Smitha10b9782013-04-22 15:31:51 +00001805 }
1806
Richard Smith099e7f62011-12-19 06:19:21 +00001807 // Dig out the initializer, and use the declaration which it's attached to.
1808 const Expr *Init = VD->getAnyInitializer(VD);
1809 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001810 // If we're checking a potential constant expression, the variable could be
1811 // initialized later.
1812 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001813 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001814 return false;
1815 }
1816
Richard Smith180f4792011-11-10 06:34:14 +00001817 // If we're currently evaluating the initializer of this declaration, use that
1818 // in-flight value.
Richard Smith6391ea22013-05-09 07:14:00 +00001819 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smithb476a142013-05-05 21:17:10 +00001820 Result = Info.EvaluatingDeclValue;
Richard Smith03ce5f82013-07-24 07:11:57 +00001821 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001822 }
1823
Richard Smith65ac5982011-11-01 21:06:14 +00001824 // Never evaluate the initializer of a weak variable. We can't be sure that
1825 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001826 if (VD->isWeak()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001827 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001828 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001829 }
Richard Smith65ac5982011-11-01 21:06:14 +00001830
Richard Smith099e7f62011-12-19 06:19:21 +00001831 // Check that we can fold the initializer. In C++, we will have already done
1832 // this in the cases where it matters for conformance.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001833 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith099e7f62011-12-19 06:19:21 +00001834 if (!VD->evaluateValue(Notes)) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001835 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001836 Notes.size() + 1) << VD;
1837 Info.Note(VD->getLocation(), diag::note_declared_at);
1838 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001839 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001840 } else if (!VD->checkInitIsICE()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001841 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001842 Notes.size() + 1) << VD;
1843 Info.Note(VD->getLocation(), diag::note_declared_at);
1844 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001845 }
Richard Smith03f96112011-10-24 17:54:18 +00001846
Richard Smithb476a142013-05-05 21:17:10 +00001847 Result = VD->getEvaluatedValue();
Richard Smith47a1eed2011-10-29 20:57:55 +00001848 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001849}
1850
Richard Smithc49bd112011-10-28 17:51:58 +00001851static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001852 Qualifiers Quals = T.getQualifiers();
1853 return Quals.hasConst() && !Quals.hasVolatile();
1854}
1855
Richard Smith59efe262011-11-11 04:05:33 +00001856/// Get the base index of the given base class within an APValue representing
1857/// the given derived class.
1858static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1859 const CXXRecordDecl *Base) {
1860 Base = Base->getCanonicalDecl();
1861 unsigned Index = 0;
1862 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1863 E = Derived->bases_end(); I != E; ++I, ++Index) {
1864 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1865 return Index;
1866 }
1867
1868 llvm_unreachable("base class missing from derived class's bases list");
1869}
1870
Richard Smithbebf5b12013-04-26 14:36:30 +00001871/// Extract the value of a character from a string literal.
1872static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1873 uint64_t Index) {
Richard Smithf3908f22012-02-17 03:35:37 +00001874 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smithbebf5b12013-04-26 14:36:30 +00001875 const StringLiteral *S = cast<StringLiteral>(Lit);
1876 const ConstantArrayType *CAT =
1877 Info.Ctx.getAsConstantArrayType(S->getType());
1878 assert(CAT && "string literal isn't an array");
1879 QualType CharType = CAT->getElementType();
Richard Smithfe587202012-04-15 02:50:59 +00001880 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smithf3908f22012-02-17 03:35:37 +00001881
1882 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smithfe587202012-04-15 02:50:59 +00001883 CharType->isUnsignedIntegerType());
Richard Smithf3908f22012-02-17 03:35:37 +00001884 if (Index < S->getLength())
1885 Value = S->getCodeUnit(Index);
1886 return Value;
1887}
1888
Richard Smithbebf5b12013-04-26 14:36:30 +00001889// Expand a string literal into an array of characters.
1890static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
1891 APValue &Result) {
1892 const StringLiteral *S = cast<StringLiteral>(Lit);
1893 const ConstantArrayType *CAT =
1894 Info.Ctx.getAsConstantArrayType(S->getType());
1895 assert(CAT && "string literal isn't an array");
1896 QualType CharType = CAT->getElementType();
1897 assert(CharType->isIntegerType() && "unexpected character type");
1898
1899 unsigned Elts = CAT->getSize().getZExtValue();
1900 Result = APValue(APValue::UninitArray(),
1901 std::min(S->getLength(), Elts), Elts);
1902 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1903 CharType->isUnsignedIntegerType());
1904 if (Result.hasArrayFiller())
1905 Result.getArrayFiller() = APValue(Value);
1906 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
1907 Value = S->getCodeUnit(I);
1908 Result.getArrayInitializedElt(I) = APValue(Value);
1909 }
1910}
1911
1912// Expand an array so that it has more than Index filled elements.
1913static void expandArray(APValue &Array, unsigned Index) {
1914 unsigned Size = Array.getArraySize();
1915 assert(Index < Size);
1916
1917 // Always at least double the number of elements for which we store a value.
1918 unsigned OldElts = Array.getArrayInitializedElts();
1919 unsigned NewElts = std::max(Index+1, OldElts * 2);
1920 NewElts = std::min(Size, std::max(NewElts, 8u));
1921
1922 // Copy the data across.
1923 APValue NewValue(APValue::UninitArray(), NewElts, Size);
1924 for (unsigned I = 0; I != OldElts; ++I)
1925 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
1926 for (unsigned I = OldElts; I != NewElts; ++I)
1927 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
1928 if (NewValue.hasArrayFiller())
1929 NewValue.getArrayFiller() = Array.getArrayFiller();
1930 Array.swap(NewValue);
1931}
1932
Richard Smitha49a7fe2013-05-07 23:34:45 +00001933/// Kinds of access we can perform on an object, for diagnostics.
Richard Smithbebf5b12013-04-26 14:36:30 +00001934enum AccessKinds {
1935 AK_Read,
Richard Smith5528ac92013-05-05 23:31:59 +00001936 AK_Assign,
1937 AK_Increment,
1938 AK_Decrement
Richard Smithbebf5b12013-04-26 14:36:30 +00001939};
1940
Richard Smithb476a142013-05-05 21:17:10 +00001941/// A handle to a complete object (an object that is not a subobject of
1942/// another object).
1943struct CompleteObject {
1944 /// The value of the complete object.
1945 APValue *Value;
1946 /// The type of the complete object.
1947 QualType Type;
1948
1949 CompleteObject() : Value(0) {}
1950 CompleteObject(APValue *Value, QualType Type)
1951 : Value(Value), Type(Type) {
1952 assert(Value && "missing value for complete object");
1953 }
1954
David Blaikie7247c882013-05-15 07:37:26 +00001955 LLVM_EXPLICIT operator bool() const { return Value; }
Richard Smithb476a142013-05-05 21:17:10 +00001956};
1957
Richard Smithbebf5b12013-04-26 14:36:30 +00001958/// Find the designated sub-object of an rvalue.
1959template<typename SubobjectHandler>
1960typename SubobjectHandler::result_type
Richard Smithb476a142013-05-05 21:17:10 +00001961findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smithbebf5b12013-04-26 14:36:30 +00001962 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001963 if (Sub.Invalid)
1964 // A diagnostic will have already been produced.
Richard Smithbebf5b12013-04-26 14:36:30 +00001965 return handler.failed();
Richard Smithb4e85ed2012-01-06 16:39:00 +00001966 if (Sub.isOnePastTheEnd()) {
Richard Smithbebf5b12013-04-26 14:36:30 +00001967 if (Info.getLangOpts().CPlusPlus11)
1968 Info.Diag(E, diag::note_constexpr_access_past_end)
1969 << handler.AccessKind;
1970 else
1971 Info.Diag(E);
1972 return handler.failed();
Richard Smith7098cbd2011-12-21 05:04:46 +00001973 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001974
Richard Smithb476a142013-05-05 21:17:10 +00001975 APValue *O = Obj.Value;
1976 QualType ObjType = Obj.Type;
Richard Smith3835a4e2013-08-06 07:09:20 +00001977 const FieldDecl *LastField = 0;
1978
Richard Smith180f4792011-11-10 06:34:14 +00001979 // Walk the designator's path to find the subobject.
Richard Smith03ce5f82013-07-24 07:11:57 +00001980 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
1981 if (O->isUninit()) {
1982 if (!Info.CheckingPotentialConstantExpression)
1983 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
1984 return handler.failed();
1985 }
1986
Richard Smith3835a4e2013-08-06 07:09:20 +00001987 if (I == N) {
1988 if (!handler.found(*O, ObjType))
1989 return false;
Richard Smith03ce5f82013-07-24 07:11:57 +00001990
Richard Smith3835a4e2013-08-06 07:09:20 +00001991 // If we modified a bit-field, truncate it to the right width.
1992 if (handler.AccessKind != AK_Read &&
1993 LastField && LastField->isBitField() &&
1994 !truncateBitfieldValue(Info, E, *O, LastField))
1995 return false;
1996
1997 return true;
1998 }
1999
2000 LastField = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00002001 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00002002 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00002003 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00002004 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00002005 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00002006 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00002007 // Note, it should not be possible to form a pointer with a valid
2008 // designator which points more than one past the end of the array.
Richard Smithbebf5b12013-04-26 14:36:30 +00002009 if (Info.getLangOpts().CPlusPlus11)
2010 Info.Diag(E, diag::note_constexpr_access_past_end)
2011 << handler.AccessKind;
2012 else
2013 Info.Diag(E);
2014 return handler.failed();
Richard Smithf48fdb02011-12-09 22:58:01 +00002015 }
Richard Smithbebf5b12013-04-26 14:36:30 +00002016
2017 ObjType = CAT->getElementType();
2018
Richard Smithf3908f22012-02-17 03:35:37 +00002019 // An array object is represented as either an Array APValue or as an
2020 // LValue which refers to a string literal.
2021 if (O->isLValue()) {
2022 assert(I == N - 1 && "extracting subobject of character?");
2023 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smithbebf5b12013-04-26 14:36:30 +00002024 if (handler.AccessKind != AK_Read)
2025 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2026 *O);
2027 else
2028 return handler.foundString(*O, ObjType, Index);
2029 }
2030
2031 if (O->getArrayInitializedElts() > Index)
Richard Smithcc5d4f62011-11-07 09:22:26 +00002032 O = &O->getArrayInitializedElt(Index);
Richard Smithbebf5b12013-04-26 14:36:30 +00002033 else if (handler.AccessKind != AK_Read) {
2034 expandArray(*O, Index);
2035 O = &O->getArrayInitializedElt(Index);
2036 } else
Richard Smithcc5d4f62011-11-07 09:22:26 +00002037 O = &O->getArrayFiller();
Richard Smith86024012012-02-18 22:04:06 +00002038 } else if (ObjType->isAnyComplexType()) {
2039 // Next subobject is a complex number.
2040 uint64_t Index = Sub.Entries[I].ArrayIndex;
2041 if (Index > 1) {
Richard Smithbebf5b12013-04-26 14:36:30 +00002042 if (Info.getLangOpts().CPlusPlus11)
2043 Info.Diag(E, diag::note_constexpr_access_past_end)
2044 << handler.AccessKind;
2045 else
2046 Info.Diag(E);
2047 return handler.failed();
Richard Smith86024012012-02-18 22:04:06 +00002048 }
Richard Smithbebf5b12013-04-26 14:36:30 +00002049
2050 bool WasConstQualified = ObjType.isConstQualified();
2051 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2052 if (WasConstQualified)
2053 ObjType.addConst();
2054
Richard Smith86024012012-02-18 22:04:06 +00002055 assert(I == N - 1 && "extracting subobject of scalar?");
2056 if (O->isComplexInt()) {
Richard Smithbebf5b12013-04-26 14:36:30 +00002057 return handler.found(Index ? O->getComplexIntImag()
2058 : O->getComplexIntReal(), ObjType);
Richard Smith86024012012-02-18 22:04:06 +00002059 } else {
2060 assert(O->isComplexFloat());
Richard Smithbebf5b12013-04-26 14:36:30 +00002061 return handler.found(Index ? O->getComplexFloatImag()
2062 : O->getComplexFloatReal(), ObjType);
Richard Smith86024012012-02-18 22:04:06 +00002063 }
Richard Smith180f4792011-11-10 06:34:14 +00002064 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithbebf5b12013-04-26 14:36:30 +00002065 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002066 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smithb4e5e282012-02-09 03:29:58 +00002067 << Field;
2068 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smithbebf5b12013-04-26 14:36:30 +00002069 return handler.failed();
Richard Smithb4e5e282012-02-09 03:29:58 +00002070 }
2071
Richard Smith180f4792011-11-10 06:34:14 +00002072 // Next subobject is a class, struct or union field.
2073 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2074 if (RD->isUnion()) {
2075 const FieldDecl *UnionField = O->getUnionField();
2076 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00002077 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smithbebf5b12013-04-26 14:36:30 +00002078 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2079 << handler.AccessKind << Field << !UnionField << UnionField;
2080 return handler.failed();
Richard Smithf48fdb02011-12-09 22:58:01 +00002081 }
Richard Smith180f4792011-11-10 06:34:14 +00002082 O = &O->getUnionValue();
2083 } else
2084 O = &O->getStructField(Field->getFieldIndex());
Richard Smithbebf5b12013-04-26 14:36:30 +00002085
2086 bool WasConstQualified = ObjType.isConstQualified();
Richard Smith180f4792011-11-10 06:34:14 +00002087 ObjType = Field->getType();
Richard Smithbebf5b12013-04-26 14:36:30 +00002088 if (WasConstQualified && !Field->isMutable())
2089 ObjType.addConst();
Richard Smith7098cbd2011-12-21 05:04:46 +00002090
2091 if (ObjType.isVolatileQualified()) {
2092 if (Info.getLangOpts().CPlusPlus) {
2093 // FIXME: Include a description of the path to the volatile subobject.
Richard Smithbebf5b12013-04-26 14:36:30 +00002094 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2095 << handler.AccessKind << 2 << Field;
Richard Smith7098cbd2011-12-21 05:04:46 +00002096 Info.Note(Field->getLocation(), diag::note_declared_at);
2097 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002098 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00002099 }
Richard Smithbebf5b12013-04-26 14:36:30 +00002100 return handler.failed();
Richard Smith7098cbd2011-12-21 05:04:46 +00002101 }
Richard Smith3835a4e2013-08-06 07:09:20 +00002102
2103 LastField = Field;
Richard Smithcc5d4f62011-11-07 09:22:26 +00002104 } else {
Richard Smith180f4792011-11-10 06:34:14 +00002105 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00002106 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2107 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2108 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smithbebf5b12013-04-26 14:36:30 +00002109
2110 bool WasConstQualified = ObjType.isConstQualified();
Richard Smith59efe262011-11-11 04:05:33 +00002111 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithbebf5b12013-04-26 14:36:30 +00002112 if (WasConstQualified)
2113 ObjType.addConst();
Richard Smithcc5d4f62011-11-07 09:22:26 +00002114 }
2115 }
Richard Smithbebf5b12013-04-26 14:36:30 +00002116}
2117
Benjamin Kramer888d3452013-04-26 22:01:47 +00002118namespace {
Richard Smithbebf5b12013-04-26 14:36:30 +00002119struct ExtractSubobjectHandler {
2120 EvalInfo &Info;
Richard Smithb476a142013-05-05 21:17:10 +00002121 APValue &Result;
Richard Smithbebf5b12013-04-26 14:36:30 +00002122
2123 static const AccessKinds AccessKind = AK_Read;
2124
2125 typedef bool result_type;
2126 bool failed() { return false; }
2127 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smithb476a142013-05-05 21:17:10 +00002128 Result = Subobj;
Richard Smithbebf5b12013-04-26 14:36:30 +00002129 return true;
2130 }
2131 bool found(APSInt &Value, QualType SubobjType) {
Richard Smithb476a142013-05-05 21:17:10 +00002132 Result = APValue(Value);
Richard Smithbebf5b12013-04-26 14:36:30 +00002133 return true;
2134 }
2135 bool found(APFloat &Value, QualType SubobjType) {
Richard Smithb476a142013-05-05 21:17:10 +00002136 Result = APValue(Value);
Richard Smithbebf5b12013-04-26 14:36:30 +00002137 return true;
2138 }
2139 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smithb476a142013-05-05 21:17:10 +00002140 Result = APValue(extractStringLiteralCharacter(
Richard Smithbebf5b12013-04-26 14:36:30 +00002141 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2142 return true;
2143 }
2144};
Richard Smithb476a142013-05-05 21:17:10 +00002145} // end anonymous namespace
2146
Richard Smithbebf5b12013-04-26 14:36:30 +00002147const AccessKinds ExtractSubobjectHandler::AccessKind;
2148
2149/// Extract the designated sub-object of an rvalue.
2150static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smithb476a142013-05-05 21:17:10 +00002151 const CompleteObject &Obj,
2152 const SubobjectDesignator &Sub,
2153 APValue &Result) {
2154 ExtractSubobjectHandler Handler = { Info, Result };
2155 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithbebf5b12013-04-26 14:36:30 +00002156}
2157
Richard Smithb476a142013-05-05 21:17:10 +00002158namespace {
Richard Smithbebf5b12013-04-26 14:36:30 +00002159struct ModifySubobjectHandler {
2160 EvalInfo &Info;
2161 APValue &NewVal;
2162 const Expr *E;
2163
2164 typedef bool result_type;
2165 static const AccessKinds AccessKind = AK_Assign;
2166
2167 bool checkConst(QualType QT) {
2168 // Assigning to a const object has undefined behavior.
2169 if (QT.isConstQualified()) {
2170 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2171 return false;
2172 }
2173 return true;
2174 }
2175
2176 bool failed() { return false; }
2177 bool found(APValue &Subobj, QualType SubobjType) {
2178 if (!checkConst(SubobjType))
2179 return false;
2180 // We've been given ownership of NewVal, so just swap it in.
2181 Subobj.swap(NewVal);
2182 return true;
2183 }
2184 bool found(APSInt &Value, QualType SubobjType) {
2185 if (!checkConst(SubobjType))
2186 return false;
2187 if (!NewVal.isInt()) {
2188 // Maybe trying to write a cast pointer value into a complex?
2189 Info.Diag(E);
2190 return false;
2191 }
2192 Value = NewVal.getInt();
2193 return true;
2194 }
2195 bool found(APFloat &Value, QualType SubobjType) {
2196 if (!checkConst(SubobjType))
2197 return false;
2198 Value = NewVal.getFloat();
2199 return true;
2200 }
2201 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2202 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2203 }
2204};
Benjamin Kramer888d3452013-04-26 22:01:47 +00002205} // end anonymous namespace
Richard Smithbebf5b12013-04-26 14:36:30 +00002206
Richard Smithb476a142013-05-05 21:17:10 +00002207const AccessKinds ModifySubobjectHandler::AccessKind;
2208
Richard Smithbebf5b12013-04-26 14:36:30 +00002209/// Update the designated sub-object of an rvalue to the given value.
2210static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smithb476a142013-05-05 21:17:10 +00002211 const CompleteObject &Obj,
Richard Smithbebf5b12013-04-26 14:36:30 +00002212 const SubobjectDesignator &Sub,
2213 APValue &NewVal) {
2214 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smithb476a142013-05-05 21:17:10 +00002215 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithcc5d4f62011-11-07 09:22:26 +00002216}
2217
Richard Smithf15fda02012-02-02 01:16:57 +00002218/// Find the position where two subobject designators diverge, or equivalently
2219/// the length of the common initial subsequence.
2220static unsigned FindDesignatorMismatch(QualType ObjType,
2221 const SubobjectDesignator &A,
2222 const SubobjectDesignator &B,
2223 bool &WasArrayIndex) {
2224 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2225 for (/**/; I != N; ++I) {
Richard Smith86024012012-02-18 22:04:06 +00002226 if (!ObjType.isNull() &&
2227 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smithf15fda02012-02-02 01:16:57 +00002228 // Next subobject is an array element.
2229 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2230 WasArrayIndex = true;
2231 return I;
2232 }
Richard Smith86024012012-02-18 22:04:06 +00002233 if (ObjType->isAnyComplexType())
2234 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2235 else
2236 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smithf15fda02012-02-02 01:16:57 +00002237 } else {
2238 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2239 WasArrayIndex = false;
2240 return I;
2241 }
2242 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2243 // Next subobject is a field.
2244 ObjType = FD->getType();
2245 else
2246 // Next subobject is a base class.
2247 ObjType = QualType();
2248 }
2249 }
2250 WasArrayIndex = false;
2251 return I;
2252}
2253
2254/// Determine whether the given subobject designators refer to elements of the
2255/// same array object.
2256static bool AreElementsOfSameArray(QualType ObjType,
2257 const SubobjectDesignator &A,
2258 const SubobjectDesignator &B) {
2259 if (A.Entries.size() != B.Entries.size())
2260 return false;
2261
2262 bool IsArray = A.MostDerivedArraySize != 0;
2263 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2264 // A is a subobject of the array element.
2265 return false;
2266
2267 // If A (and B) designates an array element, the last entry will be the array
2268 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2269 // of length 1' case, and the entire path must match.
2270 bool WasArrayIndex;
2271 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2272 return CommonLength >= A.Entries.size() - IsArray;
2273}
2274
Richard Smithb476a142013-05-05 21:17:10 +00002275/// Find the complete object to which an LValue refers.
2276CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
2277 const LValue &LVal, QualType LValType) {
2278 if (!LVal.Base) {
2279 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2280 return CompleteObject();
2281 }
2282
2283 CallStackFrame *Frame = 0;
2284 if (LVal.CallIndex) {
2285 Frame = Info.getCallFrame(LVal.CallIndex);
2286 if (!Frame) {
2287 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2288 << AK << LVal.Base.is<const ValueDecl*>();
2289 NoteLValueLocation(Info, LVal.Base);
2290 return CompleteObject();
2291 }
Richard Smithb476a142013-05-05 21:17:10 +00002292 }
2293
2294 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2295 // is not a constant expression (even if the object is non-volatile). We also
2296 // apply this rule to C++98, in order to conform to the expected 'volatile'
2297 // semantics.
2298 if (LValType.isVolatileQualified()) {
2299 if (Info.getLangOpts().CPlusPlus)
2300 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2301 << AK << LValType;
2302 else
2303 Info.Diag(E);
2304 return CompleteObject();
2305 }
2306
2307 // Compute value storage location and type of base object.
2308 APValue *BaseVal = 0;
Richard Smith8a66bf72013-06-03 05:03:02 +00002309 QualType BaseType = getType(LVal.Base);
Richard Smithb476a142013-05-05 21:17:10 +00002310
2311 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2312 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2313 // In C++11, constexpr, non-volatile variables initialized with constant
2314 // expressions are constant expressions too. Inside constexpr functions,
2315 // parameters are constant expressions even if they're non-const.
2316 // In C++1y, objects local to a constant expression (those with a Frame) are
2317 // both readable and writable inside constant expressions.
2318 // In C, such things can also be folded, although they are not ICEs.
2319 const VarDecl *VD = dyn_cast<VarDecl>(D);
2320 if (VD) {
2321 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2322 VD = VDef;
2323 }
2324 if (!VD || VD->isInvalidDecl()) {
2325 Info.Diag(E);
2326 return CompleteObject();
2327 }
2328
2329 // Accesses of volatile-qualified objects are not allowed.
Richard Smithb476a142013-05-05 21:17:10 +00002330 if (BaseType.isVolatileQualified()) {
2331 if (Info.getLangOpts().CPlusPlus) {
2332 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2333 << AK << 1 << VD;
2334 Info.Note(VD->getLocation(), diag::note_declared_at);
2335 } else {
2336 Info.Diag(E);
2337 }
2338 return CompleteObject();
2339 }
2340
2341 // Unless we're looking at a local variable or argument in a constexpr call,
2342 // the variable we're reading must be const.
2343 if (!Frame) {
Richard Smith6391ea22013-05-09 07:14:00 +00002344 if (Info.getLangOpts().CPlusPlus1y &&
2345 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2346 // OK, we can read and modify an object if we're in the process of
2347 // evaluating its initializer, because its lifetime began in this
2348 // evaluation.
2349 } else if (AK != AK_Read) {
2350 // All the remaining cases only permit reading.
2351 Info.Diag(E, diag::note_constexpr_modify_global);
2352 return CompleteObject();
2353 } else if (VD->isConstexpr()) {
Richard Smithb476a142013-05-05 21:17:10 +00002354 // OK, we can read this variable.
2355 } else if (BaseType->isIntegralOrEnumerationType()) {
2356 if (!BaseType.isConstQualified()) {
2357 if (Info.getLangOpts().CPlusPlus) {
2358 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2359 Info.Note(VD->getLocation(), diag::note_declared_at);
2360 } else {
2361 Info.Diag(E);
2362 }
2363 return CompleteObject();
2364 }
2365 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2366 // We support folding of const floating-point types, in order to make
2367 // static const data members of such types (supported as an extension)
2368 // more useful.
2369 if (Info.getLangOpts().CPlusPlus11) {
2370 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2371 Info.Note(VD->getLocation(), diag::note_declared_at);
2372 } else {
2373 Info.CCEDiag(E);
2374 }
2375 } else {
2376 // FIXME: Allow folding of values of any literal type in all languages.
2377 if (Info.getLangOpts().CPlusPlus11) {
2378 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2379 Info.Note(VD->getLocation(), diag::note_declared_at);
2380 } else {
2381 Info.Diag(E);
2382 }
2383 return CompleteObject();
2384 }
2385 }
2386
2387 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2388 return CompleteObject();
2389 } else {
2390 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2391
2392 if (!Frame) {
Richard Smith211c8dd2013-06-05 00:46:14 +00002393 if (const MaterializeTemporaryExpr *MTE =
2394 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2395 assert(MTE->getStorageDuration() == SD_Static &&
2396 "should have a frame for a non-global materialized temporary");
Richard Smithb476a142013-05-05 21:17:10 +00002397
Richard Smith211c8dd2013-06-05 00:46:14 +00002398 // Per C++1y [expr.const]p2:
2399 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2400 // - a [...] glvalue of integral or enumeration type that refers to
2401 // a non-volatile const object [...]
2402 // [...]
2403 // - a [...] glvalue of literal type that refers to a non-volatile
2404 // object whose lifetime began within the evaluation of e.
2405 //
2406 // C++11 misses the 'began within the evaluation of e' check and
2407 // instead allows all temporaries, including things like:
2408 // int &&r = 1;
2409 // int x = ++r;
2410 // constexpr int k = r;
2411 // Therefore we use the C++1y rules in C++11 too.
2412 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2413 const ValueDecl *ED = MTE->getExtendingDecl();
2414 if (!(BaseType.isConstQualified() &&
2415 BaseType->isIntegralOrEnumerationType()) &&
2416 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2417 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2418 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2419 return CompleteObject();
2420 }
2421
2422 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2423 assert(BaseVal && "got reference to unevaluated temporary");
2424 } else {
2425 Info.Diag(E);
2426 return CompleteObject();
2427 }
2428 } else {
Richard Smith03ce5f82013-07-24 07:11:57 +00002429 BaseVal = Frame->getTemporary(Base);
2430 assert(BaseVal && "missing value for temporary");
Richard Smith211c8dd2013-06-05 00:46:14 +00002431 }
Richard Smithb476a142013-05-05 21:17:10 +00002432
2433 // Volatile temporary objects cannot be accessed in constant expressions.
2434 if (BaseType.isVolatileQualified()) {
2435 if (Info.getLangOpts().CPlusPlus) {
2436 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2437 << AK << 0;
2438 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2439 } else {
2440 Info.Diag(E);
2441 }
2442 return CompleteObject();
2443 }
2444 }
2445
Richard Smith6391ea22013-05-09 07:14:00 +00002446 // During the construction of an object, it is not yet 'const'.
2447 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2448 // and this doesn't do quite the right thing for const subobjects of the
2449 // object under construction.
2450 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2451 BaseType = Info.Ctx.getCanonicalType(BaseType);
2452 BaseType.removeLocalConst();
2453 }
2454
Richard Smithb476a142013-05-05 21:17:10 +00002455 // In C++1y, we can't safely access any mutable state when checking a
2456 // potential constant expression.
2457 if (Frame && Info.getLangOpts().CPlusPlus1y &&
2458 Info.CheckingPotentialConstantExpression)
2459 return CompleteObject();
2460
2461 return CompleteObject(BaseVal, BaseType);
2462}
2463
Richard Smith5528ac92013-05-05 23:31:59 +00002464/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2465/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2466/// glvalue referred to by an entity of reference type.
Richard Smith180f4792011-11-10 06:34:14 +00002467///
2468/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00002469/// \param Conv - The expression for which we are performing the conversion.
2470/// Used for diagnostics.
Richard Smithbebf5b12013-04-26 14:36:30 +00002471/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2472/// case of a non-class type).
Richard Smith180f4792011-11-10 06:34:14 +00002473/// \param LVal - The glvalue on which we are attempting to perform this action.
2474/// \param RVal - The produced value will be placed here.
Richard Smith5528ac92013-05-05 23:31:59 +00002475static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf48fdb02011-12-09 22:58:01 +00002476 QualType Type,
Richard Smith1aa0be82012-03-03 22:46:17 +00002477 const LValue &LVal, APValue &RVal) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002478 if (LVal.Designator.Invalid)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002479 return false;
2480
Richard Smithb476a142013-05-05 21:17:10 +00002481 // Check for special cases where there is no existing APValue to look at.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002482 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithb476a142013-05-05 21:17:10 +00002483 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2484 !Type.isVolatileQualified()) {
2485 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2486 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2487 // initializer until now for such expressions. Such an expression can't be
2488 // an ICE in C, so this only matters for fold.
2489 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2490 if (Type.isVolatileQualified()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002491 Info.Diag(Conv);
Richard Smith0a3bdb62011-11-04 02:25:55 +00002492 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002493 }
Richard Smithb476a142013-05-05 21:17:10 +00002494 APValue Lit;
2495 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2496 return false;
2497 CompleteObject LitObj(&Lit, Base->getType());
2498 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2499 } else if (isa<StringLiteral>(Base)) {
2500 // We represent a string literal array as an lvalue pointing at the
2501 // corresponding expression, rather than building an array of chars.
2502 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2503 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2504 CompleteObject StrObj(&Str, Base->getType());
2505 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith0a3bdb62011-11-04 02:25:55 +00002506 }
Richard Smithc49bd112011-10-28 17:51:58 +00002507 }
2508
Richard Smithb476a142013-05-05 21:17:10 +00002509 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2510 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smithbebf5b12013-04-26 14:36:30 +00002511}
2512
2513/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith5528ac92013-05-05 23:31:59 +00002514static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smithbebf5b12013-04-26 14:36:30 +00002515 QualType LValType, APValue &Val) {
Richard Smithbebf5b12013-04-26 14:36:30 +00002516 if (LVal.Designator.Invalid)
Richard Smithbebf5b12013-04-26 14:36:30 +00002517 return false;
2518
Richard Smithb476a142013-05-05 21:17:10 +00002519 if (!Info.getLangOpts().CPlusPlus1y) {
2520 Info.Diag(E);
Richard Smithbebf5b12013-04-26 14:36:30 +00002521 return false;
2522 }
2523
Richard Smithb476a142013-05-05 21:17:10 +00002524 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2525 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smithc49bd112011-10-28 17:51:58 +00002526}
2527
Richard Smith5528ac92013-05-05 23:31:59 +00002528static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2529 return T->isSignedIntegerType() &&
2530 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2531}
2532
2533namespace {
Richard Smithd20afcb2013-05-07 04:50:00 +00002534struct CompoundAssignSubobjectHandler {
2535 EvalInfo &Info;
2536 const Expr *E;
2537 QualType PromotedLHSType;
2538 BinaryOperatorKind Opcode;
2539 const APValue &RHS;
2540
2541 static const AccessKinds AccessKind = AK_Assign;
2542
2543 typedef bool result_type;
2544
2545 bool checkConst(QualType QT) {
2546 // Assigning to a const object has undefined behavior.
2547 if (QT.isConstQualified()) {
2548 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2549 return false;
2550 }
2551 return true;
2552 }
2553
2554 bool failed() { return false; }
2555 bool found(APValue &Subobj, QualType SubobjType) {
2556 switch (Subobj.getKind()) {
2557 case APValue::Int:
2558 return found(Subobj.getInt(), SubobjType);
2559 case APValue::Float:
2560 return found(Subobj.getFloat(), SubobjType);
2561 case APValue::ComplexInt:
2562 case APValue::ComplexFloat:
2563 // FIXME: Implement complex compound assignment.
2564 Info.Diag(E);
2565 return false;
2566 case APValue::LValue:
2567 return foundPointer(Subobj, SubobjType);
2568 default:
2569 // FIXME: can this happen?
2570 Info.Diag(E);
2571 return false;
2572 }
2573 }
2574 bool found(APSInt &Value, QualType SubobjType) {
2575 if (!checkConst(SubobjType))
2576 return false;
2577
2578 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2579 // We don't support compound assignment on integer-cast-to-pointer
2580 // values.
2581 Info.Diag(E);
2582 return false;
2583 }
2584
2585 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2586 SubobjType, Value);
2587 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2588 return false;
2589 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2590 return true;
2591 }
2592 bool found(APFloat &Value, QualType SubobjType) {
Richard Smitha49a7fe2013-05-07 23:34:45 +00002593 return checkConst(SubobjType) &&
2594 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2595 Value) &&
2596 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2597 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smithd20afcb2013-05-07 04:50:00 +00002598 }
2599 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2600 if (!checkConst(SubobjType))
2601 return false;
2602
2603 QualType PointeeType;
2604 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2605 PointeeType = PT->getPointeeType();
Richard Smitha49a7fe2013-05-07 23:34:45 +00002606
2607 if (PointeeType.isNull() || !RHS.isInt() ||
2608 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smithd20afcb2013-05-07 04:50:00 +00002609 Info.Diag(E);
2610 return false;
2611 }
2612
Richard Smitha49a7fe2013-05-07 23:34:45 +00002613 int64_t Offset = getExtValue(RHS.getInt());
2614 if (Opcode == BO_Sub)
2615 Offset = -Offset;
2616
2617 LValue LVal;
2618 LVal.setFrom(Info.Ctx, Subobj);
2619 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2620 return false;
2621 LVal.moveInto(Subobj);
2622 return true;
Richard Smithd20afcb2013-05-07 04:50:00 +00002623 }
2624 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2625 llvm_unreachable("shouldn't encounter string elements here");
2626 }
2627};
2628} // end anonymous namespace
2629
2630const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2631
2632/// Perform a compound assignment of LVal <op>= RVal.
2633static bool handleCompoundAssignment(
2634 EvalInfo &Info, const Expr *E,
2635 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2636 BinaryOperatorKind Opcode, const APValue &RVal) {
2637 if (LVal.Designator.Invalid)
2638 return false;
2639
2640 if (!Info.getLangOpts().CPlusPlus1y) {
2641 Info.Diag(E);
2642 return false;
2643 }
2644
2645 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2646 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2647 RVal };
2648 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2649}
2650
2651namespace {
Richard Smith5528ac92013-05-05 23:31:59 +00002652struct IncDecSubobjectHandler {
2653 EvalInfo &Info;
2654 const Expr *E;
2655 AccessKinds AccessKind;
2656 APValue *Old;
2657
2658 typedef bool result_type;
2659
2660 bool checkConst(QualType QT) {
2661 // Assigning to a const object has undefined behavior.
2662 if (QT.isConstQualified()) {
2663 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2664 return false;
2665 }
2666 return true;
2667 }
2668
2669 bool failed() { return false; }
2670 bool found(APValue &Subobj, QualType SubobjType) {
2671 // Stash the old value. Also clear Old, so we don't clobber it later
2672 // if we're post-incrementing a complex.
2673 if (Old) {
2674 *Old = Subobj;
2675 Old = 0;
2676 }
2677
2678 switch (Subobj.getKind()) {
2679 case APValue::Int:
2680 return found(Subobj.getInt(), SubobjType);
2681 case APValue::Float:
2682 return found(Subobj.getFloat(), SubobjType);
2683 case APValue::ComplexInt:
2684 return found(Subobj.getComplexIntReal(),
2685 SubobjType->castAs<ComplexType>()->getElementType()
2686 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2687 case APValue::ComplexFloat:
2688 return found(Subobj.getComplexFloatReal(),
2689 SubobjType->castAs<ComplexType>()->getElementType()
2690 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2691 case APValue::LValue:
2692 return foundPointer(Subobj, SubobjType);
2693 default:
2694 // FIXME: can this happen?
2695 Info.Diag(E);
2696 return false;
2697 }
2698 }
2699 bool found(APSInt &Value, QualType SubobjType) {
2700 if (!checkConst(SubobjType))
2701 return false;
2702
2703 if (!SubobjType->isIntegerType()) {
2704 // We don't support increment / decrement on integer-cast-to-pointer
2705 // values.
2706 Info.Diag(E);
2707 return false;
2708 }
2709
2710 if (Old) *Old = APValue(Value);
2711
2712 // bool arithmetic promotes to int, and the conversion back to bool
2713 // doesn't reduce mod 2^n, so special-case it.
2714 if (SubobjType->isBooleanType()) {
2715 if (AccessKind == AK_Increment)
2716 Value = 1;
2717 else
2718 Value = !Value;
2719 return true;
2720 }
2721
2722 bool WasNegative = Value.isNegative();
2723 if (AccessKind == AK_Increment) {
2724 ++Value;
2725
2726 if (!WasNegative && Value.isNegative() &&
2727 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2728 APSInt ActualValue(Value, /*IsUnsigned*/true);
2729 HandleOverflow(Info, E, ActualValue, SubobjType);
2730 }
2731 } else {
2732 --Value;
2733
2734 if (WasNegative && !Value.isNegative() &&
2735 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2736 unsigned BitWidth = Value.getBitWidth();
2737 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2738 ActualValue.setBit(BitWidth);
2739 HandleOverflow(Info, E, ActualValue, SubobjType);
2740 }
2741 }
2742 return true;
2743 }
2744 bool found(APFloat &Value, QualType SubobjType) {
2745 if (!checkConst(SubobjType))
2746 return false;
2747
2748 if (Old) *Old = APValue(Value);
2749
2750 APFloat One(Value.getSemantics(), 1);
2751 if (AccessKind == AK_Increment)
2752 Value.add(One, APFloat::rmNearestTiesToEven);
2753 else
2754 Value.subtract(One, APFloat::rmNearestTiesToEven);
2755 return true;
2756 }
2757 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2758 if (!checkConst(SubobjType))
2759 return false;
2760
2761 QualType PointeeType;
2762 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2763 PointeeType = PT->getPointeeType();
2764 else {
2765 Info.Diag(E);
2766 return false;
2767 }
2768
2769 LValue LVal;
2770 LVal.setFrom(Info.Ctx, Subobj);
2771 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2772 AccessKind == AK_Increment ? 1 : -1))
2773 return false;
2774 LVal.moveInto(Subobj);
2775 return true;
2776 }
2777 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2778 llvm_unreachable("shouldn't encounter string elements here");
2779 }
2780};
2781} // end anonymous namespace
2782
2783/// Perform an increment or decrement on LVal.
2784static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
2785 QualType LValType, bool IsIncrement, APValue *Old) {
2786 if (LVal.Designator.Invalid)
2787 return false;
2788
2789 if (!Info.getLangOpts().CPlusPlus1y) {
2790 Info.Diag(E);
2791 return false;
2792 }
2793
2794 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
2795 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
2796 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
2797 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2798}
2799
Richard Smith59efe262011-11-11 04:05:33 +00002800/// Build an lvalue for the object argument of a member function call.
2801static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2802 LValue &This) {
2803 if (Object->getType()->isPointerType())
2804 return EvaluatePointer(Object, This, Info);
2805
2806 if (Object->isGLValue())
2807 return EvaluateLValue(Object, This, Info);
2808
Richard Smitha10b9782013-04-22 15:31:51 +00002809 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002810 return EvaluateTemporary(Object, This, Info);
2811
2812 return false;
2813}
2814
2815/// HandleMemberPointerAccess - Evaluate a member access operation and build an
2816/// lvalue referring to the result.
2817///
2818/// \param Info - Information about the ongoing evaluation.
Richard Smith8a66bf72013-06-03 05:03:02 +00002819/// \param LV - An lvalue referring to the base of the member pointer.
2820/// \param RHS - The member pointer expression.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002821/// \param IncludeMember - Specifies whether the member itself is included in
2822/// the resulting LValue subobject designator. This is not possible when
2823/// creating a bound member function.
2824/// \return The field or method declaration to which the member pointer refers,
2825/// or 0 if evaluation fails.
2826static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith8a66bf72013-06-03 05:03:02 +00002827 QualType LVType,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002828 LValue &LV,
Richard Smith8a66bf72013-06-03 05:03:02 +00002829 const Expr *RHS,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002830 bool IncludeMember = true) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002831 MemberPtr MemPtr;
Richard Smith8a66bf72013-06-03 05:03:02 +00002832 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002833 return 0;
2834
2835 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2836 // member value, the behavior is undefined.
Richard Smith8a66bf72013-06-03 05:03:02 +00002837 if (!MemPtr.getDecl()) {
2838 // FIXME: Specific diagnostic.
2839 Info.Diag(RHS);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002840 return 0;
Richard Smith8a66bf72013-06-03 05:03:02 +00002841 }
Richard Smith745f5142012-01-27 01:14:48 +00002842
Richard Smithe24f5fc2011-11-17 22:56:20 +00002843 if (MemPtr.isDerivedMember()) {
2844 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002845 // The end of the derived-to-base path for the base object must match the
2846 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002847 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith8a66bf72013-06-03 05:03:02 +00002848 LV.Designator.Entries.size()) {
2849 Info.Diag(RHS);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002850 return 0;
Richard Smith8a66bf72013-06-03 05:03:02 +00002851 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002852 unsigned PathLengthToMember =
2853 LV.Designator.Entries.size() - MemPtr.Path.size();
2854 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
2855 const CXXRecordDecl *LVDecl = getAsBaseClass(
2856 LV.Designator.Entries[PathLengthToMember + I]);
2857 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith8a66bf72013-06-03 05:03:02 +00002858 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
2859 Info.Diag(RHS);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002860 return 0;
Richard Smith8a66bf72013-06-03 05:03:02 +00002861 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002862 }
2863
2864 // Truncate the lvalue to the appropriate derived class.
Richard Smith8a66bf72013-06-03 05:03:02 +00002865 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00002866 PathLengthToMember))
2867 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002868 } else if (!MemPtr.Path.empty()) {
2869 // Extend the LValue path with the member pointer's path.
2870 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
2871 MemPtr.Path.size() + IncludeMember);
2872
2873 // Walk down to the appropriate base class.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002874 if (const PointerType *PT = LVType->getAs<PointerType>())
2875 LVType = PT->getPointeeType();
2876 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
2877 assert(RD && "member pointer access on non-class-type expression");
2878 // The first class in the path is that of the lvalue.
2879 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
2880 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith8a66bf72013-06-03 05:03:02 +00002881 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
John McCall8d59dee2012-05-01 00:38:49 +00002882 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002883 RD = Base;
2884 }
2885 // Finally cast to the class containing the member.
Richard Smith8a66bf72013-06-03 05:03:02 +00002886 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
2887 MemPtr.getContainingRecord()))
John McCall8d59dee2012-05-01 00:38:49 +00002888 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002889 }
2890
2891 // Add the member. Note that we cannot build bound member functions here.
2892 if (IncludeMember) {
John McCall8d59dee2012-05-01 00:38:49 +00002893 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith8a66bf72013-06-03 05:03:02 +00002894 if (!HandleLValueMember(Info, RHS, LV, FD))
John McCall8d59dee2012-05-01 00:38:49 +00002895 return 0;
2896 } else if (const IndirectFieldDecl *IFD =
2897 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith8a66bf72013-06-03 05:03:02 +00002898 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
John McCall8d59dee2012-05-01 00:38:49 +00002899 return 0;
2900 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002901 llvm_unreachable("can't construct reference to bound member function");
John McCall8d59dee2012-05-01 00:38:49 +00002902 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002903 }
2904
2905 return MemPtr.getDecl();
2906}
2907
Richard Smith8a66bf72013-06-03 05:03:02 +00002908static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
2909 const BinaryOperator *BO,
2910 LValue &LV,
2911 bool IncludeMember = true) {
2912 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
2913
2914 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
2915 if (Info.keepEvaluatingAfterFailure()) {
2916 MemberPtr MemPtr;
2917 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
2918 }
2919 return 0;
2920 }
2921
2922 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
2923 BO->getRHS(), IncludeMember);
2924}
2925
Richard Smithe24f5fc2011-11-17 22:56:20 +00002926/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
2927/// the provided lvalue, which currently refers to the base object.
2928static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
2929 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002930 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002931 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002932 return false;
2933
Richard Smithb4e85ed2012-01-06 16:39:00 +00002934 QualType TargetQT = E->getType();
2935 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2936 TargetQT = PT->getPointeeType();
2937
2938 // Check this cast lands within the final derived-to-base subobject path.
2939 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002940 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002941 << D.MostDerivedType << TargetQT;
2942 return false;
2943 }
2944
Richard Smithe24f5fc2011-11-17 22:56:20 +00002945 // Check the type of the final cast. We don't need to check the path,
2946 // since a cast can only be formed if the path is unique.
2947 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002948 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2949 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002950 if (NewEntriesSize == D.MostDerivedPathLength)
2951 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2952 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00002953 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00002954 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002955 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002956 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002957 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002958 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002959
2960 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002961 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00002962}
2963
Mike Stumpc4c90452009-10-27 22:09:17 +00002964namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00002965enum EvalStmtResult {
2966 /// Evaluation failed.
2967 ESR_Failed,
2968 /// Hit a 'return' statement.
2969 ESR_Returned,
2970 /// Evaluation succeeded.
Richard Smithce617152013-05-06 05:56:11 +00002971 ESR_Succeeded,
2972 /// Hit a 'continue' statement.
2973 ESR_Continue,
2974 /// Hit a 'break' statement.
Richard Smith284b3cb2013-05-12 17:32:42 +00002975 ESR_Break,
2976 /// Still scanning for 'case' or 'default' statement.
2977 ESR_CaseNotFound
Richard Smithd0dccea2011-10-28 22:34:42 +00002978};
2979}
2980
Richard Smitha10b9782013-04-22 15:31:51 +00002981static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
2982 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2983 // We don't need to evaluate the initializer for a static local.
2984 if (!VD->hasLocalStorage())
2985 return true;
2986
2987 LValue Result;
2988 Result.set(VD, Info.CurrentCall->Index);
Richard Smith03ce5f82013-07-24 07:11:57 +00002989 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smitha10b9782013-04-22 15:31:51 +00002990
Richard Smith37a84f62013-06-20 03:00:05 +00002991 if (!VD->getInit()) {
2992 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
2993 << false << VD->getType();
2994 Val = APValue();
2995 return false;
2996 }
2997
Richard Smitha10b9782013-04-22 15:31:51 +00002998 if (!EvaluateInPlace(Val, Info, Result, VD->getInit())) {
2999 // Wipe out any partially-computed value, to allow tracking that this
3000 // evaluation failed.
3001 Val = APValue();
3002 return false;
3003 }
3004 }
3005
3006 return true;
3007}
3008
Richard Smithce617152013-05-06 05:56:11 +00003009/// Evaluate a condition (either a variable declaration or an expression).
3010static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3011 const Expr *Cond, bool &Result) {
Richard Smith03ce5f82013-07-24 07:11:57 +00003012 FullExpressionRAII Scope(Info);
Richard Smithce617152013-05-06 05:56:11 +00003013 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3014 return false;
3015 return EvaluateAsBooleanCondition(Cond, Result, Info);
3016}
3017
3018static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith284b3cb2013-05-12 17:32:42 +00003019 const Stmt *S, const SwitchCase *SC = 0);
Richard Smithce617152013-05-06 05:56:11 +00003020
3021/// Evaluate the body of a loop, and translate the result as appropriate.
3022static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
Richard Smith284b3cb2013-05-12 17:32:42 +00003023 const Stmt *Body,
3024 const SwitchCase *Case = 0) {
Richard Smith03ce5f82013-07-24 07:11:57 +00003025 BlockScopeRAII Scope(Info);
Richard Smith284b3cb2013-05-12 17:32:42 +00003026 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smithce617152013-05-06 05:56:11 +00003027 case ESR_Break:
3028 return ESR_Succeeded;
3029 case ESR_Succeeded:
3030 case ESR_Continue:
3031 return ESR_Continue;
3032 case ESR_Failed:
3033 case ESR_Returned:
Richard Smith284b3cb2013-05-12 17:32:42 +00003034 case ESR_CaseNotFound:
Richard Smithce617152013-05-06 05:56:11 +00003035 return ESR;
3036 }
Hans Wennborgdbce2c62013-05-06 15:13:34 +00003037 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smithce617152013-05-06 05:56:11 +00003038}
3039
Richard Smith284b3cb2013-05-12 17:32:42 +00003040/// Evaluate a switch statement.
3041static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
3042 const SwitchStmt *SS) {
Richard Smith03ce5f82013-07-24 07:11:57 +00003043 BlockScopeRAII Scope(Info);
3044
Richard Smith284b3cb2013-05-12 17:32:42 +00003045 // Evaluate the switch condition.
Richard Smith284b3cb2013-05-12 17:32:42 +00003046 APSInt Value;
Richard Smith03ce5f82013-07-24 07:11:57 +00003047 {
3048 FullExpressionRAII Scope(Info);
3049 if (SS->getConditionVariable() &&
3050 !EvaluateDecl(Info, SS->getConditionVariable()))
3051 return ESR_Failed;
3052 if (!EvaluateInteger(SS->getCond(), Value, Info))
3053 return ESR_Failed;
3054 }
Richard Smith284b3cb2013-05-12 17:32:42 +00003055
3056 // Find the switch case corresponding to the value of the condition.
3057 // FIXME: Cache this lookup.
3058 const SwitchCase *Found = 0;
3059 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3060 SC = SC->getNextSwitchCase()) {
3061 if (isa<DefaultStmt>(SC)) {
3062 Found = SC;
3063 continue;
3064 }
3065
3066 const CaseStmt *CS = cast<CaseStmt>(SC);
3067 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3068 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3069 : LHS;
3070 if (LHS <= Value && Value <= RHS) {
3071 Found = SC;
3072 break;
3073 }
3074 }
3075
3076 if (!Found)
3077 return ESR_Succeeded;
3078
3079 // Search the switch body for the switch case and evaluate it from there.
3080 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3081 case ESR_Break:
3082 return ESR_Succeeded;
3083 case ESR_Succeeded:
3084 case ESR_Continue:
3085 case ESR_Failed:
3086 case ESR_Returned:
3087 return ESR;
3088 case ESR_CaseNotFound:
Richard Smith37a84f62013-06-20 03:00:05 +00003089 // This can only happen if the switch case is nested within a statement
3090 // expression. We have no intention of supporting that.
3091 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3092 return ESR_Failed;
Richard Smith284b3cb2013-05-12 17:32:42 +00003093 }
Richard Smith1071b9f2013-05-13 20:33:30 +00003094 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith284b3cb2013-05-12 17:32:42 +00003095}
3096
Richard Smithd0dccea2011-10-28 22:34:42 +00003097// Evaluate a statement.
Richard Smith1aa0be82012-03-03 22:46:17 +00003098static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith284b3cb2013-05-12 17:32:42 +00003099 const Stmt *S, const SwitchCase *Case) {
Richard Smithe7565632013-05-08 02:12:03 +00003100 if (!Info.nextStep(S))
3101 return ESR_Failed;
3102
Richard Smith284b3cb2013-05-12 17:32:42 +00003103 // If we're hunting down a 'case' or 'default' label, recurse through
3104 // substatements until we hit the label.
3105 if (Case) {
3106 // FIXME: We don't start the lifetime of objects whose initialization we
3107 // jump over. However, such objects must be of class type with a trivial
3108 // default constructor that initialize all subobjects, so must be empty,
3109 // so this almost never matters.
3110 switch (S->getStmtClass()) {
3111 case Stmt::CompoundStmtClass:
3112 // FIXME: Precompute which substatement of a compound statement we
3113 // would jump to, and go straight there rather than performing a
3114 // linear scan each time.
3115 case Stmt::LabelStmtClass:
3116 case Stmt::AttributedStmtClass:
3117 case Stmt::DoStmtClass:
3118 break;
3119
3120 case Stmt::CaseStmtClass:
3121 case Stmt::DefaultStmtClass:
3122 if (Case == S)
3123 Case = 0;
3124 break;
3125
3126 case Stmt::IfStmtClass: {
3127 // FIXME: Precompute which side of an 'if' we would jump to, and go
3128 // straight there rather than scanning both sides.
3129 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith03ce5f82013-07-24 07:11:57 +00003130
3131 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3132 // preceded by our switch label.
3133 BlockScopeRAII Scope(Info);
3134
Richard Smith284b3cb2013-05-12 17:32:42 +00003135 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3136 if (ESR != ESR_CaseNotFound || !IS->getElse())
3137 return ESR;
3138 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3139 }
3140
3141 case Stmt::WhileStmtClass: {
3142 EvalStmtResult ESR =
3143 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3144 if (ESR != ESR_Continue)
3145 return ESR;
3146 break;
3147 }
3148
3149 case Stmt::ForStmtClass: {
3150 const ForStmt *FS = cast<ForStmt>(S);
3151 EvalStmtResult ESR =
3152 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3153 if (ESR != ESR_Continue)
3154 return ESR;
Richard Smith03ce5f82013-07-24 07:11:57 +00003155 if (FS->getInc()) {
3156 FullExpressionRAII IncScope(Info);
3157 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3158 return ESR_Failed;
3159 }
Richard Smith284b3cb2013-05-12 17:32:42 +00003160 break;
3161 }
3162
3163 case Stmt::DeclStmtClass:
3164 // FIXME: If the variable has initialization that can't be jumped over,
3165 // bail out of any immediately-surrounding compound-statement too.
3166 default:
3167 return ESR_CaseNotFound;
3168 }
3169 }
3170
Richard Smithd0dccea2011-10-28 22:34:42 +00003171 switch (S->getStmtClass()) {
3172 default:
Richard Smitha10b9782013-04-22 15:31:51 +00003173 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smitha10b9782013-04-22 15:31:51 +00003174 // Don't bother evaluating beyond an expression-statement which couldn't
3175 // be evaluated.
Richard Smith03ce5f82013-07-24 07:11:57 +00003176 FullExpressionRAII Scope(Info);
Richard Smithce617152013-05-06 05:56:11 +00003177 if (!EvaluateIgnoredValue(Info, E))
Richard Smitha10b9782013-04-22 15:31:51 +00003178 return ESR_Failed;
3179 return ESR_Succeeded;
3180 }
3181
3182 Info.Diag(S->getLocStart());
Richard Smithd0dccea2011-10-28 22:34:42 +00003183 return ESR_Failed;
3184
3185 case Stmt::NullStmtClass:
Richard Smithd0dccea2011-10-28 22:34:42 +00003186 return ESR_Succeeded;
3187
Richard Smitha10b9782013-04-22 15:31:51 +00003188 case Stmt::DeclStmtClass: {
3189 const DeclStmt *DS = cast<DeclStmt>(S);
3190 for (DeclStmt::const_decl_iterator DclIt = DS->decl_begin(),
Richard Smith03ce5f82013-07-24 07:11:57 +00003191 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
3192 // Each declaration initialization is its own full-expression.
3193 // FIXME: This isn't quite right; if we're performing aggregate
3194 // initialization, each braced subexpression is its own full-expression.
3195 FullExpressionRAII Scope(Info);
Richard Smitha10b9782013-04-22 15:31:51 +00003196 if (!EvaluateDecl(Info, *DclIt) && !Info.keepEvaluatingAfterFailure())
3197 return ESR_Failed;
Richard Smith03ce5f82013-07-24 07:11:57 +00003198 }
Richard Smitha10b9782013-04-22 15:31:51 +00003199 return ESR_Succeeded;
3200 }
3201
Richard Smithc1c5f272011-12-13 06:39:58 +00003202 case Stmt::ReturnStmtClass: {
Richard Smithc1c5f272011-12-13 06:39:58 +00003203 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith03ce5f82013-07-24 07:11:57 +00003204 FullExpressionRAII Scope(Info);
Richard Smitha10b9782013-04-22 15:31:51 +00003205 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smithc1c5f272011-12-13 06:39:58 +00003206 return ESR_Failed;
3207 return ESR_Returned;
3208 }
Richard Smithd0dccea2011-10-28 22:34:42 +00003209
3210 case Stmt::CompoundStmtClass: {
Richard Smith03ce5f82013-07-24 07:11:57 +00003211 BlockScopeRAII Scope(Info);
3212
Richard Smithd0dccea2011-10-28 22:34:42 +00003213 const CompoundStmt *CS = cast<CompoundStmt>(S);
3214 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
3215 BE = CS->body_end(); BI != BE; ++BI) {
Richard Smith284b3cb2013-05-12 17:32:42 +00003216 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI, Case);
3217 if (ESR == ESR_Succeeded)
3218 Case = 0;
3219 else if (ESR != ESR_CaseNotFound)
Richard Smithd0dccea2011-10-28 22:34:42 +00003220 return ESR;
3221 }
Richard Smith284b3cb2013-05-12 17:32:42 +00003222 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smithd0dccea2011-10-28 22:34:42 +00003223 }
Richard Smitha10b9782013-04-22 15:31:51 +00003224
3225 case Stmt::IfStmtClass: {
3226 const IfStmt *IS = cast<IfStmt>(S);
3227
3228 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith03ce5f82013-07-24 07:11:57 +00003229 BlockScopeRAII Scope(Info);
Richard Smitha10b9782013-04-22 15:31:51 +00003230 bool Cond;
Richard Smithce617152013-05-06 05:56:11 +00003231 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smitha10b9782013-04-22 15:31:51 +00003232 return ESR_Failed;
3233
3234 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3235 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3236 if (ESR != ESR_Succeeded)
3237 return ESR;
3238 }
3239 return ESR_Succeeded;
3240 }
Richard Smithce617152013-05-06 05:56:11 +00003241
3242 case Stmt::WhileStmtClass: {
3243 const WhileStmt *WS = cast<WhileStmt>(S);
3244 while (true) {
Richard Smith03ce5f82013-07-24 07:11:57 +00003245 BlockScopeRAII Scope(Info);
Richard Smithce617152013-05-06 05:56:11 +00003246 bool Continue;
3247 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3248 Continue))
3249 return ESR_Failed;
3250 if (!Continue)
3251 break;
3252
3253 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3254 if (ESR != ESR_Continue)
3255 return ESR;
3256 }
3257 return ESR_Succeeded;
3258 }
3259
3260 case Stmt::DoStmtClass: {
3261 const DoStmt *DS = cast<DoStmt>(S);
3262 bool Continue;
3263 do {
Richard Smith284b3cb2013-05-12 17:32:42 +00003264 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smithce617152013-05-06 05:56:11 +00003265 if (ESR != ESR_Continue)
3266 return ESR;
Richard Smith284b3cb2013-05-12 17:32:42 +00003267 Case = 0;
Richard Smithce617152013-05-06 05:56:11 +00003268
Richard Smith03ce5f82013-07-24 07:11:57 +00003269 FullExpressionRAII CondScope(Info);
Richard Smithce617152013-05-06 05:56:11 +00003270 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3271 return ESR_Failed;
3272 } while (Continue);
3273 return ESR_Succeeded;
3274 }
3275
3276 case Stmt::ForStmtClass: {
3277 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith03ce5f82013-07-24 07:11:57 +00003278 BlockScopeRAII Scope(Info);
Richard Smithce617152013-05-06 05:56:11 +00003279 if (FS->getInit()) {
3280 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3281 if (ESR != ESR_Succeeded)
3282 return ESR;
3283 }
3284 while (true) {
Richard Smith03ce5f82013-07-24 07:11:57 +00003285 BlockScopeRAII Scope(Info);
Richard Smithce617152013-05-06 05:56:11 +00003286 bool Continue = true;
3287 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3288 FS->getCond(), Continue))
3289 return ESR_Failed;
3290 if (!Continue)
3291 break;
3292
3293 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3294 if (ESR != ESR_Continue)
3295 return ESR;
3296
Richard Smith03ce5f82013-07-24 07:11:57 +00003297 if (FS->getInc()) {
3298 FullExpressionRAII IncScope(Info);
3299 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3300 return ESR_Failed;
3301 }
Richard Smithce617152013-05-06 05:56:11 +00003302 }
3303 return ESR_Succeeded;
3304 }
3305
Richard Smith692eafd2013-05-06 06:51:17 +00003306 case Stmt::CXXForRangeStmtClass: {
3307 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith03ce5f82013-07-24 07:11:57 +00003308 BlockScopeRAII Scope(Info);
Richard Smith692eafd2013-05-06 06:51:17 +00003309
3310 // Initialize the __range variable.
3311 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3312 if (ESR != ESR_Succeeded)
3313 return ESR;
3314
3315 // Create the __begin and __end iterators.
3316 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3317 if (ESR != ESR_Succeeded)
3318 return ESR;
3319
3320 while (true) {
3321 // Condition: __begin != __end.
Richard Smith03ce5f82013-07-24 07:11:57 +00003322 {
3323 bool Continue = true;
3324 FullExpressionRAII CondExpr(Info);
3325 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3326 return ESR_Failed;
3327 if (!Continue)
3328 break;
3329 }
Richard Smith692eafd2013-05-06 06:51:17 +00003330
3331 // User's variable declaration, initialized by *__begin.
Richard Smith03ce5f82013-07-24 07:11:57 +00003332 BlockScopeRAII InnerScope(Info);
Richard Smith692eafd2013-05-06 06:51:17 +00003333 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3334 if (ESR != ESR_Succeeded)
3335 return ESR;
3336
3337 // Loop body.
3338 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3339 if (ESR != ESR_Continue)
3340 return ESR;
3341
3342 // Increment: ++__begin
3343 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3344 return ESR_Failed;
3345 }
3346
3347 return ESR_Succeeded;
3348 }
3349
Richard Smith284b3cb2013-05-12 17:32:42 +00003350 case Stmt::SwitchStmtClass:
3351 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3352
Richard Smithce617152013-05-06 05:56:11 +00003353 case Stmt::ContinueStmtClass:
3354 return ESR_Continue;
3355
3356 case Stmt::BreakStmtClass:
3357 return ESR_Break;
Richard Smith284b3cb2013-05-12 17:32:42 +00003358
3359 case Stmt::LabelStmtClass:
3360 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3361
3362 case Stmt::AttributedStmtClass:
3363 // As a general principle, C++11 attributes can be ignored without
3364 // any semantic impact.
3365 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3366 Case);
3367
3368 case Stmt::CaseStmtClass:
3369 case Stmt::DefaultStmtClass:
3370 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smithd0dccea2011-10-28 22:34:42 +00003371 }
3372}
3373
Richard Smith61802452011-12-22 02:22:31 +00003374/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3375/// default constructor. If so, we'll fold it whether or not it's marked as
3376/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3377/// so we need special handling.
3378static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00003379 const CXXConstructorDecl *CD,
3380 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00003381 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3382 return false;
3383
Richard Smith4c3fc9b2012-01-18 05:21:49 +00003384 // Value-initialization does not call a trivial default constructor, so such a
3385 // call is a core constant expression whether or not the constructor is
3386 // constexpr.
3387 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003388 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00003389 // FIXME: If DiagDecl is an implicitly-declared special member function,
3390 // we should be much more explicit about why it's not constexpr.
3391 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3392 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3393 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00003394 } else {
3395 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3396 }
3397 }
3398 return true;
3399}
3400
Richard Smithc1c5f272011-12-13 06:39:58 +00003401/// CheckConstexprFunction - Check that a function can be called in a constant
3402/// expression.
3403static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3404 const FunctionDecl *Declaration,
3405 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00003406 // Potential constant expressions can contain calls to declared, but not yet
3407 // defined, constexpr functions.
3408 if (Info.CheckingPotentialConstantExpression && !Definition &&
3409 Declaration->isConstexpr())
3410 return false;
3411
Richard Smithf039e3e2013-05-14 05:18:44 +00003412 // Bail out with no diagnostic if the function declaration itself is invalid.
3413 // We will have produced a relevant diagnostic while parsing it.
3414 if (Declaration->isInvalidDecl())
3415 return false;
3416
Richard Smithc1c5f272011-12-13 06:39:58 +00003417 // Can we evaluate this function call?
3418 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3419 return true;
3420
Richard Smith80ad52f2013-01-02 11:42:31 +00003421 if (Info.getLangOpts().CPlusPlus11) {
Richard Smithc1c5f272011-12-13 06:39:58 +00003422 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00003423 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3424 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00003425 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3426 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3427 << DiagDecl;
3428 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3429 } else {
3430 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3431 }
3432 return false;
3433}
3434
Richard Smith180f4792011-11-10 06:34:14 +00003435namespace {
Richard Smith1aa0be82012-03-03 22:46:17 +00003436typedef SmallVector<APValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00003437}
3438
3439/// EvaluateArgs - Evaluate the arguments to a function call.
3440static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3441 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00003442 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003443 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00003444 I != E; ++I) {
3445 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3446 // If we're checking for a potential constant expression, evaluate all
3447 // initializers even if some of them fail.
3448 if (!Info.keepEvaluatingAfterFailure())
3449 return false;
3450 Success = false;
3451 }
3452 }
3453 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003454}
3455
Richard Smithd0dccea2011-10-28 22:34:42 +00003456/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00003457static bool HandleFunctionCall(SourceLocation CallLoc,
3458 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00003459 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith1aa0be82012-03-03 22:46:17 +00003460 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00003461 ArgVector ArgValues(Args.size());
3462 if (!EvaluateArgs(Args, ArgValues, Info))
3463 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00003464
Richard Smith745f5142012-01-27 01:14:48 +00003465 if (!Info.CheckCallLimit(CallLoc))
3466 return false;
3467
3468 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smitha8942d72013-05-07 03:19:20 +00003469
3470 // For a trivial copy or move assignment, perform an APValue copy. This is
3471 // essential for unions, where the operations performed by the assignment
3472 // operator cannot be represented as statements.
3473 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3474 if (MD && MD->isDefaulted() && MD->isTrivial()) {
3475 assert(This &&
3476 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3477 LValue RHS;
3478 RHS.setFrom(Info.Ctx, ArgValues[0]);
3479 APValue RHSValue;
3480 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3481 RHS, RHSValue))
3482 return false;
3483 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3484 RHSValue))
3485 return false;
3486 This->moveInto(Result);
3487 return true;
3488 }
3489
Richard Smitha10b9782013-04-22 15:31:51 +00003490 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smithbebf5b12013-04-26 14:36:30 +00003491 if (ESR == ESR_Succeeded) {
3492 if (Callee->getResultType()->isVoidType())
3493 return true;
Richard Smitha10b9782013-04-22 15:31:51 +00003494 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smithbebf5b12013-04-26 14:36:30 +00003495 }
Richard Smitha10b9782013-04-22 15:31:51 +00003496 return ESR == ESR_Returned;
Richard Smithd0dccea2011-10-28 22:34:42 +00003497}
3498
Richard Smith180f4792011-11-10 06:34:14 +00003499/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00003500static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00003501 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00003502 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00003503 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00003504 ArgVector ArgValues(Args.size());
3505 if (!EvaluateArgs(Args, ArgValues, Info))
3506 return false;
3507
Richard Smith745f5142012-01-27 01:14:48 +00003508 if (!Info.CheckCallLimit(CallLoc))
3509 return false;
3510
Richard Smith86c3ae42012-02-13 03:54:03 +00003511 const CXXRecordDecl *RD = Definition->getParent();
3512 if (RD->getNumVBases()) {
3513 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3514 return false;
3515 }
3516
Richard Smith745f5142012-01-27 01:14:48 +00003517 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00003518
3519 // If it's a delegating constructor, just delegate.
3520 if (Definition->isDelegatingConstructor()) {
3521 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smitha10b9782013-04-22 15:31:51 +00003522 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3523 return false;
3524 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smith180f4792011-11-10 06:34:14 +00003525 }
3526
Richard Smith610a60c2012-01-10 04:32:03 +00003527 // For a trivial copy or move constructor, perform an APValue copy. This is
3528 // essential for unions, where the operations performed by the constructor
3529 // cannot be represented by ctor-initializers.
Richard Smith610a60c2012-01-10 04:32:03 +00003530 if (Definition->isDefaulted() &&
Douglas Gregorf6cfe8b2012-02-24 07:55:51 +00003531 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3532 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith610a60c2012-01-10 04:32:03 +00003533 LValue RHS;
Richard Smith1aa0be82012-03-03 22:46:17 +00003534 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5528ac92013-05-05 23:31:59 +00003535 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith1aa0be82012-03-03 22:46:17 +00003536 RHS, Result);
Richard Smith610a60c2012-01-10 04:32:03 +00003537 }
3538
3539 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00003540 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00003541 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3542 std::distance(RD->field_begin(), RD->field_end()));
3543
John McCall8d59dee2012-05-01 00:38:49 +00003544 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00003545 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3546
Richard Smith03ce5f82013-07-24 07:11:57 +00003547 // A scope for temporaries lifetime-extended by reference members.
3548 BlockScopeRAII LifetimeExtendedScope(Info);
3549
Richard Smith745f5142012-01-27 01:14:48 +00003550 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003551 unsigned BasesSeen = 0;
3552#ifndef NDEBUG
3553 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3554#endif
3555 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
3556 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00003557 LValue Subobject = This;
3558 APValue *Value = &Result;
3559
3560 // Determine the subobject to initialize.
Richard Smith3835a4e2013-08-06 07:09:20 +00003561 FieldDecl *FD = 0;
Richard Smith180f4792011-11-10 06:34:14 +00003562 if ((*I)->isBaseInitializer()) {
3563 QualType BaseType((*I)->getBaseClass(), 0);
3564#ifndef NDEBUG
3565 // Non-virtual base classes are initialized in the order in the class
Richard Smith86c3ae42012-02-13 03:54:03 +00003566 // definition. We have already checked for virtual base classes.
Richard Smith180f4792011-11-10 06:34:14 +00003567 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3568 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3569 "base class initializers not in expected order");
3570 ++BaseIt;
3571#endif
John McCall8d59dee2012-05-01 00:38:49 +00003572 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
3573 BaseType->getAsCXXRecordDecl(), &Layout))
3574 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003575 Value = &Result.getStructBase(BasesSeen++);
Richard Smith3835a4e2013-08-06 07:09:20 +00003576 } else if ((FD = (*I)->getMember())) {
John McCall8d59dee2012-05-01 00:38:49 +00003577 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
3578 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003579 if (RD->isUnion()) {
3580 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00003581 Value = &Result.getUnionValue();
3582 } else {
3583 Value = &Result.getStructField(FD->getFieldIndex());
3584 }
Richard Smithd9b02e72012-01-25 22:15:11 +00003585 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00003586 // Walk the indirect field decl's chain to find the object to initialize,
3587 // and make sure we've initialized every step along it.
3588 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
3589 CE = IFD->chain_end();
3590 C != CE; ++C) {
Richard Smith3835a4e2013-08-06 07:09:20 +00003591 FD = cast<FieldDecl>(*C);
Richard Smithd9b02e72012-01-25 22:15:11 +00003592 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3593 // Switch the union field if it differs. This happens if we had
3594 // preceding zero-initialization, and we're now initializing a union
3595 // subobject other than the first.
3596 // FIXME: In this case, the values of the other subobjects are
3597 // specified, since zero-initialization sets all padding bits to zero.
3598 if (Value->isUninit() ||
3599 (Value->isUnion() && Value->getUnionField() != FD)) {
3600 if (CD->isUnion())
3601 *Value = APValue(FD);
3602 else
3603 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
3604 std::distance(CD->field_begin(), CD->field_end()));
3605 }
John McCall8d59dee2012-05-01 00:38:49 +00003606 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
3607 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00003608 if (CD->isUnion())
3609 Value = &Value->getUnionValue();
3610 else
3611 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00003612 }
Richard Smith180f4792011-11-10 06:34:14 +00003613 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00003614 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00003615 }
Richard Smith745f5142012-01-27 01:14:48 +00003616
Richard Smith03ce5f82013-07-24 07:11:57 +00003617 FullExpressionRAII InitScope(Info);
Richard Smith3835a4e2013-08-06 07:09:20 +00003618 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit()) ||
3619 (FD && FD->isBitField() && !truncateBitfieldValue(Info, (*I)->getInit(),
3620 *Value, FD))) {
Richard Smith745f5142012-01-27 01:14:48 +00003621 // If we're checking for a potential constant expression, evaluate all
3622 // initializers even if some of them fail.
3623 if (!Info.keepEvaluatingAfterFailure())
3624 return false;
3625 Success = false;
3626 }
Richard Smith180f4792011-11-10 06:34:14 +00003627 }
3628
Richard Smitha10b9782013-04-22 15:31:51 +00003629 return Success &&
3630 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smith180f4792011-11-10 06:34:14 +00003631}
3632
Eli Friedman4efaa272008-11-12 09:44:48 +00003633//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003634// Generic Evaluation
3635//===----------------------------------------------------------------------===//
3636namespace {
3637
Richard Smithf48fdb02011-12-09 22:58:01 +00003638// FIXME: RetTy is always bool. Remove it.
3639template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003640class ExprEvaluatorBase
3641 : public ConstStmtVisitor<Derived, RetTy> {
3642private:
Richard Smith1aa0be82012-03-03 22:46:17 +00003643 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003644 return static_cast<Derived*>(this)->Success(V, E);
3645 }
Richard Smith51201882011-12-30 21:15:51 +00003646 RetTy DerivedZeroInitialization(const Expr *E) {
3647 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00003648 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003649
Richard Smith74e1ad92012-02-16 02:46:34 +00003650 // Check whether a conditional operator with a non-constant condition is a
3651 // potential constant expression. If neither arm is a potential constant
3652 // expression, then the conditional operator is not either.
3653 template<typename ConditionalOperator>
3654 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
3655 assert(Info.CheckingPotentialConstantExpression);
3656
3657 // Speculatively evaluate both arms.
3658 {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003659 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith74e1ad92012-02-16 02:46:34 +00003660 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3661
3662 StmtVisitorTy::Visit(E->getFalseExpr());
3663 if (Diag.empty())
3664 return;
3665
3666 Diag.clear();
3667 StmtVisitorTy::Visit(E->getTrueExpr());
3668 if (Diag.empty())
3669 return;
3670 }
3671
3672 Error(E, diag::note_constexpr_conditional_never_const);
3673 }
3674
3675
3676 template<typename ConditionalOperator>
3677 bool HandleConditionalOperator(const ConditionalOperator *E) {
3678 bool BoolResult;
3679 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
3680 if (Info.CheckingPotentialConstantExpression)
3681 CheckPotentialConstantConditional(E);
3682 return false;
3683 }
3684
3685 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3686 return StmtVisitorTy::Visit(EvalExpr);
3687 }
3688
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003689protected:
3690 EvalInfo &Info;
3691 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
3692 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3693
Richard Smithdd1f29b2011-12-12 09:28:41 +00003694 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00003695 return Info.CCEDiag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00003696 }
3697
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003698 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
3699
3700public:
3701 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3702
3703 EvalInfo &getEvalInfo() { return Info; }
3704
Richard Smithf48fdb02011-12-09 22:58:01 +00003705 /// Report an evaluation error. This should only be called when an error is
3706 /// first discovered. When propagating an error, just return false.
3707 bool Error(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00003708 Info.Diag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00003709 return false;
3710 }
3711 bool Error(const Expr *E) {
3712 return Error(E, diag::note_invalid_subexpr_in_const_expr);
3713 }
3714
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003715 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003716 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003717 }
3718 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00003719 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003720 }
3721
3722 RetTy VisitParenExpr(const ParenExpr *E)
3723 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3724 RetTy VisitUnaryExtension(const UnaryOperator *E)
3725 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3726 RetTy VisitUnaryPlus(const UnaryOperator *E)
3727 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3728 RetTy VisitChooseExpr(const ChooseExpr *E)
Eli Friedmana5e66012013-07-20 00:40:58 +00003729 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003730 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
3731 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00003732 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
3733 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00003734 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
3735 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithc3bf52c2013-04-20 22:23:05 +00003736 RetTy VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
3737 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00003738 // We cannot create any objects for which cleanups are required, so there is
3739 // nothing to do here; all cleanups must come from unevaluated subexpressions.
3740 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
3741 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003742
Richard Smithc216a012011-12-12 12:46:16 +00003743 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
3744 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3745 return static_cast<Derived*>(this)->VisitCastExpr(E);
3746 }
3747 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
3748 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3749 return static_cast<Derived*>(this)->VisitCastExpr(E);
3750 }
3751
Richard Smithe24f5fc2011-11-17 22:56:20 +00003752 RetTy VisitBinaryOperator(const BinaryOperator *E) {
3753 switch (E->getOpcode()) {
3754 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00003755 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003756
3757 case BO_Comma:
3758 VisitIgnoredValue(E->getLHS());
3759 return StmtVisitorTy::Visit(E->getRHS());
3760
3761 case BO_PtrMemD:
3762 case BO_PtrMemI: {
3763 LValue Obj;
3764 if (!HandleMemberPointerAccess(Info, E, Obj))
3765 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00003766 APValue Result;
Richard Smith5528ac92013-05-05 23:31:59 +00003767 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00003768 return false;
3769 return DerivedSuccess(Result, E);
3770 }
3771 }
3772 }
3773
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003774 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smithe92b1f42012-06-26 08:12:11 +00003775 // Evaluate and cache the common expression. We treat it as a temporary,
3776 // even though it's not quite the same thing.
Richard Smith03ce5f82013-07-24 07:11:57 +00003777 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smithe92b1f42012-06-26 08:12:11 +00003778 Info, E->getCommon()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003779 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003780
Richard Smith74e1ad92012-02-16 02:46:34 +00003781 return HandleConditionalOperator(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003782 }
3783
3784 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00003785 bool IsBcpCall = false;
3786 // If the condition (ignoring parens) is a __builtin_constant_p call,
3787 // the result is a constant expression if it can be folded without
3788 // side-effects. This is an important GNU extension. See GCC PR38377
3789 // for discussion.
3790 if (const CallExpr *CallCE =
3791 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
3792 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
3793 IsBcpCall = true;
3794
3795 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3796 // constant expression; we can't check whether it's potentially foldable.
3797 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
3798 return false;
3799
3800 FoldConstant Fold(Info);
3801
Richard Smith74e1ad92012-02-16 02:46:34 +00003802 if (!HandleConditionalOperator(E))
Richard Smithf15fda02012-02-02 01:16:57 +00003803 return false;
3804
3805 if (IsBcpCall)
3806 Fold.Fold(Info);
3807
3808 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003809 }
3810
3811 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith03ce5f82013-07-24 07:11:57 +00003812 if (APValue *Value = Info.CurrentCall->getTemporary(E))
3813 return DerivedSuccess(*Value, E);
3814
3815 const Expr *Source = E->getSourceExpr();
3816 if (!Source)
3817 return Error(E);
3818 if (Source == E) { // sanity checking.
3819 assert(0 && "OpaqueValueExpr recursively refers to itself");
3820 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00003821 }
Richard Smith03ce5f82013-07-24 07:11:57 +00003822 return StmtVisitorTy::Visit(Source);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003823 }
Richard Smithf10d9172011-10-11 21:43:33 +00003824
Richard Smithd0dccea2011-10-28 22:34:42 +00003825 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003826 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00003827 QualType CalleeType = Callee->getType();
3828
Richard Smithd0dccea2011-10-28 22:34:42 +00003829 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00003830 LValue *This = 0, ThisVal;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003831 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith86c3ae42012-02-13 03:54:03 +00003832 bool HasQualifier = false;
Richard Smith6c957872011-11-10 09:31:24 +00003833
Richard Smith59efe262011-11-11 04:05:33 +00003834 // Extract function decl and 'this' pointer from the callee.
3835 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00003836 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003837 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3838 // Explicit bound member calls, such as x.f() or p->g();
3839 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00003840 return false;
3841 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00003842 This = &ThisVal;
Richard Smith86c3ae42012-02-13 03:54:03 +00003843 HasQualifier = ME->hasQualifier();
Richard Smithe24f5fc2011-11-17 22:56:20 +00003844 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
3845 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00003846 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
3847 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003848 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003849 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00003850 return Error(Callee);
3851
3852 FD = dyn_cast<FunctionDecl>(Member);
3853 if (!FD)
3854 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00003855 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003856 LValue Call;
3857 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003858 return false;
Richard Smith59efe262011-11-11 04:05:33 +00003859
Richard Smithb4e85ed2012-01-06 16:39:00 +00003860 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00003861 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003862 FD = dyn_cast_or_null<FunctionDecl>(
3863 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00003864 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00003865 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00003866
3867 // Overloaded operator calls to member functions are represented as normal
3868 // calls with '*this' as the first argument.
3869 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
3870 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00003871 // FIXME: When selecting an implicit conversion for an overloaded
3872 // operator delete, we sometimes try to evaluate calls to conversion
3873 // operators without a 'this' parameter!
3874 if (Args.empty())
3875 return Error(E);
3876
Richard Smith59efe262011-11-11 04:05:33 +00003877 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
3878 return false;
3879 This = &ThisVal;
3880 Args = Args.slice(1);
3881 }
3882
3883 // Don't call function pointers which have been cast to some other type.
3884 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003885 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00003886 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00003887 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00003888
Richard Smithb04035a2012-02-01 02:39:43 +00003889 if (This && !This->checkSubobject(Info, E, CSK_This))
3890 return false;
3891
Richard Smith86c3ae42012-02-13 03:54:03 +00003892 // DR1358 allows virtual constexpr functions in some cases. Don't allow
3893 // calls to such functions in constant expressions.
3894 if (This && !HasQualifier &&
3895 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
3896 return Error(E, diag::note_constexpr_virtual_call);
3897
Richard Smithc1c5f272011-12-13 06:39:58 +00003898 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00003899 Stmt *Body = FD->getBody(Definition);
Richard Smith1aa0be82012-03-03 22:46:17 +00003900 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00003901
Richard Smithc1c5f272011-12-13 06:39:58 +00003902 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00003903 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
3904 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00003905 return false;
3906
Richard Smith83587db2012-02-15 02:18:13 +00003907 return DerivedSuccess(Result, E);
Richard Smithd0dccea2011-10-28 22:34:42 +00003908 }
3909
Richard Smithc49bd112011-10-28 17:51:58 +00003910 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
3911 return StmtVisitorTy::Visit(E->getInitializer());
3912 }
Richard Smithf10d9172011-10-11 21:43:33 +00003913 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00003914 if (E->getNumInits() == 0)
3915 return DerivedZeroInitialization(E);
3916 if (E->getNumInits() == 1)
3917 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00003918 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00003919 }
3920 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00003921 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00003922 }
3923 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00003924 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00003925 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00003926 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00003927 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003928 }
Richard Smithf10d9172011-10-11 21:43:33 +00003929
Richard Smith180f4792011-11-10 06:34:14 +00003930 /// A member expression where the object is a prvalue is itself a prvalue.
3931 RetTy VisitMemberExpr(const MemberExpr *E) {
3932 assert(!E->isArrow() && "missing call to bound member function?");
3933
Richard Smith1aa0be82012-03-03 22:46:17 +00003934 APValue Val;
Richard Smith180f4792011-11-10 06:34:14 +00003935 if (!Evaluate(Val, Info, E->getBase()))
3936 return false;
3937
3938 QualType BaseTy = E->getBase()->getType();
3939
3940 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00003941 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003942 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek890f0f12012-08-23 20:46:57 +00003943 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smith180f4792011-11-10 06:34:14 +00003944 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3945
Richard Smithb476a142013-05-05 21:17:10 +00003946 CompleteObject Obj(&Val, BaseTy);
Richard Smithb4e85ed2012-01-06 16:39:00 +00003947 SubobjectDesignator Designator(BaseTy);
3948 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00003949
Richard Smithb476a142013-05-05 21:17:10 +00003950 APValue Result;
3951 return extractSubobject(Info, E, Obj, Designator, Result) &&
3952 DerivedSuccess(Result, E);
Richard Smith180f4792011-11-10 06:34:14 +00003953 }
3954
Richard Smithc49bd112011-10-28 17:51:58 +00003955 RetTy VisitCastExpr(const CastExpr *E) {
3956 switch (E->getCastKind()) {
3957 default:
3958 break;
3959
Richard Smith5705f212013-05-23 00:30:41 +00003960 case CK_AtomicToNonAtomic: {
3961 APValue AtomicVal;
3962 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
3963 return false;
3964 return DerivedSuccess(AtomicVal, E);
3965 }
3966
Richard Smithc49bd112011-10-28 17:51:58 +00003967 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00003968 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00003969 return StmtVisitorTy::Visit(E->getSubExpr());
3970
3971 case CK_LValueToRValue: {
3972 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00003973 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
3974 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00003975 APValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00003976 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith5528ac92013-05-05 23:31:59 +00003977 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smith9ec71972012-02-05 01:23:16 +00003978 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00003979 return false;
3980 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00003981 }
3982 }
3983
Richard Smithf48fdb02011-12-09 22:58:01 +00003984 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00003985 }
3986
Richard Smith5528ac92013-05-05 23:31:59 +00003987 RetTy VisitUnaryPostInc(const UnaryOperator *UO) {
3988 return VisitUnaryPostIncDec(UO);
3989 }
3990 RetTy VisitUnaryPostDec(const UnaryOperator *UO) {
3991 return VisitUnaryPostIncDec(UO);
3992 }
3993 RetTy VisitUnaryPostIncDec(const UnaryOperator *UO) {
3994 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
3995 return Error(UO);
3996
3997 LValue LVal;
3998 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
3999 return false;
4000 APValue RVal;
4001 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4002 UO->isIncrementOp(), &RVal))
4003 return false;
4004 return DerivedSuccess(RVal, UO);
4005 }
4006
Richard Smith37a84f62013-06-20 03:00:05 +00004007 RetTy VisitStmtExpr(const StmtExpr *E) {
4008 // We will have checked the full-expressions inside the statement expression
4009 // when they were completed, and don't need to check them again now.
4010 if (Info.getIntOverflowCheckMode())
4011 return Error(E);
4012
Richard Smith03ce5f82013-07-24 07:11:57 +00004013 BlockScopeRAII Scope(Info);
Richard Smith37a84f62013-06-20 03:00:05 +00004014 const CompoundStmt *CS = E->getSubStmt();
4015 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4016 BE = CS->body_end();
4017 /**/; ++BI) {
4018 if (BI + 1 == BE) {
4019 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4020 if (!FinalExpr) {
4021 Info.Diag((*BI)->getLocStart(),
4022 diag::note_constexpr_stmt_expr_unsupported);
4023 return false;
4024 }
4025 return this->Visit(FinalExpr);
4026 }
4027
4028 APValue ReturnValue;
4029 EvalStmtResult ESR = EvaluateStmt(ReturnValue, Info, *BI);
4030 if (ESR != ESR_Succeeded) {
4031 // FIXME: If the statement-expression terminated due to 'return',
4032 // 'break', or 'continue', it would be nice to propagate that to
4033 // the outer statement evaluation rather than bailing out.
4034 if (ESR != ESR_Failed)
4035 Info.Diag((*BI)->getLocStart(),
4036 diag::note_constexpr_stmt_expr_unsupported);
4037 return false;
4038 }
4039 }
4040 }
4041
Richard Smith8327fad2011-10-24 18:44:57 +00004042 /// Visit a value which is evaluated, but whose value is ignored.
4043 void VisitIgnoredValue(const Expr *E) {
Richard Smitha10b9782013-04-22 15:31:51 +00004044 EvaluateIgnoredValue(Info, E);
Richard Smith8327fad2011-10-24 18:44:57 +00004045 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004046};
4047
4048}
4049
4050//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00004051// Common base class for lvalue and temporary evaluation.
4052//===----------------------------------------------------------------------===//
4053namespace {
4054template<class Derived>
4055class LValueExprEvaluatorBase
4056 : public ExprEvaluatorBase<Derived, bool> {
4057protected:
4058 LValue &Result;
4059 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4060 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
4061
4062 bool Success(APValue::LValueBase B) {
4063 Result.set(B);
4064 return true;
4065 }
4066
4067public:
4068 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4069 ExprEvaluatorBaseTy(Info), Result(Result) {}
4070
Richard Smith1aa0be82012-03-03 22:46:17 +00004071 bool Success(const APValue &V, const Expr *E) {
4072 Result.setFrom(this->Info.Ctx, V);
Richard Smithe24f5fc2011-11-17 22:56:20 +00004073 return true;
4074 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00004075
Richard Smithe24f5fc2011-11-17 22:56:20 +00004076 bool VisitMemberExpr(const MemberExpr *E) {
4077 // Handle non-static data members.
4078 QualType BaseTy;
4079 if (E->isArrow()) {
4080 if (!EvaluatePointer(E->getBase(), Result, this->Info))
4081 return false;
Ted Kremenek890f0f12012-08-23 20:46:57 +00004082 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00004083 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00004084 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00004085 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
4086 return false;
4087 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00004088 } else {
4089 if (!this->Visit(E->getBase()))
4090 return false;
4091 BaseTy = E->getBase()->getType();
4092 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00004093
Richard Smithd9b02e72012-01-25 22:15:11 +00004094 const ValueDecl *MD = E->getMemberDecl();
4095 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4096 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4097 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4098 (void)BaseTy;
John McCall8d59dee2012-05-01 00:38:49 +00004099 if (!HandleLValueMember(this->Info, E, Result, FD))
4100 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00004101 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCall8d59dee2012-05-01 00:38:49 +00004102 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4103 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00004104 } else
4105 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00004106
Richard Smithd9b02e72012-01-25 22:15:11 +00004107 if (MD->getType()->isReferenceType()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00004108 APValue RefValue;
Richard Smith5528ac92013-05-05 23:31:59 +00004109 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00004110 RefValue))
4111 return false;
4112 return Success(RefValue, E);
4113 }
4114 return true;
4115 }
4116
4117 bool VisitBinaryOperator(const BinaryOperator *E) {
4118 switch (E->getOpcode()) {
4119 default:
4120 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4121
4122 case BO_PtrMemD:
4123 case BO_PtrMemI:
4124 return HandleMemberPointerAccess(this->Info, E, Result);
4125 }
4126 }
4127
4128 bool VisitCastExpr(const CastExpr *E) {
4129 switch (E->getCastKind()) {
4130 default:
4131 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4132
4133 case CK_DerivedToBase:
Richard Smith8a66bf72013-06-03 05:03:02 +00004134 case CK_UncheckedDerivedToBase:
Richard Smithe24f5fc2011-11-17 22:56:20 +00004135 if (!this->Visit(E->getSubExpr()))
4136 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00004137
4138 // Now figure out the necessary offset to add to the base LV to get from
4139 // the derived class to the base class.
Richard Smith8a66bf72013-06-03 05:03:02 +00004140 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4141 Result);
Richard Smithe24f5fc2011-11-17 22:56:20 +00004142 }
4143 }
4144};
4145}
4146
4147//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00004148// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00004149//
4150// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4151// function designators (in C), decl references to void objects (in C), and
4152// temporaries (if building with -Wno-address-of-temporary).
4153//
4154// LValue evaluation produces values comprising a base expression of one of the
4155// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004156// - Declarations
4157// * VarDecl
4158// * FunctionDecl
4159// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00004160// * CompoundLiteralExpr in C
4161// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00004162// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00004163// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00004164// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00004165// * ObjCEncodeExpr
4166// * AddrLabelExpr
4167// * BlockExpr
4168// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004169// - Locals and temporaries
Richard Smith8a66bf72013-06-03 05:03:02 +00004170// * MaterializeTemporaryExpr
Richard Smith83587db2012-02-15 02:18:13 +00004171// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith8a66bf72013-06-03 05:03:02 +00004172// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4173// from the AST (FIXME).
Richard Smith211c8dd2013-06-05 00:46:14 +00004174// * A MaterializeTemporaryExpr that has static storage duration, with no
4175// CallIndex, for a lifetime-extended temporary.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004176// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00004177//===----------------------------------------------------------------------===//
4178namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004179class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00004180 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00004181public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00004182 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4183 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00004184
Richard Smithc49bd112011-10-28 17:51:58 +00004185 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith5528ac92013-05-05 23:31:59 +00004186 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smithc49bd112011-10-28 17:51:58 +00004187
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004188 bool VisitDeclRefExpr(const DeclRefExpr *E);
4189 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00004190 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004191 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4192 bool VisitMemberExpr(const MemberExpr *E);
4193 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4194 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00004195 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichete275a182012-04-16 04:08:35 +00004196 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004197 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4198 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith86024012012-02-18 22:04:06 +00004199 bool VisitUnaryReal(const UnaryOperator *E);
4200 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith5528ac92013-05-05 23:31:59 +00004201 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4202 return VisitUnaryPreIncDec(UO);
4203 }
4204 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4205 return VisitUnaryPreIncDec(UO);
4206 }
Richard Smithb476a142013-05-05 21:17:10 +00004207 bool VisitBinAssign(const BinaryOperator *BO);
4208 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlsson26bc2202009-10-03 16:30:22 +00004209
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004210 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00004211 switch (E->getCastKind()) {
4212 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00004213 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00004214
Eli Friedmandb924222011-10-11 00:13:24 +00004215 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00004216 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00004217 if (!Visit(E->getSubExpr()))
4218 return false;
4219 Result.Designator.setInvalid();
4220 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00004221
Richard Smithe24f5fc2011-11-17 22:56:20 +00004222 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00004223 if (!Visit(E->getSubExpr()))
4224 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00004225 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00004226 }
4227 }
Eli Friedman4efaa272008-11-12 09:44:48 +00004228};
4229} // end anonymous namespace
4230
Richard Smithc49bd112011-10-28 17:51:58 +00004231/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smitha07a6c32013-05-01 19:00:39 +00004232/// expressions which are not glvalues, in two cases:
4233/// * function designators in C, and
4234/// * "extern void" objects
4235static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4236 assert(E->isGLValue() || E->getType()->isFunctionType() ||
4237 E->getType()->isVoidType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004238 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004239}
4240
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004241bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004242 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
4243 return Success(FD);
4244 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00004245 return VisitVarDecl(E, VD);
4246 return Error(E);
4247}
Richard Smith436c8892011-10-24 23:14:33 +00004248
Richard Smithc49bd112011-10-28 17:51:58 +00004249bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithb476a142013-05-05 21:17:10 +00004250 CallStackFrame *Frame = 0;
4251 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4252 Frame = Info.CurrentCall;
4253
Richard Smith177dce72011-11-01 16:57:24 +00004254 if (!VD->getType()->isReferenceType()) {
Richard Smithb476a142013-05-05 21:17:10 +00004255 if (Frame) {
4256 Result.set(VD, Frame->Index);
Richard Smith177dce72011-11-01 16:57:24 +00004257 return true;
4258 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004259 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00004260 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00004261
Richard Smithb476a142013-05-05 21:17:10 +00004262 APValue *V;
4263 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf48fdb02011-12-09 22:58:01 +00004264 return false;
Richard Smith03ce5f82013-07-24 07:11:57 +00004265 if (V->isUninit()) {
4266 if (!Info.CheckingPotentialConstantExpression)
4267 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4268 return false;
4269 }
Richard Smithb476a142013-05-05 21:17:10 +00004270 return Success(*V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00004271}
4272
Richard Smithbd552ef2011-10-31 05:52:43 +00004273bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4274 const MaterializeTemporaryExpr *E) {
Richard Smith8a66bf72013-06-03 05:03:02 +00004275 // Walk through the expression to find the materialized temporary itself.
4276 SmallVector<const Expr *, 2> CommaLHSs;
4277 SmallVector<SubobjectAdjustment, 2> Adjustments;
4278 const Expr *Inner = E->GetTemporaryExpr()->
4279 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smithe24f5fc2011-11-17 22:56:20 +00004280
Richard Smith8a66bf72013-06-03 05:03:02 +00004281 // If we passed any comma operators, evaluate their LHSs.
4282 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4283 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4284 return false;
4285
Richard Smith211c8dd2013-06-05 00:46:14 +00004286 // A materialized temporary with static storage duration can appear within the
4287 // result of a constant expression evaluation, so we need to preserve its
4288 // value for use outside this evaluation.
4289 APValue *Value;
4290 if (E->getStorageDuration() == SD_Static) {
4291 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smith3282b842013-06-14 03:07:01 +00004292 *Value = APValue();
Richard Smith211c8dd2013-06-05 00:46:14 +00004293 Result.set(E);
4294 } else {
Richard Smith03ce5f82013-07-24 07:11:57 +00004295 Value = &Info.CurrentCall->
4296 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smith211c8dd2013-06-05 00:46:14 +00004297 Result.set(E, Info.CurrentCall->Index);
4298 }
4299
Richard Smithf69dd332013-06-06 08:19:16 +00004300 QualType Type = Inner->getType();
4301
Richard Smith8a66bf72013-06-03 05:03:02 +00004302 // Materialize the temporary itself.
Richard Smithf69dd332013-06-06 08:19:16 +00004303 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4304 (E->getStorageDuration() == SD_Static &&
4305 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4306 *Value = APValue();
Richard Smith8a66bf72013-06-03 05:03:02 +00004307 return false;
Richard Smithf69dd332013-06-06 08:19:16 +00004308 }
Richard Smith8a66bf72013-06-03 05:03:02 +00004309
4310 // Adjust our lvalue to refer to the desired subobject.
Richard Smith8a66bf72013-06-03 05:03:02 +00004311 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4312 --I;
4313 switch (Adjustments[I].Kind) {
4314 case SubobjectAdjustment::DerivedToBaseAdjustment:
4315 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4316 Type, Result))
4317 return false;
4318 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4319 break;
4320
4321 case SubobjectAdjustment::FieldAdjustment:
4322 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4323 return false;
4324 Type = Adjustments[I].Field->getType();
4325 break;
4326
4327 case SubobjectAdjustment::MemberPointerAdjustment:
4328 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4329 Adjustments[I].Ptr.RHS))
4330 return false;
4331 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4332 break;
4333 }
4334 }
4335
4336 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00004337}
4338
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004339bool
4340LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004341 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4342 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4343 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00004344 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004345}
4346
Richard Smith47d21452011-12-27 12:18:28 +00004347bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith9be36ab2012-10-17 23:52:07 +00004348 if (!E->isPotentiallyEvaluated())
Richard Smith47d21452011-12-27 12:18:28 +00004349 return Success(E);
Richard Smith9be36ab2012-10-17 23:52:07 +00004350
4351 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4352 << E->getExprOperand()->getType()
4353 << E->getExprOperand()->getSourceRange();
4354 return false;
Richard Smith47d21452011-12-27 12:18:28 +00004355}
4356
Francois Pichete275a182012-04-16 04:08:35 +00004357bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4358 return Success(E);
Richard Smithb476a142013-05-05 21:17:10 +00004359}
Francois Pichete275a182012-04-16 04:08:35 +00004360
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004361bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004362 // Handle static data members.
4363 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4364 VisitIgnoredValue(E->getBase());
4365 return VisitVarDecl(E, VD);
4366 }
4367
Richard Smithd0dccea2011-10-28 22:34:42 +00004368 // Handle static member functions.
4369 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4370 if (MD->isStatic()) {
4371 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004372 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00004373 }
4374 }
4375
Richard Smith180f4792011-11-10 06:34:14 +00004376 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00004377 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004378}
4379
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004380bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004381 // FIXME: Deal with vectors as array subscript bases.
4382 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004383 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004384
Anders Carlsson3068d112008-11-16 19:01:22 +00004385 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00004386 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004387
Anders Carlsson3068d112008-11-16 19:01:22 +00004388 APSInt Index;
4389 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00004390 return false;
Anders Carlsson3068d112008-11-16 19:01:22 +00004391
Richard Smitha49a7fe2013-05-07 23:34:45 +00004392 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4393 getExtValue(Index));
Anders Carlsson3068d112008-11-16 19:01:22 +00004394}
Eli Friedman4efaa272008-11-12 09:44:48 +00004395
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004396bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00004397 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00004398}
4399
Richard Smith86024012012-02-18 22:04:06 +00004400bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4401 if (!Visit(E->getSubExpr()))
4402 return false;
4403 // __real is a no-op on scalar lvalues.
4404 if (E->getSubExpr()->getType()->isAnyComplexType())
4405 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4406 return true;
4407}
4408
4409bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4410 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4411 "lvalue __imag__ on scalar?");
4412 if (!Visit(E->getSubExpr()))
4413 return false;
4414 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4415 return true;
4416}
4417
Richard Smith5528ac92013-05-05 23:31:59 +00004418bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4419 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smithb476a142013-05-05 21:17:10 +00004420 return Error(UO);
4421
4422 if (!this->Visit(UO->getSubExpr()))
4423 return false;
4424
Richard Smith5528ac92013-05-05 23:31:59 +00004425 return handleIncDec(
4426 this->Info, UO, Result, UO->getSubExpr()->getType(),
4427 UO->isIncrementOp(), 0);
Richard Smithb476a142013-05-05 21:17:10 +00004428}
4429
4430bool LValueExprEvaluator::VisitCompoundAssignOperator(
4431 const CompoundAssignOperator *CAO) {
Richard Smith5528ac92013-05-05 23:31:59 +00004432 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smithb476a142013-05-05 21:17:10 +00004433 return Error(CAO);
4434
Richard Smithb476a142013-05-05 21:17:10 +00004435 APValue RHS;
Richard Smith5528ac92013-05-05 23:31:59 +00004436
4437 // The overall lvalue result is the result of evaluating the LHS.
4438 if (!this->Visit(CAO->getLHS())) {
4439 if (Info.keepEvaluatingAfterFailure())
4440 Evaluate(RHS, this->Info, CAO->getRHS());
4441 return false;
4442 }
4443
Richard Smithb476a142013-05-05 21:17:10 +00004444 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4445 return false;
4446
Richard Smithd20afcb2013-05-07 04:50:00 +00004447 return handleCompoundAssignment(
4448 this->Info, CAO,
4449 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4450 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smithb476a142013-05-05 21:17:10 +00004451}
4452
4453bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Richard Smith5528ac92013-05-05 23:31:59 +00004454 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4455 return Error(E);
4456
Richard Smithb476a142013-05-05 21:17:10 +00004457 APValue NewVal;
Richard Smith5528ac92013-05-05 23:31:59 +00004458
4459 if (!this->Visit(E->getLHS())) {
4460 if (Info.keepEvaluatingAfterFailure())
4461 Evaluate(NewVal, this->Info, E->getRHS());
4462 return false;
4463 }
4464
Richard Smithb476a142013-05-05 21:17:10 +00004465 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4466 return false;
Richard Smith5528ac92013-05-05 23:31:59 +00004467
4468 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smithb476a142013-05-05 21:17:10 +00004469 NewVal);
4470}
4471
Eli Friedman4efaa272008-11-12 09:44:48 +00004472//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004473// Pointer Evaluation
4474//===----------------------------------------------------------------------===//
4475
Anders Carlssonc754aa62008-07-08 05:13:58 +00004476namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004477class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004478 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00004479 LValue &Result;
4480
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004481 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004482 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00004483 return true;
4484 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00004485public:
Mike Stump1eb44332009-09-09 15:08:12 +00004486
John McCallefdb83e2010-05-07 21:00:08 +00004487 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004488 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004489
Richard Smith1aa0be82012-03-03 22:46:17 +00004490 bool Success(const APValue &V, const Expr *E) {
4491 Result.setFrom(Info.Ctx, V);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004492 return true;
4493 }
Richard Smith51201882011-12-30 21:15:51 +00004494 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00004495 return Success((Expr*)0);
4496 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00004497
John McCallefdb83e2010-05-07 21:00:08 +00004498 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004499 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00004500 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004501 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00004502 { return Success(E); }
Patrick Beardeb382ec2012-04-19 00:25:12 +00004503 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004504 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004505 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00004506 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004507 bool VisitCallExpr(const CallExpr *E);
4508 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00004509 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00004510 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00004511 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00004512 }
Richard Smith180f4792011-11-10 06:34:14 +00004513 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith8a66bf72013-06-03 05:03:02 +00004514 // Can't look at 'this' when checking a potential constant expression.
4515 if (Info.CheckingPotentialConstantExpression)
4516 return false;
Richard Smith180f4792011-11-10 06:34:14 +00004517 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00004518 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00004519 Result = *Info.CurrentCall->This;
4520 return true;
4521 }
John McCall56ca35d2011-02-17 10:25:35 +00004522
Eli Friedmanba98d6b2009-03-23 04:56:01 +00004523 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00004524};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004525} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00004526
John McCallefdb83e2010-05-07 21:00:08 +00004527static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004528 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004529 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004530}
4531
John McCallefdb83e2010-05-07 21:00:08 +00004532bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00004533 if (E->getOpcode() != BO_Add &&
4534 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00004535 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004536
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004537 const Expr *PExp = E->getLHS();
4538 const Expr *IExp = E->getRHS();
4539 if (IExp->getType()->isPointerType())
4540 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00004541
Richard Smith745f5142012-01-27 01:14:48 +00004542 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4543 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00004544 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004545
John McCallefdb83e2010-05-07 21:00:08 +00004546 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00004547 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00004548 return false;
Richard Smitha49a7fe2013-05-07 23:34:45 +00004549
4550 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith0a3bdb62011-11-04 02:25:55 +00004551 if (E->getOpcode() == BO_Sub)
4552 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004553
Ted Kremenek890f0f12012-08-23 20:46:57 +00004554 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00004555 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4556 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004557}
Eli Friedman4efaa272008-11-12 09:44:48 +00004558
John McCallefdb83e2010-05-07 21:00:08 +00004559bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4560 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00004561}
Mike Stump1eb44332009-09-09 15:08:12 +00004562
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004563bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4564 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004565
Eli Friedman09a8a0e2009-12-27 05:43:15 +00004566 switch (E->getCastKind()) {
4567 default:
4568 break;
4569
John McCall2de56d12010-08-25 11:45:40 +00004570 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00004571 case CK_CPointerToObjCPointerCast:
4572 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00004573 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00004574 if (!Visit(SubExpr))
4575 return false;
Richard Smithc216a012011-12-12 12:46:16 +00004576 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4577 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4578 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00004579 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00004580 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00004581 if (SubExpr->getType()->isVoidPointerType())
4582 CCEDiag(E, diag::note_constexpr_invalid_cast)
4583 << 3 << SubExpr->getType();
4584 else
4585 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4586 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00004587 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00004588
Anders Carlsson5c5a7642010-10-31 20:41:46 +00004589 case CK_DerivedToBase:
Richard Smith8a66bf72013-06-03 05:03:02 +00004590 case CK_UncheckedDerivedToBase:
Richard Smith47a1eed2011-10-29 20:57:55 +00004591 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00004592 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00004593 if (!Result.Base && Result.Offset.isZero())
4594 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00004595
Richard Smith180f4792011-11-10 06:34:14 +00004596 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00004597 // the derived class to the base class.
Richard Smith8a66bf72013-06-03 05:03:02 +00004598 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4599 castAs<PointerType>()->getPointeeType(),
4600 Result);
Anders Carlsson5c5a7642010-10-31 20:41:46 +00004601
Richard Smithe24f5fc2011-11-17 22:56:20 +00004602 case CK_BaseToDerived:
4603 if (!Visit(E->getSubExpr()))
4604 return false;
4605 if (!Result.Base && Result.Offset.isZero())
4606 return true;
4607 return HandleBaseToDerivedCast(Info, E, Result);
4608
Richard Smith47a1eed2011-10-29 20:57:55 +00004609 case CK_NullToPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00004610 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00004611 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00004612
John McCall2de56d12010-08-25 11:45:40 +00004613 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00004614 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4615
Richard Smith1aa0be82012-03-03 22:46:17 +00004616 APValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00004617 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00004618 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004619
John McCallefdb83e2010-05-07 21:00:08 +00004620 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004621 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4622 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004623 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00004624 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith83587db2012-02-15 02:18:13 +00004625 Result.CallIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00004626 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00004627 return true;
4628 } else {
4629 // Cast is of an lvalue, no need to change value.
Richard Smith1aa0be82012-03-03 22:46:17 +00004630 Result.setFrom(Info.Ctx, Value);
John McCallefdb83e2010-05-07 21:00:08 +00004631 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004632 }
4633 }
John McCall2de56d12010-08-25 11:45:40 +00004634 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00004635 if (SubExpr->isGLValue()) {
4636 if (!EvaluateLValue(SubExpr, Result, Info))
4637 return false;
4638 } else {
Richard Smith83587db2012-02-15 02:18:13 +00004639 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith03ce5f82013-07-24 07:11:57 +00004640 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smith83587db2012-02-15 02:18:13 +00004641 Info, Result, SubExpr))
Richard Smithe24f5fc2011-11-17 22:56:20 +00004642 return false;
4643 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00004644 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00004645 if (const ConstantArrayType *CAT
4646 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4647 Result.addArray(Info, E, CAT);
4648 else
4649 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00004650 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00004651
John McCall2de56d12010-08-25 11:45:40 +00004652 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00004653 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00004654 }
4655
Richard Smithc49bd112011-10-28 17:51:58 +00004656 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004657}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004658
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004659bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004660 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00004661 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00004662
Richard Smith5154dce2013-07-11 02:27:57 +00004663 switch (E->isBuiltinCall()) {
4664 case Builtin::BI__builtin_addressof:
4665 return EvaluateLValue(E->getArg(0), Result, Info);
4666
4667 default:
4668 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4669 }
Eli Friedman4efaa272008-11-12 09:44:48 +00004670}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004671
4672//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00004673// Member Pointer Evaluation
4674//===----------------------------------------------------------------------===//
4675
4676namespace {
4677class MemberPointerExprEvaluator
4678 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
4679 MemberPtr &Result;
4680
4681 bool Success(const ValueDecl *D) {
4682 Result = MemberPtr(D);
4683 return true;
4684 }
4685public:
4686
4687 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
4688 : ExprEvaluatorBaseTy(Info), Result(Result) {}
4689
Richard Smith1aa0be82012-03-03 22:46:17 +00004690 bool Success(const APValue &V, const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004691 Result.setFrom(V);
4692 return true;
4693 }
Richard Smith51201882011-12-30 21:15:51 +00004694 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004695 return Success((const ValueDecl*)0);
4696 }
4697
4698 bool VisitCastExpr(const CastExpr *E);
4699 bool VisitUnaryAddrOf(const UnaryOperator *E);
4700};
4701} // end anonymous namespace
4702
4703static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
4704 EvalInfo &Info) {
4705 assert(E->isRValue() && E->getType()->isMemberPointerType());
4706 return MemberPointerExprEvaluator(Info, Result).Visit(E);
4707}
4708
4709bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
4710 switch (E->getCastKind()) {
4711 default:
4712 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4713
4714 case CK_NullToMemberPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00004715 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00004716 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00004717
4718 case CK_BaseToDerivedMemberPointer: {
4719 if (!Visit(E->getSubExpr()))
4720 return false;
4721 if (E->path_empty())
4722 return true;
4723 // Base-to-derived member pointer casts store the path in derived-to-base
4724 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
4725 // the wrong end of the derived->base arc, so stagger the path by one class.
4726 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
4727 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
4728 PathI != PathE; ++PathI) {
4729 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4730 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
4731 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00004732 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00004733 }
4734 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
4735 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004736 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00004737 return true;
4738 }
4739
4740 case CK_DerivedToBaseMemberPointer:
4741 if (!Visit(E->getSubExpr()))
4742 return false;
4743 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4744 PathE = E->path_end(); PathI != PathE; ++PathI) {
4745 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4746 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4747 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00004748 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00004749 }
4750 return true;
4751 }
4752}
4753
4754bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4755 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
4756 // member can be formed.
4757 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
4758}
4759
4760//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00004761// Record Evaluation
4762//===----------------------------------------------------------------------===//
4763
4764namespace {
4765 class RecordExprEvaluator
4766 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
4767 const LValue &This;
4768 APValue &Result;
4769 public:
4770
4771 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
4772 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
4773
Richard Smith1aa0be82012-03-03 22:46:17 +00004774 bool Success(const APValue &V, const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00004775 Result = V;
4776 return true;
Richard Smith180f4792011-11-10 06:34:14 +00004777 }
Richard Smith51201882011-12-30 21:15:51 +00004778 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00004779
Richard Smith59efe262011-11-11 04:05:33 +00004780 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00004781 bool VisitInitListExpr(const InitListExpr *E);
4782 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith7c3e6152013-06-12 22:31:48 +00004783 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00004784 };
4785}
4786
Richard Smith51201882011-12-30 21:15:51 +00004787/// Perform zero-initialization on an object of non-union class type.
4788/// C++11 [dcl.init]p5:
4789/// To zero-initialize an object or reference of type T means:
4790/// [...]
4791/// -- if T is a (possibly cv-qualified) non-union class type,
4792/// each non-static data member and each base-class subobject is
4793/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00004794static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
4795 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00004796 const LValue &This, APValue &Result) {
4797 assert(!RD->isUnion() && "Expected non-union class type");
4798 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
4799 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
4800 std::distance(RD->field_begin(), RD->field_end()));
4801
John McCall8d59dee2012-05-01 00:38:49 +00004802 if (RD->isInvalidDecl()) return false;
Richard Smith51201882011-12-30 21:15:51 +00004803 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4804
4805 if (CD) {
4806 unsigned Index = 0;
4807 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00004808 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00004809 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4810 LValue Subobject = This;
John McCall8d59dee2012-05-01 00:38:49 +00004811 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4812 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00004813 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00004814 Result.getStructBase(Index)))
4815 return false;
4816 }
4817 }
4818
Richard Smithb4e85ed2012-01-06 16:39:00 +00004819 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
4820 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00004821 // -- if T is a reference type, no initialization is performed.
David Blaikie262bc182012-04-30 02:36:29 +00004822 if (I->getType()->isReferenceType())
Richard Smith51201882011-12-30 21:15:51 +00004823 continue;
4824
4825 LValue Subobject = This;
David Blaikie581deb32012-06-06 20:45:41 +00004826 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCall8d59dee2012-05-01 00:38:49 +00004827 return false;
Richard Smith51201882011-12-30 21:15:51 +00004828
David Blaikie262bc182012-04-30 02:36:29 +00004829 ImplicitValueInitExpr VIE(I->getType());
Richard Smith83587db2012-02-15 02:18:13 +00004830 if (!EvaluateInPlace(
David Blaikie262bc182012-04-30 02:36:29 +00004831 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00004832 return false;
4833 }
4834
4835 return true;
4836}
4837
4838bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
4839 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall1de9d7d2012-04-26 18:10:01 +00004840 if (RD->isInvalidDecl()) return false;
Richard Smith51201882011-12-30 21:15:51 +00004841 if (RD->isUnion()) {
4842 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4843 // object's first non-static named data member is zero-initialized
4844 RecordDecl::field_iterator I = RD->field_begin();
4845 if (I == RD->field_end()) {
4846 Result = APValue((const FieldDecl*)0);
4847 return true;
4848 }
4849
4850 LValue Subobject = This;
David Blaikie581deb32012-06-06 20:45:41 +00004851 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCall8d59dee2012-05-01 00:38:49 +00004852 return false;
David Blaikie581deb32012-06-06 20:45:41 +00004853 Result = APValue(*I);
David Blaikie262bc182012-04-30 02:36:29 +00004854 ImplicitValueInitExpr VIE(I->getType());
Richard Smith83587db2012-02-15 02:18:13 +00004855 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00004856 }
4857
Richard Smithce582fe2012-02-17 00:44:16 +00004858 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00004859 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smithce582fe2012-02-17 00:44:16 +00004860 return false;
4861 }
4862
Richard Smithb4e85ed2012-01-06 16:39:00 +00004863 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00004864}
4865
Richard Smith59efe262011-11-11 04:05:33 +00004866bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
4867 switch (E->getCastKind()) {
4868 default:
4869 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4870
4871 case CK_ConstructorConversion:
4872 return Visit(E->getSubExpr());
4873
4874 case CK_DerivedToBase:
4875 case CK_UncheckedDerivedToBase: {
Richard Smith1aa0be82012-03-03 22:46:17 +00004876 APValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00004877 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00004878 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004879 if (!DerivedObject.isStruct())
4880 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00004881
4882 // Derived-to-base rvalue conversion: just slice off the derived part.
4883 APValue *Value = &DerivedObject;
4884 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
4885 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4886 PathE = E->path_end(); PathI != PathE; ++PathI) {
4887 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
4888 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4889 Value = &Value->getStructBase(getBaseIndex(RD, Base));
4890 RD = Base;
4891 }
4892 Result = *Value;
4893 return true;
4894 }
4895 }
4896}
4897
Richard Smith180f4792011-11-10 06:34:14 +00004898bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
4899 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall1de9d7d2012-04-26 18:10:01 +00004900 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00004901 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4902
4903 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00004904 const FieldDecl *Field = E->getInitializedFieldInUnion();
4905 Result = APValue(Field);
4906 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00004907 return true;
Richard Smithec789162012-01-12 18:54:33 +00004908
4909 // If the initializer list for a union does not contain any elements, the
4910 // first element of the union is value-initialized.
Richard Smithc3bf52c2013-04-20 22:23:05 +00004911 // FIXME: The element should be initialized from an initializer list.
4912 // Is this difference ever observable for initializer lists which
4913 // we don't build?
Richard Smithec789162012-01-12 18:54:33 +00004914 ImplicitValueInitExpr VIE(Field->getType());
4915 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
4916
Richard Smith180f4792011-11-10 06:34:14 +00004917 LValue Subobject = This;
John McCall8d59dee2012-05-01 00:38:49 +00004918 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
4919 return false;
Richard Smithc3bf52c2013-04-20 22:23:05 +00004920
4921 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4922 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4923 isa<CXXDefaultInitExpr>(InitExpr));
4924
Richard Smith83587db2012-02-15 02:18:13 +00004925 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00004926 }
4927
4928 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
4929 "initializer list for class with base classes");
4930 Result = APValue(APValue::UninitStruct(), 0,
4931 std::distance(RD->field_begin(), RD->field_end()));
4932 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00004933 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00004934 for (RecordDecl::field_iterator Field = RD->field_begin(),
4935 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
4936 // Anonymous bit-fields are not considered members of the class for
4937 // purposes of aggregate initialization.
4938 if (Field->isUnnamedBitfield())
4939 continue;
4940
4941 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00004942
Richard Smith745f5142012-01-27 01:14:48 +00004943 bool HaveInit = ElementNo < E->getNumInits();
4944
4945 // FIXME: Diagnostics here should point to the end of the initializer
4946 // list, not the start.
John McCall8d59dee2012-05-01 00:38:49 +00004947 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie581deb32012-06-06 20:45:41 +00004948 Subobject, *Field, &Layout))
John McCall8d59dee2012-05-01 00:38:49 +00004949 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004950
4951 // Perform an implicit value-initialization for members beyond the end of
4952 // the initializer list.
4953 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smithc3bf52c2013-04-20 22:23:05 +00004954 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith745f5142012-01-27 01:14:48 +00004955
Richard Smithc3bf52c2013-04-20 22:23:05 +00004956 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4957 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4958 isa<CXXDefaultInitExpr>(Init));
4959
Richard Smith3835a4e2013-08-06 07:09:20 +00004960 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
4961 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
4962 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
4963 FieldVal, *Field))) {
Richard Smith745f5142012-01-27 01:14:48 +00004964 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00004965 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004966 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00004967 }
4968 }
4969
Richard Smith745f5142012-01-27 01:14:48 +00004970 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00004971}
4972
4973bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
4974 const CXXConstructorDecl *FD = E->getConstructor();
John McCall1de9d7d2012-04-26 18:10:01 +00004975 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
4976
Richard Smith51201882011-12-30 21:15:51 +00004977 bool ZeroInit = E->requiresZeroInitialization();
4978 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00004979 // If we've already performed zero-initialization, we're already done.
4980 if (!Result.isUninit())
4981 return true;
4982
Richard Smith51201882011-12-30 21:15:51 +00004983 if (ZeroInit)
4984 return ZeroInitialization(E);
4985
Richard Smith61802452011-12-22 02:22:31 +00004986 const CXXRecordDecl *RD = FD->getParent();
4987 if (RD->isUnion())
4988 Result = APValue((FieldDecl*)0);
4989 else
4990 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4991 std::distance(RD->field_begin(), RD->field_end()));
4992 return true;
4993 }
4994
Richard Smith180f4792011-11-10 06:34:14 +00004995 const FunctionDecl *Definition = 0;
4996 FD->getBody(Definition);
4997
Richard Smithc1c5f272011-12-13 06:39:58 +00004998 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
4999 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005000
Richard Smith610a60c2012-01-10 04:32:03 +00005001 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00005002 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00005003 if (const MaterializeTemporaryExpr *ME
5004 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5005 return Visit(ME->GetTemporaryExpr());
5006
Richard Smith51201882011-12-30 21:15:51 +00005007 if (ZeroInit && !ZeroInitialization(E))
5008 return false;
5009
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005010 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00005011 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00005012 cast<CXXConstructorDecl>(Definition), Info,
5013 Result);
Richard Smith180f4792011-11-10 06:34:14 +00005014}
5015
Richard Smith7c3e6152013-06-12 22:31:48 +00005016bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5017 const CXXStdInitializerListExpr *E) {
5018 const ConstantArrayType *ArrayType =
5019 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5020
5021 LValue Array;
5022 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5023 return false;
5024
5025 // Get a pointer to the first element of the array.
5026 Array.addArray(Info, E, ArrayType);
5027
5028 // FIXME: Perform the checks on the field types in SemaInit.
5029 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5030 RecordDecl::field_iterator Field = Record->field_begin();
5031 if (Field == Record->field_end())
5032 return Error(E);
5033
5034 // Start pointer.
5035 if (!Field->getType()->isPointerType() ||
5036 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5037 ArrayType->getElementType()))
5038 return Error(E);
5039
5040 // FIXME: What if the initializer_list type has base classes, etc?
5041 Result = APValue(APValue::UninitStruct(), 0, 2);
5042 Array.moveInto(Result.getStructField(0));
5043
5044 if (++Field == Record->field_end())
5045 return Error(E);
5046
5047 if (Field->getType()->isPointerType() &&
5048 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5049 ArrayType->getElementType())) {
5050 // End pointer.
5051 if (!HandleLValueArrayAdjustment(Info, E, Array,
5052 ArrayType->getElementType(),
5053 ArrayType->getSize().getZExtValue()))
5054 return false;
5055 Array.moveInto(Result.getStructField(1));
5056 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5057 // Length.
5058 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5059 else
5060 return Error(E);
5061
5062 if (++Field != Record->field_end())
5063 return Error(E);
5064
5065 return true;
5066}
5067
Richard Smith180f4792011-11-10 06:34:14 +00005068static bool EvaluateRecord(const Expr *E, const LValue &This,
5069 APValue &Result, EvalInfo &Info) {
5070 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00005071 "can't evaluate expression as a record rvalue");
5072 return RecordExprEvaluator(Info, This, Result).Visit(E);
5073}
5074
5075//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00005076// Temporary Evaluation
5077//
5078// Temporaries are represented in the AST as rvalues, but generally behave like
5079// lvalues. The full-object of which the temporary is a subobject is implicitly
5080// materialized so that a reference can bind to it.
5081//===----------------------------------------------------------------------===//
5082namespace {
5083class TemporaryExprEvaluator
5084 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5085public:
5086 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5087 LValueExprEvaluatorBaseTy(Info, Result) {}
5088
5089 /// Visit an expression which constructs the value of this temporary.
5090 bool VisitConstructExpr(const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00005091 Result.set(E, Info.CurrentCall->Index);
Richard Smith03ce5f82013-07-24 07:11:57 +00005092 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5093 Info, Result, E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00005094 }
5095
5096 bool VisitCastExpr(const CastExpr *E) {
5097 switch (E->getCastKind()) {
5098 default:
5099 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5100
5101 case CK_ConstructorConversion:
5102 return VisitConstructExpr(E->getSubExpr());
5103 }
5104 }
5105 bool VisitInitListExpr(const InitListExpr *E) {
5106 return VisitConstructExpr(E);
5107 }
5108 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5109 return VisitConstructExpr(E);
5110 }
5111 bool VisitCallExpr(const CallExpr *E) {
5112 return VisitConstructExpr(E);
5113 }
5114};
5115} // end anonymous namespace
5116
5117/// Evaluate an expression of record type as a temporary.
5118static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00005119 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00005120 return TemporaryExprEvaluator(Info, Result).Visit(E);
5121}
5122
5123//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00005124// Vector Evaluation
5125//===----------------------------------------------------------------------===//
5126
5127namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005128 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00005129 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
5130 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00005131 public:
Mike Stump1eb44332009-09-09 15:08:12 +00005132
Richard Smith07fc6572011-10-22 21:10:00 +00005133 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5134 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00005135
Richard Smith07fc6572011-10-22 21:10:00 +00005136 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
5137 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5138 // FIXME: remove this APValue copy.
5139 Result = APValue(V.data(), V.size());
5140 return true;
5141 }
Richard Smith1aa0be82012-03-03 22:46:17 +00005142 bool Success(const APValue &V, const Expr *E) {
Richard Smith69c2c502011-11-04 05:33:44 +00005143 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00005144 Result = V;
5145 return true;
5146 }
Richard Smith51201882011-12-30 21:15:51 +00005147 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00005148
Richard Smith07fc6572011-10-22 21:10:00 +00005149 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00005150 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00005151 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00005152 bool VisitInitListExpr(const InitListExpr *E);
5153 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00005154 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00005155 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00005156 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00005157 };
5158} // end anonymous namespace
5159
5160static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005161 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00005162 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00005163}
5164
Richard Smith07fc6572011-10-22 21:10:00 +00005165bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5166 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00005167 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00005168
Richard Smithd62ca372011-12-06 22:44:34 +00005169 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00005170 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00005171
Eli Friedman46a52322011-03-25 00:43:55 +00005172 switch (E->getCastKind()) {
5173 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00005174 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00005175 if (SETy->isIntegerType()) {
5176 APSInt IntResult;
5177 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00005178 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00005179 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00005180 } else if (SETy->isRealFloatingType()) {
5181 APFloat F(0.0);
5182 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00005183 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00005184 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00005185 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00005186 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005187 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00005188
5189 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00005190 SmallVector<APValue, 4> Elts(NElts, Val);
5191 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00005192 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00005193 case CK_BitCast: {
5194 // Evaluate the operand into an APInt we can extract from.
5195 llvm::APInt SValInt;
5196 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5197 return false;
5198 // Extract the elements
5199 QualType EltTy = VTy->getElementType();
5200 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5201 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5202 SmallVector<APValue, 4> Elts;
5203 if (EltTy->isRealFloatingType()) {
5204 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedmane6a24e82011-12-22 03:51:45 +00005205 unsigned FloatEltSize = EltSize;
5206 if (&Sem == &APFloat::x87DoubleExtended)
5207 FloatEltSize = 80;
5208 for (unsigned i = 0; i < NElts; i++) {
5209 llvm::APInt Elt;
5210 if (BigEndian)
5211 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5212 else
5213 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover9ec55f22013-01-22 09:46:51 +00005214 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedmane6a24e82011-12-22 03:51:45 +00005215 }
5216 } else if (EltTy->isIntegerType()) {
5217 for (unsigned i = 0; i < NElts; i++) {
5218 llvm::APInt Elt;
5219 if (BigEndian)
5220 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5221 else
5222 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5223 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5224 }
5225 } else {
5226 return Error(E);
5227 }
5228 return Success(Elts, E);
5229 }
Eli Friedman46a52322011-03-25 00:43:55 +00005230 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005231 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005232 }
Nate Begeman59b5da62009-01-18 03:20:47 +00005233}
5234
Richard Smith07fc6572011-10-22 21:10:00 +00005235bool
Nate Begeman59b5da62009-01-18 03:20:47 +00005236VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00005237 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00005238 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00005239 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00005240
Nate Begeman59b5da62009-01-18 03:20:47 +00005241 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00005242 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00005243
Eli Friedman3edd5a92012-01-03 23:24:20 +00005244 // The number of initializers can be less than the number of
5245 // vector elements. For OpenCL, this can be due to nested vector
5246 // initialization. For GCC compatibility, missing trailing elements
5247 // should be initialized with zeroes.
5248 unsigned CountInits = 0, CountElts = 0;
5249 while (CountElts < NumElements) {
5250 // Handle nested vector initialization.
5251 if (CountInits < NumInits
5252 && E->getInit(CountInits)->getType()->isExtVectorType()) {
5253 APValue v;
5254 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5255 return Error(E);
5256 unsigned vlen = v.getVectorLength();
5257 for (unsigned j = 0; j < vlen; j++)
5258 Elements.push_back(v.getVectorElt(j));
5259 CountElts += vlen;
5260 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00005261 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00005262 if (CountInits < NumInits) {
5263 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00005264 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00005265 } else // trailing integer zero.
5266 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5267 Elements.push_back(APValue(sInt));
5268 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00005269 } else {
5270 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00005271 if (CountInits < NumInits) {
5272 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00005273 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00005274 } else // trailing float zero.
5275 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5276 Elements.push_back(APValue(f));
5277 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00005278 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00005279 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00005280 }
Richard Smith07fc6572011-10-22 21:10:00 +00005281 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00005282}
5283
Richard Smith07fc6572011-10-22 21:10:00 +00005284bool
Richard Smith51201882011-12-30 21:15:51 +00005285VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00005286 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00005287 QualType EltTy = VT->getElementType();
5288 APValue ZeroElement;
5289 if (EltTy->isIntegerType())
5290 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5291 else
5292 ZeroElement =
5293 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5294
Chris Lattner5f9e2722011-07-23 10:55:15 +00005295 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00005296 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00005297}
5298
Richard Smith07fc6572011-10-22 21:10:00 +00005299bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00005300 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00005301 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00005302}
5303
Nate Begeman59b5da62009-01-18 03:20:47 +00005304//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00005305// Array Evaluation
5306//===----------------------------------------------------------------------===//
5307
5308namespace {
5309 class ArrayExprEvaluator
5310 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00005311 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00005312 APValue &Result;
5313 public:
5314
Richard Smith180f4792011-11-10 06:34:14 +00005315 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5316 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00005317
5318 bool Success(const APValue &V, const Expr *E) {
Richard Smithf3908f22012-02-17 03:35:37 +00005319 assert((V.isArray() || V.isLValue()) &&
5320 "expected array or string literal");
Richard Smithcc5d4f62011-11-07 09:22:26 +00005321 Result = V;
5322 return true;
5323 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00005324
Richard Smith51201882011-12-30 21:15:51 +00005325 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005326 const ConstantArrayType *CAT =
5327 Info.Ctx.getAsConstantArrayType(E->getType());
5328 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005329 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00005330
5331 Result = APValue(APValue::UninitArray(), 0,
5332 CAT->getSize().getZExtValue());
5333 if (!Result.hasArrayFiller()) return true;
5334
Richard Smith51201882011-12-30 21:15:51 +00005335 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00005336 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00005337 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00005338 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00005339 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith180f4792011-11-10 06:34:14 +00005340 }
5341
Richard Smithcc5d4f62011-11-07 09:22:26 +00005342 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00005343 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith99ad3592013-04-22 14:44:29 +00005344 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5345 const LValue &Subobject,
5346 APValue *Value, QualType Type);
Richard Smithcc5d4f62011-11-07 09:22:26 +00005347 };
5348} // end anonymous namespace
5349
Richard Smith180f4792011-11-10 06:34:14 +00005350static bool EvaluateArray(const Expr *E, const LValue &This,
5351 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00005352 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00005353 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00005354}
5355
5356bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5357 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5358 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005359 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00005360
Richard Smith974c5f92011-12-22 01:07:19 +00005361 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5362 // an appropriately-typed string literal enclosed in braces.
Richard Smithfe587202012-04-15 02:50:59 +00005363 if (E->isStringLiteralInit()) {
Richard Smith974c5f92011-12-22 01:07:19 +00005364 LValue LV;
5365 if (!EvaluateLValue(E->getInit(0), LV, Info))
5366 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00005367 APValue Val;
Richard Smithf3908f22012-02-17 03:35:37 +00005368 LV.moveInto(Val);
5369 return Success(Val, E);
Richard Smith974c5f92011-12-22 01:07:19 +00005370 }
5371
Richard Smith745f5142012-01-27 01:14:48 +00005372 bool Success = true;
5373
Richard Smithde31aa72012-07-07 22:48:24 +00005374 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5375 "zero-initialized array shouldn't have any initialized elts");
5376 APValue Filler;
5377 if (Result.isArray() && Result.hasArrayFiller())
5378 Filler = Result.getArrayFiller();
5379
Richard Smith99ad3592013-04-22 14:44:29 +00005380 unsigned NumEltsToInit = E->getNumInits();
5381 unsigned NumElts = CAT->getSize().getZExtValue();
5382 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
5383
5384 // If the initializer might depend on the array index, run it for each
5385 // array element. For now, just whitelist non-class value-initialization.
5386 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5387 NumEltsToInit = NumElts;
5388
5389 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smithde31aa72012-07-07 22:48:24 +00005390
5391 // If the array was previously zero-initialized, preserve the
5392 // zero-initialized values.
5393 if (!Filler.isUninit()) {
5394 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5395 Result.getArrayInitializedElt(I) = Filler;
5396 if (Result.hasArrayFiller())
5397 Result.getArrayFiller() = Filler;
5398 }
5399
Richard Smith180f4792011-11-10 06:34:14 +00005400 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00005401 Subobject.addArray(Info, E, CAT);
Richard Smith99ad3592013-04-22 14:44:29 +00005402 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5403 const Expr *Init =
5404 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smith83587db2012-02-15 02:18:13 +00005405 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith99ad3592013-04-22 14:44:29 +00005406 Info, Subobject, Init) ||
5407 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith745f5142012-01-27 01:14:48 +00005408 CAT->getElementType(), 1)) {
5409 if (!Info.keepEvaluatingAfterFailure())
5410 return false;
5411 Success = false;
5412 }
Richard Smith180f4792011-11-10 06:34:14 +00005413 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00005414
Richard Smith99ad3592013-04-22 14:44:29 +00005415 if (!Result.hasArrayFiller())
5416 return Success;
5417
5418 // If we get here, we have a trivial filler, which we can just evaluate
5419 // once and splat over the rest of the array elements.
5420 assert(FillerExpr && "no array filler for incomplete init list");
5421 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5422 FillerExpr) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00005423}
5424
Richard Smithe24f5fc2011-11-17 22:56:20 +00005425bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith99ad3592013-04-22 14:44:29 +00005426 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5427}
Richard Smithde31aa72012-07-07 22:48:24 +00005428
Richard Smith99ad3592013-04-22 14:44:29 +00005429bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5430 const LValue &Subobject,
5431 APValue *Value,
5432 QualType Type) {
5433 bool HadZeroInit = !Value->isUninit();
5434
5435 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5436 unsigned N = CAT->getSize().getZExtValue();
5437
5438 // Preserve the array filler if we had prior zero-initialization.
5439 APValue Filler =
5440 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5441 : APValue();
5442
5443 *Value = APValue(APValue::UninitArray(), N, N);
5444
5445 if (HadZeroInit)
5446 for (unsigned I = 0; I != N; ++I)
5447 Value->getArrayInitializedElt(I) = Filler;
5448
5449 // Initialize the elements.
5450 LValue ArrayElt = Subobject;
5451 ArrayElt.addArray(Info, E, CAT);
5452 for (unsigned I = 0; I != N; ++I)
5453 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5454 CAT->getElementType()) ||
5455 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5456 CAT->getElementType(), 1))
5457 return false;
5458
5459 return true;
Richard Smithde31aa72012-07-07 22:48:24 +00005460 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00005461
Richard Smith99ad3592013-04-22 14:44:29 +00005462 if (!Type->isRecordType())
Richard Smitha4334df2012-07-10 22:12:55 +00005463 return Error(E);
5464
Richard Smithe24f5fc2011-11-17 22:56:20 +00005465 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00005466
Richard Smith51201882011-12-30 21:15:51 +00005467 bool ZeroInit = E->requiresZeroInitialization();
5468 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00005469 if (HadZeroInit)
5470 return true;
5471
Richard Smith51201882011-12-30 21:15:51 +00005472 if (ZeroInit) {
Richard Smith99ad3592013-04-22 14:44:29 +00005473 ImplicitValueInitExpr VIE(Type);
Richard Smithde31aa72012-07-07 22:48:24 +00005474 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00005475 }
5476
Richard Smith61802452011-12-22 02:22:31 +00005477 const CXXRecordDecl *RD = FD->getParent();
5478 if (RD->isUnion())
Richard Smithde31aa72012-07-07 22:48:24 +00005479 *Value = APValue((FieldDecl*)0);
Richard Smith61802452011-12-22 02:22:31 +00005480 else
Richard Smithde31aa72012-07-07 22:48:24 +00005481 *Value =
Richard Smith61802452011-12-22 02:22:31 +00005482 APValue(APValue::UninitStruct(), RD->getNumBases(),
5483 std::distance(RD->field_begin(), RD->field_end()));
5484 return true;
5485 }
5486
Richard Smithe24f5fc2011-11-17 22:56:20 +00005487 const FunctionDecl *Definition = 0;
5488 FD->getBody(Definition);
5489
Richard Smithc1c5f272011-12-13 06:39:58 +00005490 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5491 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00005492
Richard Smithec789162012-01-12 18:54:33 +00005493 if (ZeroInit && !HadZeroInit) {
Richard Smith99ad3592013-04-22 14:44:29 +00005494 ImplicitValueInitExpr VIE(Type);
Richard Smithde31aa72012-07-07 22:48:24 +00005495 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00005496 return false;
5497 }
5498
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005499 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00005500 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00005501 cast<CXXConstructorDecl>(Definition),
Richard Smithde31aa72012-07-07 22:48:24 +00005502 Info, *Value);
Richard Smithe24f5fc2011-11-17 22:56:20 +00005503}
5504
Richard Smithcc5d4f62011-11-07 09:22:26 +00005505//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005506// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00005507//
5508// As a GNU extension, we support casting pointers to sufficiently-wide integer
5509// types and back in constant folding. Integer values are thus represented
5510// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005511//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005512
5513namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005514class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005515 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith1aa0be82012-03-03 22:46:17 +00005516 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00005517public:
Richard Smith1aa0be82012-03-03 22:46:17 +00005518 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005519 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005520
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00005521 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00005522 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00005523 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00005524 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00005525 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00005526 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00005527 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00005528 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00005529 return true;
5530 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00005531 bool Success(const llvm::APSInt &SI, const Expr *E) {
5532 return Success(SI, E, Result);
5533 }
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00005534
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00005535 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00005536 assert(E->getType()->isIntegralOrEnumerationType() &&
5537 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005538 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00005539 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00005540 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00005541 Result.getInt().setIsUnsigned(
5542 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00005543 return true;
5544 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00005545 bool Success(const llvm::APInt &I, const Expr *E) {
5546 return Success(I, E, Result);
5547 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00005548
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00005549 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00005550 assert(E->getType()->isIntegralOrEnumerationType() &&
5551 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00005552 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00005553 return true;
5554 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00005555 bool Success(uint64_t Value, const Expr *E) {
5556 return Success(Value, E, Result);
5557 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00005558
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005559 bool Success(CharUnits Size, const Expr *E) {
5560 return Success(Size.getQuantity(), E);
5561 }
5562
Richard Smith1aa0be82012-03-03 22:46:17 +00005563 bool Success(const APValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00005564 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00005565 Result = V;
5566 return true;
5567 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005568 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00005569 }
Mike Stump1eb44332009-09-09 15:08:12 +00005570
Richard Smith51201882011-12-30 21:15:51 +00005571 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00005572
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005573 //===--------------------------------------------------------------------===//
5574 // Visitor Methods
5575 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00005576
Chris Lattner4c4867e2008-07-12 00:38:25 +00005577 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00005578 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00005579 }
5580 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00005581 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00005582 }
Eli Friedman04309752009-11-24 05:28:59 +00005583
5584 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5585 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005586 if (CheckReferencedDecl(E, E->getDecl()))
5587 return true;
5588
5589 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00005590 }
5591 bool VisitMemberExpr(const MemberExpr *E) {
5592 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00005593 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00005594 return true;
5595 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005596
5597 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00005598 }
5599
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005600 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00005601 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005602 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00005603 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00005604
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005605 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005606 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00005607
Anders Carlsson3068d112008-11-16 19:01:22 +00005608 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00005609 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00005610 }
Mike Stump1eb44332009-09-09 15:08:12 +00005611
Ted Kremenekebcb57a2012-03-06 20:05:56 +00005612 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5613 return Success(E->getValue(), E);
5614 }
5615
Richard Smithf10d9172011-10-11 21:43:33 +00005616 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00005617 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00005618 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00005619 }
5620
Sebastian Redl64b45f72009-01-05 20:52:13 +00005621 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00005622 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00005623 }
5624
Francois Pichet6ad6f282010-12-07 00:08:36 +00005625 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
5626 return Success(E->getValue(), E);
5627 }
5628
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00005629 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5630 return Success(E->getValue(), E);
5631 }
5632
John Wiegley21ff2e52011-04-28 00:16:57 +00005633 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5634 return Success(E->getValue(), E);
5635 }
5636
John Wiegley55262202011-04-25 06:54:41 +00005637 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5638 return Success(E->getValue(), E);
5639 }
5640
Eli Friedman722c7172009-02-28 03:59:05 +00005641 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00005642 bool VisitUnaryImag(const UnaryOperator *E);
5643
Sebastian Redl295995c2010-09-10 20:55:47 +00005644 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00005645 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00005646
Chris Lattnerfcee0012008-07-11 21:24:13 +00005647private:
Ken Dyck8b752f12010-01-27 17:10:57 +00005648 CharUnits GetAlignOfExpr(const Expr *E);
5649 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005650 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005651 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00005652 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005653};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005654} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00005655
Richard Smithc49bd112011-10-28 17:51:58 +00005656/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
5657/// produce either the integer value or a pointer.
5658///
5659/// GCC has a heinous extension which folds casts between pointer types and
5660/// pointer-sized integral types. We support this by allowing the evaluation of
5661/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
5662/// Some simple arithmetic on such values is supported (they are treated much
5663/// like char*).
Richard Smith1aa0be82012-03-03 22:46:17 +00005664static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00005665 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005666 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005667 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00005668}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005669
Richard Smithf48fdb02011-12-09 22:58:01 +00005670static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith1aa0be82012-03-03 22:46:17 +00005671 APValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00005672 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00005673 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005674 if (!Val.isInt()) {
5675 // FIXME: It would be better to produce the diagnostic for casting
5676 // a pointer to an integer.
Richard Smith5cfc7d82012-03-15 04:53:45 +00005677 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00005678 return false;
5679 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005680 Result = Val.getInt();
5681 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00005682}
Anders Carlsson650c92f2008-07-08 15:34:11 +00005683
Richard Smithf48fdb02011-12-09 22:58:01 +00005684/// Check whether the given declaration can be directly converted to an integral
5685/// rvalue. If not, no diagnostic is produced; there are other things we can
5686/// try.
Eli Friedman04309752009-11-24 05:28:59 +00005687bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00005688 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00005689 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00005690 // Check for signedness/width mismatches between E type and ECD value.
5691 bool SameSign = (ECD->getInitVal().isSigned()
5692 == E->getType()->isSignedIntegerOrEnumerationType());
5693 bool SameWidth = (ECD->getInitVal().getBitWidth()
5694 == Info.Ctx.getIntWidth(E->getType()));
5695 if (SameSign && SameWidth)
5696 return Success(ECD->getInitVal(), E);
5697 else {
5698 // Get rid of mismatch (otherwise Success assertions will fail)
5699 // by computing a new value matching the type of E.
5700 llvm::APSInt Val = ECD->getInitVal();
5701 if (!SameSign)
5702 Val.setIsSigned(!ECD->getInitVal().isSigned());
5703 if (!SameWidth)
5704 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
5705 return Success(Val, E);
5706 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00005707 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005708 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00005709}
5710
Chris Lattnera4d55d82008-10-06 06:40:35 +00005711/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
5712/// as GCC.
5713static int EvaluateBuiltinClassifyType(const CallExpr *E) {
5714 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005715 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00005716 enum gcc_type_class {
5717 no_type_class = -1,
5718 void_type_class, integer_type_class, char_type_class,
5719 enumeral_type_class, boolean_type_class,
5720 pointer_type_class, reference_type_class, offset_type_class,
5721 real_type_class, complex_type_class,
5722 function_type_class, method_type_class,
5723 record_type_class, union_type_class,
5724 array_type_class, string_type_class,
5725 lang_type_class
5726 };
Mike Stump1eb44332009-09-09 15:08:12 +00005727
5728 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00005729 // ideal, however it is what gcc does.
5730 if (E->getNumArgs() == 0)
5731 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00005732
Chris Lattnera4d55d82008-10-06 06:40:35 +00005733 QualType ArgTy = E->getArg(0)->getType();
5734 if (ArgTy->isVoidType())
5735 return void_type_class;
5736 else if (ArgTy->isEnumeralType())
5737 return enumeral_type_class;
5738 else if (ArgTy->isBooleanType())
5739 return boolean_type_class;
5740 else if (ArgTy->isCharType())
5741 return string_type_class; // gcc doesn't appear to use char_type_class
5742 else if (ArgTy->isIntegerType())
5743 return integer_type_class;
5744 else if (ArgTy->isPointerType())
5745 return pointer_type_class;
5746 else if (ArgTy->isReferenceType())
5747 return reference_type_class;
5748 else if (ArgTy->isRealType())
5749 return real_type_class;
5750 else if (ArgTy->isComplexType())
5751 return complex_type_class;
5752 else if (ArgTy->isFunctionType())
5753 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00005754 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00005755 return record_type_class;
5756 else if (ArgTy->isUnionType())
5757 return union_type_class;
5758 else if (ArgTy->isArrayType())
5759 return array_type_class;
5760 else if (ArgTy->isUnionType())
5761 return union_type_class;
5762 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00005763 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00005764}
5765
Richard Smith80d4b552011-12-28 19:48:30 +00005766/// EvaluateBuiltinConstantPForLValue - Determine the result of
5767/// __builtin_constant_p when applied to the given lvalue.
5768///
5769/// An lvalue is only "constant" if it is a pointer or reference to the first
5770/// character of a string literal.
5771template<typename LValue>
5772static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregor8e55ed12012-03-11 02:23:56 +00005773 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith80d4b552011-12-28 19:48:30 +00005774 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
5775}
5776
5777/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
5778/// GCC as we can manage.
5779static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
5780 QualType ArgType = Arg->getType();
5781
5782 // __builtin_constant_p always has one operand. The rules which gcc follows
5783 // are not precisely documented, but are as follows:
5784 //
5785 // - If the operand is of integral, floating, complex or enumeration type,
5786 // and can be folded to a known value of that type, it returns 1.
5787 // - If the operand and can be folded to a pointer to the first character
5788 // of a string literal (or such a pointer cast to an integral type), it
5789 // returns 1.
5790 //
5791 // Otherwise, it returns 0.
5792 //
5793 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
5794 // its support for this does not currently work.
5795 if (ArgType->isIntegralOrEnumerationType()) {
5796 Expr::EvalResult Result;
5797 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
5798 return false;
5799
5800 APValue &V = Result.Val;
5801 if (V.getKind() == APValue::Int)
5802 return true;
5803
5804 return EvaluateBuiltinConstantPForLValue(V);
5805 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
5806 return Arg->isEvaluatable(Ctx);
5807 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
5808 LValue LV;
5809 Expr::EvalStatus Status;
5810 EvalInfo Info(Ctx, Status);
5811 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
5812 : EvaluatePointer(Arg, LV, Info)) &&
5813 !Status.HasSideEffects)
5814 return EvaluateBuiltinConstantPForLValue(LV);
5815 }
5816
5817 // Anything else isn't considered to be sufficiently constant.
5818 return false;
5819}
5820
John McCall42c8f872010-05-10 23:27:23 +00005821/// Retrieves the "underlying object type" of the given expression,
5822/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005823QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
5824 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
5825 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00005826 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005827 } else if (const Expr *E = B.get<const Expr*>()) {
5828 if (isa<CompoundLiteralExpr>(E))
5829 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00005830 }
5831
5832 return QualType();
5833}
5834
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005835bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00005836 LValue Base;
Richard Smithc6794852012-05-23 04:13:20 +00005837
5838 {
5839 // The operand of __builtin_object_size is never evaluated for side-effects.
5840 // If there are any, but we can determine the pointed-to object anyway, then
5841 // ignore the side-effects.
5842 SpeculativeEvaluationRAII SpeculativeEval(Info);
5843 if (!EvaluatePointer(E->getArg(0), Base, Info))
5844 return false;
5845 }
John McCall42c8f872010-05-10 23:27:23 +00005846
5847 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005848 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00005849
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005850 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00005851 if (T.isNull() ||
5852 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00005853 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00005854 T->isVariablyModifiedType() ||
5855 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00005856 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00005857
5858 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
5859 CharUnits Offset = Base.getLValueOffset();
5860
5861 if (!Offset.isNegative() && Offset <= Size)
5862 Size -= Offset;
5863 else
5864 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005865 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00005866}
5867
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005868bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith2c39d712012-04-13 00:45:38 +00005869 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00005870 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005871 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00005872
5873 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00005874 if (TryEvaluateBuiltinObjectSize(E))
5875 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00005876
Richard Smith8ae4ec22012-08-07 04:16:51 +00005877 // If evaluating the argument has side-effects, we can't determine the size
5878 // of the object, and so we lower it to unknown now. CodeGen relies on us to
5879 // handle all cases where the expression has side-effects.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00005880 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005881 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00005882 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00005883 return Success(0, E);
5884 }
Mike Stumpc4c90452009-10-27 22:09:17 +00005885
Richard Smithc6794852012-05-23 04:13:20 +00005886 // Expression had no side effects, but we couldn't statically determine the
5887 // size of the referenced object.
Richard Smithf48fdb02011-12-09 22:58:01 +00005888 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00005889 }
5890
Benjamin Kramerd1900572012-10-06 14:42:22 +00005891 case Builtin::BI__builtin_bswap16:
Richard Smith70d38f32012-09-28 20:20:52 +00005892 case Builtin::BI__builtin_bswap32:
5893 case Builtin::BI__builtin_bswap64: {
5894 APSInt Val;
5895 if (!EvaluateInteger(E->getArg(0), Val, Info))
5896 return false;
5897
5898 return Success(Val.byteSwap(), E);
5899 }
5900
Richard Smithacaf72a2013-06-13 06:26:32 +00005901 case Builtin::BI__builtin_classify_type:
5902 return Success(EvaluateBuiltinClassifyType(E), E);
5903
5904 // FIXME: BI__builtin_clrsb
5905 // FIXME: BI__builtin_clrsbl
5906 // FIXME: BI__builtin_clrsbll
5907
Richard Smith4dbf4082013-06-13 05:04:16 +00005908 case Builtin::BI__builtin_clz:
5909 case Builtin::BI__builtin_clzl:
5910 case Builtin::BI__builtin_clzll: {
5911 APSInt Val;
5912 if (!EvaluateInteger(E->getArg(0), Val, Info))
5913 return false;
5914 if (!Val)
5915 return Error(E);
5916
5917 return Success(Val.countLeadingZeros(), E);
5918 }
5919
Richard Smithacaf72a2013-06-13 06:26:32 +00005920 case Builtin::BI__builtin_constant_p:
5921 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
5922
Richard Smith4dbf4082013-06-13 05:04:16 +00005923 case Builtin::BI__builtin_ctz:
5924 case Builtin::BI__builtin_ctzl:
5925 case Builtin::BI__builtin_ctzll: {
5926 APSInt Val;
5927 if (!EvaluateInteger(E->getArg(0), Val, Info))
5928 return false;
5929 if (!Val)
5930 return Error(E);
5931
5932 return Success(Val.countTrailingZeros(), E);
5933 }
5934
Richard Smithacaf72a2013-06-13 06:26:32 +00005935 case Builtin::BI__builtin_eh_return_data_regno: {
5936 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
5937 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
5938 return Success(Operand, E);
5939 }
5940
5941 case Builtin::BI__builtin_expect:
5942 return Visit(E->getArg(0));
5943
5944 case Builtin::BI__builtin_ffs:
5945 case Builtin::BI__builtin_ffsl:
5946 case Builtin::BI__builtin_ffsll: {
5947 APSInt Val;
5948 if (!EvaluateInteger(E->getArg(0), Val, Info))
5949 return false;
5950
5951 unsigned N = Val.countTrailingZeros();
5952 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
5953 }
5954
5955 case Builtin::BI__builtin_fpclassify: {
5956 APFloat Val(0.0);
5957 if (!EvaluateFloat(E->getArg(5), Val, Info))
5958 return false;
5959 unsigned Arg;
5960 switch (Val.getCategory()) {
5961 case APFloat::fcNaN: Arg = 0; break;
5962 case APFloat::fcInfinity: Arg = 1; break;
5963 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
5964 case APFloat::fcZero: Arg = 4; break;
5965 }
5966 return Visit(E->getArg(Arg));
5967 }
5968
5969 case Builtin::BI__builtin_isinf_sign: {
5970 APFloat Val(0.0);
Richard Smith5350ded2013-06-13 06:31:13 +00005971 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smithacaf72a2013-06-13 06:26:32 +00005972 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
5973 }
5974
5975 case Builtin::BI__builtin_parity:
5976 case Builtin::BI__builtin_parityl:
5977 case Builtin::BI__builtin_parityll: {
5978 APSInt Val;
5979 if (!EvaluateInteger(E->getArg(0), Val, Info))
5980 return false;
5981
5982 return Success(Val.countPopulation() % 2, E);
5983 }
5984
Richard Smith4dbf4082013-06-13 05:04:16 +00005985 case Builtin::BI__builtin_popcount:
5986 case Builtin::BI__builtin_popcountl:
5987 case Builtin::BI__builtin_popcountll: {
5988 APSInt Val;
5989 if (!EvaluateInteger(E->getArg(0), Val, Info))
5990 return false;
5991
5992 return Success(Val.countPopulation(), E);
5993 }
5994
Douglas Gregor5726d402010-09-10 06:27:15 +00005995 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00005996 // A call to strlen is not a constant expression.
Richard Smith80ad52f2013-01-02 11:42:31 +00005997 if (Info.getLangOpts().CPlusPlus11)
Richard Smith5cfc7d82012-03-15 04:53:45 +00005998 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith40b993a2012-01-18 03:06:12 +00005999 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6000 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00006001 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith40b993a2012-01-18 03:06:12 +00006002 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00006003 case Builtin::BI__builtin_strlen:
6004 // As an extension, we support strlen() and __builtin_strlen() as constant
6005 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00006006 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00006007 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
6008 // The string literal may have embedded null characters. Find the first
6009 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006010 StringRef Str = S->getString();
6011 StringRef::size_type Pos = Str.find(0);
6012 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00006013 Str = Str.substr(0, Pos);
6014
6015 return Success(Str.size(), E);
6016 }
6017
Richard Smithf48fdb02011-12-09 22:58:01 +00006018 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00006019
Richard Smith2c39d712012-04-13 00:45:38 +00006020 case Builtin::BI__atomic_always_lock_free:
Richard Smithfafbf062012-04-11 17:55:32 +00006021 case Builtin::BI__atomic_is_lock_free:
6022 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedman454b57a2011-10-17 21:44:23 +00006023 APSInt SizeVal;
6024 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6025 return false;
6026
6027 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6028 // of two less than the maximum inline atomic width, we know it is
6029 // lock-free. If the size isn't a power of two, or greater than the
6030 // maximum alignment where we promote atomics, we know it is not lock-free
6031 // (at least not in the sense of atomic_is_lock_free). Otherwise,
6032 // the answer can only be determined at runtime; for example, 16-byte
6033 // atomics have lock-free implementations on some, but not all,
6034 // x86-64 processors.
6035
6036 // Check power-of-two.
6037 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith2c39d712012-04-13 00:45:38 +00006038 if (Size.isPowerOfTwo()) {
6039 // Check against inlining width.
6040 unsigned InlineWidthBits =
6041 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6042 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6043 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6044 Size == CharUnits::One() ||
6045 E->getArg(1)->isNullPointerConstant(Info.Ctx,
6046 Expr::NPC_NeverValueDependent))
6047 // OK, we will inline appropriately-aligned operations of this size,
6048 // and _Atomic(T) is appropriately-aligned.
6049 return Success(1, E);
Eli Friedman454b57a2011-10-17 21:44:23 +00006050
Richard Smith2c39d712012-04-13 00:45:38 +00006051 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6052 castAs<PointerType>()->getPointeeType();
6053 if (!PointeeType->isIncompleteType() &&
6054 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6055 // OK, we will inline operations on this object.
6056 return Success(1, E);
6057 }
6058 }
6059 }
Eli Friedman454b57a2011-10-17 21:44:23 +00006060
Richard Smith2c39d712012-04-13 00:45:38 +00006061 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6062 Success(0, E) : Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00006063 }
Chris Lattner019f4e82008-10-06 05:28:25 +00006064 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00006065}
Anders Carlsson650c92f2008-07-08 15:34:11 +00006066
Richard Smith625b8072011-10-31 01:37:14 +00006067static bool HasSameBase(const LValue &A, const LValue &B) {
6068 if (!A.getLValueBase())
6069 return !B.getLValueBase();
6070 if (!B.getLValueBase())
6071 return false;
6072
Richard Smith1bf9a9e2011-11-12 22:28:03 +00006073 if (A.getLValueBase().getOpaqueValue() !=
6074 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00006075 const Decl *ADecl = GetLValueBaseDecl(A);
6076 if (!ADecl)
6077 return false;
6078 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00006079 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00006080 return false;
6081 }
6082
6083 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith83587db2012-02-15 02:18:13 +00006084 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith625b8072011-10-31 01:37:14 +00006085}
6086
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006087namespace {
Richard Smithc49bd112011-10-28 17:51:58 +00006088
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006089/// \brief Data recursive integer evaluator of certain binary operators.
6090///
6091/// We use a data recursive algorithm for binary operators so that we are able
6092/// to handle extreme cases of chained binary operators without causing stack
6093/// overflow.
6094class DataRecursiveIntBinOpEvaluator {
6095 struct EvalResult {
6096 APValue Val;
6097 bool Failed;
6098
6099 EvalResult() : Failed(false) { }
6100
6101 void swap(EvalResult &RHS) {
6102 Val.swap(RHS.Val);
6103 Failed = RHS.Failed;
6104 RHS.Failed = false;
6105 }
6106 };
6107
6108 struct Job {
6109 const Expr *E;
6110 EvalResult LHSResult; // meaningful only for binary operator expression.
6111 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
6112
6113 Job() : StoredInfo(0) { }
6114 void startSpeculativeEval(EvalInfo &Info) {
6115 OldEvalStatus = Info.EvalStatus;
6116 Info.EvalStatus.Diag = 0;
6117 StoredInfo = &Info;
6118 }
6119 ~Job() {
6120 if (StoredInfo) {
6121 StoredInfo->EvalStatus = OldEvalStatus;
6122 }
6123 }
6124 private:
6125 EvalInfo *StoredInfo; // non-null if status changed.
6126 Expr::EvalStatus OldEvalStatus;
6127 };
6128
6129 SmallVector<Job, 16> Queue;
6130
6131 IntExprEvaluator &IntEval;
6132 EvalInfo &Info;
6133 APValue &FinalResult;
6134
6135public:
6136 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
6137 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
6138
6139 /// \brief True if \param E is a binary operator that we are going to handle
6140 /// data recursively.
6141 /// We handle binary operators that are comma, logical, or that have operands
6142 /// with integral or enumeration type.
6143 static bool shouldEnqueue(const BinaryOperator *E) {
6144 return E->getOpcode() == BO_Comma ||
6145 E->isLogicalOp() ||
6146 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6147 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedmana6afa762008-11-13 06:09:17 +00006148 }
6149
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006150 bool Traverse(const BinaryOperator *E) {
6151 enqueue(E);
6152 EvalResult PrevResult;
Richard Trieub7783052012-03-21 23:30:30 +00006153 while (!Queue.empty())
6154 process(PrevResult);
6155
6156 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00006157
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006158 FinalResult.swap(PrevResult.Val);
6159 return true;
6160 }
6161
6162private:
6163 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6164 return IntEval.Success(Value, E, Result);
6165 }
6166 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6167 return IntEval.Success(Value, E, Result);
6168 }
6169 bool Error(const Expr *E) {
6170 return IntEval.Error(E);
6171 }
6172 bool Error(const Expr *E, diag::kind D) {
6173 return IntEval.Error(E, D);
6174 }
6175
6176 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6177 return Info.CCEDiag(E, D);
6178 }
6179
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00006180 // \brief Returns true if visiting the RHS is necessary, false otherwise.
6181 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006182 bool &SuppressRHSDiags);
6183
6184 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6185 const BinaryOperator *E, APValue &Result);
6186
6187 void EvaluateExpr(const Expr *E, EvalResult &Result) {
6188 Result.Failed = !Evaluate(Result.Val, Info, E);
6189 if (Result.Failed)
6190 Result.Val = APValue();
6191 }
6192
Richard Trieub7783052012-03-21 23:30:30 +00006193 void process(EvalResult &Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006194
6195 void enqueue(const Expr *E) {
6196 E = E->IgnoreParens();
6197 Queue.resize(Queue.size()+1);
6198 Queue.back().E = E;
6199 Queue.back().Kind = Job::AnyExprKind;
6200 }
6201};
6202
6203}
6204
6205bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00006206 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006207 bool &SuppressRHSDiags) {
6208 if (E->getOpcode() == BO_Comma) {
6209 // Ignore LHS but note if we could not evaluate it.
6210 if (LHSResult.Failed)
6211 Info.EvalStatus.HasSideEffects = true;
6212 return true;
6213 }
6214
6215 if (E->isLogicalOp()) {
6216 bool lhsResult;
6217 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00006218 // We were able to evaluate the LHS, see if we can get away with not
6219 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006220 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00006221 Success(lhsResult, E, LHSResult.Val);
6222 return false; // Ignore RHS
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00006223 }
6224 } else {
6225 // Since we weren't able to evaluate the left hand side, it
6226 // must have had side effects.
6227 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006228
6229 // We can't evaluate the LHS; however, sometimes the result
6230 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6231 // Don't ignore RHS and suppress diagnostics from this arm.
6232 SuppressRHSDiags = true;
6233 }
6234
6235 return true;
6236 }
6237
6238 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6239 E->getRHS()->getType()->isIntegralOrEnumerationType());
6240
6241 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00006242 return false; // Ignore RHS;
6243
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006244 return true;
6245}
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00006246
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006247bool DataRecursiveIntBinOpEvaluator::
6248 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6249 const BinaryOperator *E, APValue &Result) {
6250 if (E->getOpcode() == BO_Comma) {
6251 if (RHSResult.Failed)
6252 return false;
6253 Result = RHSResult.Val;
6254 return true;
6255 }
6256
6257 if (E->isLogicalOp()) {
6258 bool lhsResult, rhsResult;
6259 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
6260 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
6261
6262 if (LHSIsOK) {
6263 if (RHSIsOK) {
6264 if (E->getOpcode() == BO_LOr)
6265 return Success(lhsResult || rhsResult, E, Result);
6266 else
6267 return Success(lhsResult && rhsResult, E, Result);
6268 }
6269 } else {
6270 if (RHSIsOK) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00006271 // We can't evaluate the LHS; however, sometimes the result
6272 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6273 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006274 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00006275 }
6276 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006277
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00006278 return false;
6279 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006280
6281 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6282 E->getRHS()->getType()->isIntegralOrEnumerationType());
6283
6284 if (LHSResult.Failed || RHSResult.Failed)
6285 return false;
6286
6287 const APValue &LHSVal = LHSResult.Val;
6288 const APValue &RHSVal = RHSResult.Val;
6289
6290 // Handle cases like (unsigned long)&a + 4.
6291 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
6292 Result = LHSVal;
6293 CharUnits AdditionalOffset = CharUnits::fromQuantity(
6294 RHSVal.getInt().getZExtValue());
6295 if (E->getOpcode() == BO_Add)
6296 Result.getLValueOffset() += AdditionalOffset;
6297 else
6298 Result.getLValueOffset() -= AdditionalOffset;
6299 return true;
6300 }
6301
6302 // Handle cases like 4 + (unsigned long)&a
6303 if (E->getOpcode() == BO_Add &&
6304 RHSVal.isLValue() && LHSVal.isInt()) {
6305 Result = RHSVal;
6306 Result.getLValueOffset() += CharUnits::fromQuantity(
6307 LHSVal.getInt().getZExtValue());
6308 return true;
6309 }
6310
6311 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
6312 // Handle (intptr_t)&&A - (intptr_t)&&B.
6313 if (!LHSVal.getLValueOffset().isZero() ||
6314 !RHSVal.getLValueOffset().isZero())
6315 return false;
6316 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
6317 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
6318 if (!LHSExpr || !RHSExpr)
6319 return false;
6320 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6321 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6322 if (!LHSAddrExpr || !RHSAddrExpr)
6323 return false;
6324 // Make sure both labels come from the same function.
6325 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6326 RHSAddrExpr->getLabel()->getDeclContext())
6327 return false;
6328 Result = APValue(LHSAddrExpr, RHSAddrExpr);
6329 return true;
6330 }
Richard Smithd20afcb2013-05-07 04:50:00 +00006331
6332 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006333 if (!LHSVal.isInt() || !RHSVal.isInt())
6334 return Error(E);
Richard Smithd20afcb2013-05-07 04:50:00 +00006335
6336 // Set up the width and signedness manually, in case it can't be deduced
6337 // from the operation we're performing.
6338 // FIXME: Don't do this in the cases where we can deduce it.
6339 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
6340 E->getType()->isUnsignedIntegerOrEnumerationType());
6341 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
6342 RHSVal.getInt(), Value))
6343 return false;
6344 return Success(Value, E, Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006345}
6346
Richard Trieub7783052012-03-21 23:30:30 +00006347void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006348 Job &job = Queue.back();
6349
6350 switch (job.Kind) {
6351 case Job::AnyExprKind: {
6352 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
6353 if (shouldEnqueue(Bop)) {
6354 job.Kind = Job::BinOpKind;
6355 enqueue(Bop->getLHS());
Richard Trieub7783052012-03-21 23:30:30 +00006356 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006357 }
6358 }
6359
6360 EvaluateExpr(job.E, Result);
6361 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00006362 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006363 }
6364
6365 case Job::BinOpKind: {
6366 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006367 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00006368 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006369 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00006370 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006371 }
6372 if (SuppressRHSDiags)
6373 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00006374 job.LHSResult.swap(Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006375 job.Kind = Job::BinOpVisitedLHSKind;
6376 enqueue(Bop->getRHS());
Richard Trieub7783052012-03-21 23:30:30 +00006377 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006378 }
6379
6380 case Job::BinOpVisitedLHSKind: {
6381 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6382 EvalResult RHS;
6383 RHS.swap(Result);
Richard Trieub7783052012-03-21 23:30:30 +00006384 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006385 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00006386 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006387 }
6388 }
6389
6390 llvm_unreachable("Invalid Job::Kind!");
6391}
6392
6393bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6394 if (E->isAssignmentOp())
6395 return Error(E);
6396
6397 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
6398 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00006399
Anders Carlsson286f85e2008-11-16 07:17:21 +00006400 QualType LHSTy = E->getLHS()->getType();
6401 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00006402
6403 if (LHSTy->isAnyComplexType()) {
6404 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00006405 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00006406
Richard Smith745f5142012-01-27 01:14:48 +00006407 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
6408 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00006409 return false;
6410
Richard Smith745f5142012-01-27 01:14:48 +00006411 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00006412 return false;
6413
6414 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006415 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00006416 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00006417 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00006418 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
6419
John McCall2de56d12010-08-25 11:45:40 +00006420 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00006421 return Success((CR_r == APFloat::cmpEqual &&
6422 CR_i == APFloat::cmpEqual), E);
6423 else {
John McCall2de56d12010-08-25 11:45:40 +00006424 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00006425 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00006426 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00006427 CR_r == APFloat::cmpLessThan ||
6428 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00006429 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00006430 CR_i == APFloat::cmpLessThan ||
6431 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00006432 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00006433 } else {
John McCall2de56d12010-08-25 11:45:40 +00006434 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00006435 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
6436 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
6437 else {
John McCall2de56d12010-08-25 11:45:40 +00006438 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00006439 "Invalid compex comparison.");
6440 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
6441 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
6442 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00006443 }
6444 }
Mike Stump1eb44332009-09-09 15:08:12 +00006445
Anders Carlsson286f85e2008-11-16 07:17:21 +00006446 if (LHSTy->isRealFloatingType() &&
6447 RHSTy->isRealFloatingType()) {
6448 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00006449
Richard Smith745f5142012-01-27 01:14:48 +00006450 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
6451 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00006452 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006453
Richard Smith745f5142012-01-27 01:14:48 +00006454 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00006455 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006456
Anders Carlsson286f85e2008-11-16 07:17:21 +00006457 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00006458
Anders Carlsson286f85e2008-11-16 07:17:21 +00006459 switch (E->getOpcode()) {
6460 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00006461 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00006462 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00006463 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00006464 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00006465 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00006466 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00006467 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00006468 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00006469 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00006470 E);
John McCall2de56d12010-08-25 11:45:40 +00006471 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00006472 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00006473 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00006474 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00006475 || CR == APFloat::cmpLessThan
6476 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00006477 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00006478 }
Mike Stump1eb44332009-09-09 15:08:12 +00006479
Eli Friedmanad02d7d2009-04-28 19:17:36 +00006480 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00006481 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00006482 LValue LHSValue, RHSValue;
6483
6484 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6485 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00006486 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00006487
Richard Smith745f5142012-01-27 01:14:48 +00006488 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00006489 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00006490
Richard Smith625b8072011-10-31 01:37:14 +00006491 // Reject differing bases from the normal codepath; we special-case
6492 // comparisons to null.
6493 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00006494 if (E->getOpcode() == BO_Sub) {
6495 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00006496 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6497 return false;
6498 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramer7b2f93c2012-10-03 14:15:39 +00006499 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedman65639282012-01-04 23:13:47 +00006500 if (!LHSExpr || !RHSExpr)
6501 return false;
6502 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6503 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6504 if (!LHSAddrExpr || !RHSAddrExpr)
6505 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00006506 // Make sure both labels come from the same function.
6507 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6508 RHSAddrExpr->getLabel()->getDeclContext())
6509 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00006510 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedman65639282012-01-04 23:13:47 +00006511 return true;
6512 }
Richard Smith9e36b532011-10-31 05:11:32 +00006513 // Inequalities and subtractions between unrelated pointers have
6514 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00006515 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00006516 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00006517 // A constant address may compare equal to the address of a symbol.
6518 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00006519 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00006520 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6521 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00006522 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00006523 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00006524 // distinct addresses. In clang, the result of such a comparison is
6525 // unspecified, so it is not a constant expression. However, we do know
6526 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00006527 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6528 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00006529 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00006530 // We can't tell whether weak symbols will end up pointing to the same
6531 // object.
6532 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00006533 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00006534 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00006535 // (Note that clang defaults to -fmerge-all-constants, which can
6536 // lead to inconsistent results for comparisons involving the address
6537 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00006538 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00006539 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00006540
Richard Smith15efc4d2012-02-01 08:10:20 +00006541 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
6542 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
6543
Richard Smithf15fda02012-02-02 01:16:57 +00006544 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
6545 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
6546
John McCall2de56d12010-08-25 11:45:40 +00006547 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00006548 // C++11 [expr.add]p6:
6549 // Unless both pointers point to elements of the same array object, or
6550 // one past the last element of the array object, the behavior is
6551 // undefined.
6552 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6553 !AreElementsOfSameArray(getType(LHSValue.Base),
6554 LHSDesignator, RHSDesignator))
6555 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
6556
Chris Lattner4992bdd2010-04-20 17:13:14 +00006557 QualType Type = E->getLHS()->getType();
6558 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00006559
Richard Smith180f4792011-11-10 06:34:14 +00006560 CharUnits ElementSize;
Richard Smith74e1ad92012-02-16 02:46:34 +00006561 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smith180f4792011-11-10 06:34:14 +00006562 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00006563
Richard Smith15efc4d2012-02-01 08:10:20 +00006564 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
6565 // and produce incorrect results when it overflows. Such behavior
6566 // appears to be non-conforming, but is common, so perhaps we should
6567 // assume the standard intended for such cases to be undefined behavior
6568 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00006569
Richard Smith15efc4d2012-02-01 08:10:20 +00006570 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
6571 // overflow in the final conversion to ptrdiff_t.
6572 APSInt LHS(
6573 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
6574 APSInt RHS(
6575 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
6576 APSInt ElemSize(
6577 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
6578 APSInt TrueResult = (LHS - RHS) / ElemSize;
6579 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
6580
6581 if (Result.extend(65) != TrueResult)
6582 HandleOverflow(Info, E, TrueResult, E->getType());
6583 return Success(Result, E);
6584 }
Richard Smith82f28582012-01-31 06:41:30 +00006585
6586 // C++11 [expr.rel]p3:
6587 // Pointers to void (after pointer conversions) can be compared, with a
6588 // result defined as follows: If both pointers represent the same
6589 // address or are both the null pointer value, the result is true if the
6590 // operator is <= or >= and false otherwise; otherwise the result is
6591 // unspecified.
6592 // We interpret this as applying to pointers to *cv* void.
6593 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00006594 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00006595 CCEDiag(E, diag::note_constexpr_void_comparison);
6596
Richard Smithf15fda02012-02-02 01:16:57 +00006597 // C++11 [expr.rel]p2:
6598 // - If two pointers point to non-static data members of the same object,
6599 // or to subobjects or array elements fo such members, recursively, the
6600 // pointer to the later declared member compares greater provided the
6601 // two members have the same access control and provided their class is
6602 // not a union.
6603 // [...]
6604 // - Otherwise pointer comparisons are unspecified.
6605 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6606 E->isRelationalOp()) {
6607 bool WasArrayIndex;
6608 unsigned Mismatch =
6609 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
6610 RHSDesignator, WasArrayIndex);
6611 // At the point where the designators diverge, the comparison has a
6612 // specified value if:
6613 // - we are comparing array indices
6614 // - we are comparing fields of a union, or fields with the same access
6615 // Otherwise, the result is unspecified and thus the comparison is not a
6616 // constant expression.
6617 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
6618 Mismatch < RHSDesignator.Entries.size()) {
6619 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
6620 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
6621 if (!LF && !RF)
6622 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
6623 else if (!LF)
6624 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6625 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
6626 << RF->getParent() << RF;
6627 else if (!RF)
6628 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6629 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
6630 << LF->getParent() << LF;
6631 else if (!LF->getParent()->isUnion() &&
6632 LF->getAccess() != RF->getAccess())
6633 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
6634 << LF << LF->getAccess() << RF << RF->getAccess()
6635 << LF->getParent();
6636 }
6637 }
6638
Eli Friedmana3169882012-04-16 04:30:08 +00006639 // The comparison here must be unsigned, and performed with the same
6640 // width as the pointer.
Eli Friedmana3169882012-04-16 04:30:08 +00006641 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
6642 uint64_t CompareLHS = LHSOffset.getQuantity();
6643 uint64_t CompareRHS = RHSOffset.getQuantity();
6644 assert(PtrSize <= 64 && "Unexpected pointer width");
6645 uint64_t Mask = ~0ULL >> (64 - PtrSize);
6646 CompareLHS &= Mask;
6647 CompareRHS &= Mask;
6648
Eli Friedman28503762012-04-16 19:23:57 +00006649 // If there is a base and this is a relational operator, we can only
6650 // compare pointers within the object in question; otherwise, the result
6651 // depends on where the object is located in memory.
6652 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
6653 QualType BaseTy = getType(LHSValue.Base);
6654 if (BaseTy->isIncompleteType())
6655 return Error(E);
6656 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
6657 uint64_t OffsetLimit = Size.getQuantity();
6658 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
6659 return Error(E);
6660 }
6661
Richard Smith625b8072011-10-31 01:37:14 +00006662 switch (E->getOpcode()) {
6663 default: llvm_unreachable("missing comparison operator");
Eli Friedmana3169882012-04-16 04:30:08 +00006664 case BO_LT: return Success(CompareLHS < CompareRHS, E);
6665 case BO_GT: return Success(CompareLHS > CompareRHS, E);
6666 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
6667 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
6668 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
6669 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00006670 }
Anders Carlsson3068d112008-11-16 19:01:22 +00006671 }
6672 }
Richard Smithb02e4622012-02-01 01:42:44 +00006673
6674 if (LHSTy->isMemberPointerType()) {
6675 assert(E->isEqualityOp() && "unexpected member pointer operation");
6676 assert(RHSTy->isMemberPointerType() && "invalid comparison");
6677
6678 MemberPtr LHSValue, RHSValue;
6679
6680 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
6681 if (!LHSOK && Info.keepEvaluatingAfterFailure())
6682 return false;
6683
6684 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6685 return false;
6686
6687 // C++11 [expr.eq]p2:
6688 // If both operands are null, they compare equal. Otherwise if only one is
6689 // null, they compare unequal.
6690 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
6691 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
6692 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6693 }
6694
6695 // Otherwise if either is a pointer to a virtual member function, the
6696 // result is unspecified.
6697 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
6698 if (MD->isVirtual())
6699 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6700 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
6701 if (MD->isVirtual())
6702 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6703
6704 // Otherwise they compare equal if and only if they would refer to the
6705 // same member of the same most derived object or the same subobject if
6706 // they were dereferenced with a hypothetical object of the associated
6707 // class type.
6708 bool Equal = LHSValue == RHSValue;
6709 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6710 }
6711
Richard Smith26f2cac2012-02-14 22:35:28 +00006712 if (LHSTy->isNullPtrType()) {
6713 assert(E->isComparisonOp() && "unexpected nullptr operation");
6714 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
6715 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
6716 // are compared, the result is true of the operator is <=, >= or ==, and
6717 // false otherwise.
6718 BinaryOperator::Opcode Opcode = E->getOpcode();
6719 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
6720 }
6721
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006722 assert((!LHSTy->isIntegralOrEnumerationType() ||
6723 !RHSTy->isIntegralOrEnumerationType()) &&
6724 "DataRecursiveIntBinOpEvaluator should have handled integral types");
6725 // We can't continue from here for non-integral types.
6726 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00006727}
6728
Ken Dyck8b752f12010-01-27 17:10:57 +00006729CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00006730 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
6731 // result shall be the alignment of the referenced type."
6732 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6733 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00006734
6735 // __alignof is defined to return the preferred alignment.
6736 return Info.Ctx.toCharUnitsFromBits(
6737 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00006738}
6739
Ken Dyck8b752f12010-01-27 17:10:57 +00006740CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00006741 E = E->IgnoreParens();
6742
John McCall10f6f062013-05-06 07:40:34 +00006743 // The kinds of expressions that we have special-case logic here for
6744 // should be kept up to date with the special checks for those
6745 // expressions in Sema.
6746
Chris Lattneraf707ab2009-01-24 21:53:27 +00006747 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00006748 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00006749 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00006750 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6751 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00006752
Chris Lattneraf707ab2009-01-24 21:53:27 +00006753 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00006754 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6755 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00006756
Chris Lattnere9feb472009-01-24 21:09:06 +00006757 return GetAlignOfType(E->getType());
6758}
6759
6760
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006761/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
6762/// a result as the expression's type.
6763bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
6764 const UnaryExprOrTypeTraitExpr *E) {
6765 switch(E->getKind()) {
6766 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00006767 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00006768 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00006769 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00006770 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00006771 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00006772
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006773 case UETT_VecStep: {
6774 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00006775
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006776 if (Ty->isVectorType()) {
Ted Kremenek890f0f12012-08-23 20:46:57 +00006777 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00006778
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006779 // The vec_step built-in functions that take a 3-component
6780 // vector return 4. (OpenCL 1.1 spec 6.11.12)
6781 if (n == 3)
6782 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00006783
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006784 return Success(n, E);
6785 } else
6786 return Success(1, E);
6787 }
6788
6789 case UETT_SizeOf: {
6790 QualType SrcTy = E->getTypeOfArgument();
6791 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
6792 // the result is the size of the referenced type."
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006793 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
6794 SrcTy = Ref->getPointeeType();
6795
Richard Smith180f4792011-11-10 06:34:14 +00006796 CharUnits Sizeof;
Richard Smith74e1ad92012-02-16 02:46:34 +00006797 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006798 return false;
Richard Smith180f4792011-11-10 06:34:14 +00006799 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006800 }
6801 }
6802
6803 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00006804}
6805
Peter Collingbourne8cad3042011-05-13 03:29:01 +00006806bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006807 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00006808 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006809 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00006810 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00006811 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006812 for (unsigned i = 0; i != n; ++i) {
6813 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
6814 switch (ON.getKind()) {
6815 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00006816 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006817 APSInt IdxResult;
6818 if (!EvaluateInteger(Idx, IdxResult, Info))
6819 return false;
6820 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
6821 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00006822 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006823 CurrentType = AT->getElementType();
6824 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
6825 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smitha49a7fe2013-05-07 23:34:45 +00006826 break;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006827 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006828
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006829 case OffsetOfExpr::OffsetOfNode::Field: {
6830 FieldDecl *MemberDecl = ON.getField();
6831 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00006832 if (!RT)
6833 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006834 RecordDecl *RD = RT->getDecl();
John McCall8d59dee2012-05-01 00:38:49 +00006835 if (RD->isInvalidDecl()) return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006836 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00006837 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00006838 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00006839 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006840 CurrentType = MemberDecl->getType().getNonReferenceType();
6841 break;
6842 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006843
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006844 case OffsetOfExpr::OffsetOfNode::Identifier:
6845 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00006846
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00006847 case OffsetOfExpr::OffsetOfNode::Base: {
6848 CXXBaseSpecifier *BaseSpec = ON.getBase();
6849 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00006850 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00006851
6852 // Find the layout of the class whose base we are looking into.
6853 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00006854 if (!RT)
6855 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00006856 RecordDecl *RD = RT->getDecl();
John McCall8d59dee2012-05-01 00:38:49 +00006857 if (RD->isInvalidDecl()) return false;
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00006858 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
6859
6860 // Find the base class itself.
6861 CurrentType = BaseSpec->getType();
6862 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
6863 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00006864 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00006865
6866 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00006867 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00006868 break;
6869 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006870 }
6871 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00006872 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006873}
6874
Chris Lattnerb542afe2008-07-11 19:10:17 +00006875bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00006876 switch (E->getOpcode()) {
6877 default:
6878 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
6879 // See C99 6.6p3.
6880 return Error(E);
6881 case UO_Extension:
6882 // FIXME: Should extension allow i-c-e extension expressions in its scope?
6883 // If so, we could clear the diagnostic ID.
6884 return Visit(E->getSubExpr());
6885 case UO_Plus:
6886 // The result is just the value.
6887 return Visit(E->getSubExpr());
6888 case UO_Minus: {
6889 if (!Visit(E->getSubExpr()))
6890 return false;
6891 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00006892 const APSInt &Value = Result.getInt();
6893 if (Value.isSigned() && Value.isMinSignedValue())
6894 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
6895 E->getType());
6896 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00006897 }
6898 case UO_Not: {
6899 if (!Visit(E->getSubExpr()))
6900 return false;
6901 if (!Result.isInt()) return Error(E);
6902 return Success(~Result.getInt(), E);
6903 }
6904 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00006905 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00006906 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00006907 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00006908 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00006909 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00006910 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00006911}
Mike Stump1eb44332009-09-09 15:08:12 +00006912
Chris Lattner732b2232008-07-12 01:15:53 +00006913/// HandleCast - This is used to evaluate implicit or explicit casts where the
6914/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00006915bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
6916 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00006917 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00006918 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00006919
Eli Friedman46a52322011-03-25 00:43:55 +00006920 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00006921 case CK_BaseToDerived:
6922 case CK_DerivedToBase:
6923 case CK_UncheckedDerivedToBase:
6924 case CK_Dynamic:
6925 case CK_ToUnion:
6926 case CK_ArrayToPointerDecay:
6927 case CK_FunctionToPointerDecay:
6928 case CK_NullToPointer:
6929 case CK_NullToMemberPointer:
6930 case CK_BaseToDerivedMemberPointer:
6931 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00006932 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00006933 case CK_ConstructorConversion:
6934 case CK_IntegralToPointer:
6935 case CK_ToVoid:
6936 case CK_VectorSplat:
6937 case CK_IntegralToFloating:
6938 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00006939 case CK_CPointerToObjCPointerCast:
6940 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00006941 case CK_AnyPointerToBlockPointerCast:
6942 case CK_ObjCObjectLValueCast:
6943 case CK_FloatingRealToComplex:
6944 case CK_FloatingComplexToReal:
6945 case CK_FloatingComplexCast:
6946 case CK_FloatingComplexToIntegralComplex:
6947 case CK_IntegralRealToComplex:
6948 case CK_IntegralComplexCast:
6949 case CK_IntegralComplexToFloatingComplex:
Eli Friedmana6c66ce2012-08-31 00:14:07 +00006950 case CK_BuiltinFnToFnPtr:
Guy Benyeie6b9d802013-01-20 12:31:11 +00006951 case CK_ZeroToOCLEvent:
Richard Smith5705f212013-05-23 00:30:41 +00006952 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00006953 llvm_unreachable("invalid cast kind for integral value");
6954
Eli Friedmane50c2972011-03-25 19:07:11 +00006955 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00006956 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00006957 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00006958 case CK_ARCProduceObject:
6959 case CK_ARCConsumeObject:
6960 case CK_ARCReclaimReturnedObject:
6961 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00006962 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00006963 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00006964
Richard Smith7d580a42012-01-17 21:17:26 +00006965 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00006966 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006967 case CK_AtomicToNonAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00006968 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00006969 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00006970
6971 case CK_MemberPointerToBoolean:
6972 case CK_PointerToBoolean:
6973 case CK_IntegralToBoolean:
6974 case CK_FloatingToBoolean:
6975 case CK_FloatingComplexToBoolean:
6976 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00006977 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00006978 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00006979 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00006980 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00006981 }
6982
Eli Friedman46a52322011-03-25 00:43:55 +00006983 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00006984 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00006985 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00006986
Eli Friedmanbe265702009-02-20 01:15:07 +00006987 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00006988 // Allow casts of address-of-label differences if they are no-ops
6989 // or narrowing. (The narrowing case isn't actually guaranteed to
6990 // be constant-evaluatable except in some narrow cases which are hard
6991 // to detect here. We let it through on the assumption the user knows
6992 // what they are doing.)
6993 if (Result.isAddrLabelDiff())
6994 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00006995 // Only allow casts of lvalues if they are lossless.
6996 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
6997 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00006998
Richard Smithf72fccf2012-01-30 22:27:01 +00006999 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
7000 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00007001 }
Mike Stump1eb44332009-09-09 15:08:12 +00007002
Eli Friedman46a52322011-03-25 00:43:55 +00007003 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00007004 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7005
John McCallefdb83e2010-05-07 21:00:08 +00007006 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00007007 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00007008 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00007009
Daniel Dunbardd211642009-02-19 22:24:01 +00007010 if (LV.getLValueBase()) {
7011 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00007012 // FIXME: Allow a larger integer size than the pointer size, and allow
7013 // narrowing back down to pointer width in subsequent integral casts.
7014 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00007015 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00007016 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00007017
Richard Smithb755a9d2011-11-16 07:18:12 +00007018 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00007019 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00007020 return true;
7021 }
7022
Ken Dycka7305832010-01-15 12:37:54 +00007023 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
7024 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00007025 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00007026 }
Eli Friedman4efaa272008-11-12 09:44:48 +00007027
Eli Friedman46a52322011-03-25 00:43:55 +00007028 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00007029 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00007030 if (!EvaluateComplex(SubExpr, C, Info))
7031 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00007032 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00007033 }
Eli Friedman2217c872009-02-22 11:46:18 +00007034
Eli Friedman46a52322011-03-25 00:43:55 +00007035 case CK_FloatingToIntegral: {
7036 APFloat F(0.0);
7037 if (!EvaluateFloat(SubExpr, F, Info))
7038 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00007039
Richard Smithc1c5f272011-12-13 06:39:58 +00007040 APSInt Value;
7041 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7042 return false;
7043 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00007044 }
7045 }
Mike Stump1eb44332009-09-09 15:08:12 +00007046
Eli Friedman46a52322011-03-25 00:43:55 +00007047 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00007048}
Anders Carlsson2bad1682008-07-08 14:30:00 +00007049
Eli Friedman722c7172009-02-28 03:59:05 +00007050bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7051 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00007052 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00007053 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7054 return false;
7055 if (!LV.isComplexInt())
7056 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00007057 return Success(LV.getComplexIntReal(), E);
7058 }
7059
7060 return Visit(E->getSubExpr());
7061}
7062
Eli Friedman664a1042009-02-27 04:45:43 +00007063bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00007064 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00007065 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00007066 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7067 return false;
7068 if (!LV.isComplexInt())
7069 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00007070 return Success(LV.getComplexIntImag(), E);
7071 }
7072
Richard Smith8327fad2011-10-24 18:44:57 +00007073 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00007074 return Success(0, E);
7075}
7076
Douglas Gregoree8aff02011-01-04 17:33:58 +00007077bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
7078 return Success(E->getPackLength(), E);
7079}
7080
Sebastian Redl295995c2010-09-10 20:55:47 +00007081bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
7082 return Success(E->getValue(), E);
7083}
7084
Chris Lattnerf5eeb052008-07-11 18:11:29 +00007085//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00007086// Float Evaluation
7087//===----------------------------------------------------------------------===//
7088
7089namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00007090class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00007091 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00007092 APFloat &Result;
7093public:
7094 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00007095 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00007096
Richard Smith1aa0be82012-03-03 22:46:17 +00007097 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00007098 Result = V.getFloat();
7099 return true;
7100 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00007101
Richard Smith51201882011-12-30 21:15:51 +00007102 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00007103 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
7104 return true;
7105 }
7106
Chris Lattner019f4e82008-10-06 05:28:25 +00007107 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00007108
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00007109 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00007110 bool VisitBinaryOperator(const BinaryOperator *E);
7111 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00007112 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00007113
John McCallabd3a852010-05-07 22:08:54 +00007114 bool VisitUnaryReal(const UnaryOperator *E);
7115 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00007116
Richard Smith51201882011-12-30 21:15:51 +00007117 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00007118};
7119} // end anonymous namespace
7120
7121static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00007122 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00007123 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00007124}
7125
Jay Foad4ba2a172011-01-12 09:06:06 +00007126static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00007127 QualType ResultTy,
7128 const Expr *Arg,
7129 bool SNaN,
7130 llvm::APFloat &Result) {
7131 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
7132 if (!S) return false;
7133
7134 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
7135
7136 llvm::APInt fill;
7137
7138 // Treat empty strings as if they were zero.
7139 if (S->getString().empty())
7140 fill = llvm::APInt(32, 0);
7141 else if (S->getString().getAsInteger(0, fill))
7142 return false;
7143
7144 if (SNaN)
7145 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7146 else
7147 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7148 return true;
7149}
7150
Chris Lattner019f4e82008-10-06 05:28:25 +00007151bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00007152 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00007153 default:
7154 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7155
Chris Lattner019f4e82008-10-06 05:28:25 +00007156 case Builtin::BI__builtin_huge_val:
7157 case Builtin::BI__builtin_huge_valf:
7158 case Builtin::BI__builtin_huge_vall:
7159 case Builtin::BI__builtin_inf:
7160 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00007161 case Builtin::BI__builtin_infl: {
7162 const llvm::fltSemantics &Sem =
7163 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00007164 Result = llvm::APFloat::getInf(Sem);
7165 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00007166 }
Mike Stump1eb44332009-09-09 15:08:12 +00007167
John McCalldb7b72a2010-02-28 13:00:19 +00007168 case Builtin::BI__builtin_nans:
7169 case Builtin::BI__builtin_nansf:
7170 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00007171 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7172 true, Result))
7173 return Error(E);
7174 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00007175
Chris Lattner9e621712008-10-06 06:31:58 +00007176 case Builtin::BI__builtin_nan:
7177 case Builtin::BI__builtin_nanf:
7178 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00007179 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00007180 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00007181 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7182 false, Result))
7183 return Error(E);
7184 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00007185
7186 case Builtin::BI__builtin_fabs:
7187 case Builtin::BI__builtin_fabsf:
7188 case Builtin::BI__builtin_fabsl:
7189 if (!EvaluateFloat(E->getArg(0), Result, Info))
7190 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00007191
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00007192 if (Result.isNegative())
7193 Result.changeSign();
7194 return true;
7195
Richard Smithacaf72a2013-06-13 06:26:32 +00007196 // FIXME: Builtin::BI__builtin_powi
7197 // FIXME: Builtin::BI__builtin_powif
7198 // FIXME: Builtin::BI__builtin_powil
7199
Mike Stump1eb44332009-09-09 15:08:12 +00007200 case Builtin::BI__builtin_copysign:
7201 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00007202 case Builtin::BI__builtin_copysignl: {
7203 APFloat RHS(0.);
7204 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
7205 !EvaluateFloat(E->getArg(1), RHS, Info))
7206 return false;
7207 Result.copySign(RHS);
7208 return true;
7209 }
Chris Lattner019f4e82008-10-06 05:28:25 +00007210 }
7211}
7212
John McCallabd3a852010-05-07 22:08:54 +00007213bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00007214 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7215 ComplexValue CV;
7216 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7217 return false;
7218 Result = CV.FloatReal;
7219 return true;
7220 }
7221
7222 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00007223}
7224
7225bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00007226 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7227 ComplexValue CV;
7228 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7229 return false;
7230 Result = CV.FloatImag;
7231 return true;
7232 }
7233
Richard Smith8327fad2011-10-24 18:44:57 +00007234 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00007235 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
7236 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00007237 return true;
7238}
7239
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00007240bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00007241 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00007242 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00007243 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00007244 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00007245 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00007246 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
7247 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00007248 Result.changeSign();
7249 return true;
7250 }
7251}
Chris Lattner019f4e82008-10-06 05:28:25 +00007252
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00007253bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00007254 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7255 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00007256
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00007257 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00007258 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
7259 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00007260 return false;
Richard Smitha49a7fe2013-05-07 23:34:45 +00007261 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
7262 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00007263}
7264
7265bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
7266 Result = E->getValue();
7267 return true;
7268}
7269
Peter Collingbourne8cad3042011-05-13 03:29:01 +00007270bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
7271 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00007272
Eli Friedman2a523ee2011-03-25 00:54:52 +00007273 switch (E->getCastKind()) {
7274 default:
Richard Smithc49bd112011-10-28 17:51:58 +00007275 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00007276
7277 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00007278 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00007279 return EvaluateInteger(SubExpr, IntResult, Info) &&
7280 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
7281 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00007282 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00007283
7284 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00007285 if (!Visit(SubExpr))
7286 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00007287 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
7288 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00007289 }
John McCallf3ea8cf2010-11-14 08:17:51 +00007290
Eli Friedman2a523ee2011-03-25 00:54:52 +00007291 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00007292 ComplexValue V;
7293 if (!EvaluateComplex(SubExpr, V, Info))
7294 return false;
7295 Result = V.getComplexFloatReal();
7296 return true;
7297 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00007298 }
Eli Friedman4efaa272008-11-12 09:44:48 +00007299}
7300
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00007301//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00007302// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00007303//===----------------------------------------------------------------------===//
7304
7305namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00007306class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00007307 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00007308 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00007309
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00007310public:
John McCallf4cf1a12010-05-07 17:22:02 +00007311 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00007312 : ExprEvaluatorBaseTy(info), Result(Result) {}
7313
Richard Smith1aa0be82012-03-03 22:46:17 +00007314 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00007315 Result.setFrom(V);
7316 return true;
7317 }
Mike Stump1eb44332009-09-09 15:08:12 +00007318
Eli Friedman7ead5c72012-01-10 04:58:17 +00007319 bool ZeroInitialization(const Expr *E);
7320
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00007321 //===--------------------------------------------------------------------===//
7322 // Visitor Methods
7323 //===--------------------------------------------------------------------===//
7324
Peter Collingbourne8cad3042011-05-13 03:29:01 +00007325 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00007326 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00007327 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00007328 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00007329 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00007330};
7331} // end anonymous namespace
7332
John McCallf4cf1a12010-05-07 17:22:02 +00007333static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
7334 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00007335 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00007336 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00007337}
7338
Eli Friedman7ead5c72012-01-10 04:58:17 +00007339bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek890f0f12012-08-23 20:46:57 +00007340 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00007341 if (ElemTy->isRealFloatingType()) {
7342 Result.makeComplexFloat();
7343 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
7344 Result.FloatReal = Zero;
7345 Result.FloatImag = Zero;
7346 } else {
7347 Result.makeComplexInt();
7348 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
7349 Result.IntReal = Zero;
7350 Result.IntImag = Zero;
7351 }
7352 return true;
7353}
7354
Peter Collingbourne8cad3042011-05-13 03:29:01 +00007355bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
7356 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00007357
7358 if (SubExpr->getType()->isRealFloatingType()) {
7359 Result.makeComplexFloat();
7360 APFloat &Imag = Result.FloatImag;
7361 if (!EvaluateFloat(SubExpr, Imag, Info))
7362 return false;
7363
7364 Result.FloatReal = APFloat(Imag.getSemantics());
7365 return true;
7366 } else {
7367 assert(SubExpr->getType()->isIntegerType() &&
7368 "Unexpected imaginary literal.");
7369
7370 Result.makeComplexInt();
7371 APSInt &Imag = Result.IntImag;
7372 if (!EvaluateInteger(SubExpr, Imag, Info))
7373 return false;
7374
7375 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
7376 return true;
7377 }
7378}
7379
Peter Collingbourne8cad3042011-05-13 03:29:01 +00007380bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00007381
John McCall8786da72010-12-14 17:51:41 +00007382 switch (E->getCastKind()) {
7383 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00007384 case CK_BaseToDerived:
7385 case CK_DerivedToBase:
7386 case CK_UncheckedDerivedToBase:
7387 case CK_Dynamic:
7388 case CK_ToUnion:
7389 case CK_ArrayToPointerDecay:
7390 case CK_FunctionToPointerDecay:
7391 case CK_NullToPointer:
7392 case CK_NullToMemberPointer:
7393 case CK_BaseToDerivedMemberPointer:
7394 case CK_DerivedToBaseMemberPointer:
7395 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00007396 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00007397 case CK_ConstructorConversion:
7398 case CK_IntegralToPointer:
7399 case CK_PointerToIntegral:
7400 case CK_PointerToBoolean:
7401 case CK_ToVoid:
7402 case CK_VectorSplat:
7403 case CK_IntegralCast:
7404 case CK_IntegralToBoolean:
7405 case CK_IntegralToFloating:
7406 case CK_FloatingToIntegral:
7407 case CK_FloatingToBoolean:
7408 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00007409 case CK_CPointerToObjCPointerCast:
7410 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00007411 case CK_AnyPointerToBlockPointerCast:
7412 case CK_ObjCObjectLValueCast:
7413 case CK_FloatingComplexToReal:
7414 case CK_FloatingComplexToBoolean:
7415 case CK_IntegralComplexToReal:
7416 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00007417 case CK_ARCProduceObject:
7418 case CK_ARCConsumeObject:
7419 case CK_ARCReclaimReturnedObject:
7420 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00007421 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedmana6c66ce2012-08-31 00:14:07 +00007422 case CK_BuiltinFnToFnPtr:
Guy Benyeie6b9d802013-01-20 12:31:11 +00007423 case CK_ZeroToOCLEvent:
Richard Smith5705f212013-05-23 00:30:41 +00007424 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00007425 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00007426
John McCall8786da72010-12-14 17:51:41 +00007427 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00007428 case CK_AtomicToNonAtomic:
John McCall8786da72010-12-14 17:51:41 +00007429 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00007430 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00007431
7432 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00007433 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00007434 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00007435 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00007436
7437 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00007438 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00007439 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00007440 return false;
7441
John McCall8786da72010-12-14 17:51:41 +00007442 Result.makeComplexFloat();
7443 Result.FloatImag = APFloat(Real.getSemantics());
7444 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00007445 }
7446
John McCall8786da72010-12-14 17:51:41 +00007447 case CK_FloatingComplexCast: {
7448 if (!Visit(E->getSubExpr()))
7449 return false;
7450
7451 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7452 QualType From
7453 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7454
Richard Smithc1c5f272011-12-13 06:39:58 +00007455 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
7456 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00007457 }
7458
7459 case CK_FloatingComplexToIntegralComplex: {
7460 if (!Visit(E->getSubExpr()))
7461 return false;
7462
7463 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7464 QualType From
7465 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7466 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00007467 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
7468 To, Result.IntReal) &&
7469 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
7470 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00007471 }
7472
7473 case CK_IntegralRealToComplex: {
7474 APSInt &Real = Result.IntReal;
7475 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
7476 return false;
7477
7478 Result.makeComplexInt();
7479 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
7480 return true;
7481 }
7482
7483 case CK_IntegralComplexCast: {
7484 if (!Visit(E->getSubExpr()))
7485 return false;
7486
7487 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7488 QualType From
7489 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7490
Richard Smithf72fccf2012-01-30 22:27:01 +00007491 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7492 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00007493 return true;
7494 }
7495
7496 case CK_IntegralComplexToFloatingComplex: {
7497 if (!Visit(E->getSubExpr()))
7498 return false;
7499
Ted Kremenek890f0f12012-08-23 20:46:57 +00007500 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00007501 QualType From
Ted Kremenek890f0f12012-08-23 20:46:57 +00007502 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00007503 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00007504 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7505 To, Result.FloatReal) &&
7506 HandleIntToFloatCast(Info, E, From, Result.IntImag,
7507 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00007508 }
7509 }
7510
7511 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00007512}
7513
John McCallf4cf1a12010-05-07 17:22:02 +00007514bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00007515 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00007516 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7517
Richard Smith745f5142012-01-27 01:14:48 +00007518 bool LHSOK = Visit(E->getLHS());
7519 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00007520 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00007521
John McCallf4cf1a12010-05-07 17:22:02 +00007522 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00007523 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00007524 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00007525
Daniel Dunbar3f279872009-01-29 01:32:56 +00007526 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
7527 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00007528 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00007529 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00007530 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00007531 if (Result.isComplexFloat()) {
7532 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
7533 APFloat::rmNearestTiesToEven);
7534 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
7535 APFloat::rmNearestTiesToEven);
7536 } else {
7537 Result.getComplexIntReal() += RHS.getComplexIntReal();
7538 Result.getComplexIntImag() += RHS.getComplexIntImag();
7539 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00007540 break;
John McCall2de56d12010-08-25 11:45:40 +00007541 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00007542 if (Result.isComplexFloat()) {
7543 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
7544 APFloat::rmNearestTiesToEven);
7545 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
7546 APFloat::rmNearestTiesToEven);
7547 } else {
7548 Result.getComplexIntReal() -= RHS.getComplexIntReal();
7549 Result.getComplexIntImag() -= RHS.getComplexIntImag();
7550 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00007551 break;
John McCall2de56d12010-08-25 11:45:40 +00007552 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00007553 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00007554 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00007555 APFloat &LHS_r = LHS.getComplexFloatReal();
7556 APFloat &LHS_i = LHS.getComplexFloatImag();
7557 APFloat &RHS_r = RHS.getComplexFloatReal();
7558 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00007559
Daniel Dunbar3f279872009-01-29 01:32:56 +00007560 APFloat Tmp = LHS_r;
7561 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7562 Result.getComplexFloatReal() = Tmp;
7563 Tmp = LHS_i;
7564 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7565 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
7566
7567 Tmp = LHS_r;
7568 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7569 Result.getComplexFloatImag() = Tmp;
7570 Tmp = LHS_i;
7571 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7572 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
7573 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00007574 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00007575 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00007576 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
7577 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00007578 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00007579 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
7580 LHS.getComplexIntImag() * RHS.getComplexIntReal());
7581 }
7582 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00007583 case BO_Div:
7584 if (Result.isComplexFloat()) {
7585 ComplexValue LHS = Result;
7586 APFloat &LHS_r = LHS.getComplexFloatReal();
7587 APFloat &LHS_i = LHS.getComplexFloatImag();
7588 APFloat &RHS_r = RHS.getComplexFloatReal();
7589 APFloat &RHS_i = RHS.getComplexFloatImag();
7590 APFloat &Res_r = Result.getComplexFloatReal();
7591 APFloat &Res_i = Result.getComplexFloatImag();
7592
7593 APFloat Den = RHS_r;
7594 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7595 APFloat Tmp = RHS_i;
7596 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7597 Den.add(Tmp, APFloat::rmNearestTiesToEven);
7598
7599 Res_r = LHS_r;
7600 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7601 Tmp = LHS_i;
7602 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7603 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
7604 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
7605
7606 Res_i = LHS_i;
7607 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7608 Tmp = LHS_r;
7609 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7610 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
7611 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
7612 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00007613 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
7614 return Error(E, diag::note_expr_divide_by_zero);
7615
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00007616 ComplexValue LHS = Result;
7617 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
7618 RHS.getComplexIntImag() * RHS.getComplexIntImag();
7619 Result.getComplexIntReal() =
7620 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
7621 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
7622 Result.getComplexIntImag() =
7623 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
7624 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
7625 }
7626 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00007627 }
7628
John McCallf4cf1a12010-05-07 17:22:02 +00007629 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00007630}
7631
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00007632bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7633 // Get the operand value into 'Result'.
7634 if (!Visit(E->getSubExpr()))
7635 return false;
7636
7637 switch (E->getOpcode()) {
7638 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00007639 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00007640 case UO_Extension:
7641 return true;
7642 case UO_Plus:
7643 // The result is always just the subexpr.
7644 return true;
7645 case UO_Minus:
7646 if (Result.isComplexFloat()) {
7647 Result.getComplexFloatReal().changeSign();
7648 Result.getComplexFloatImag().changeSign();
7649 }
7650 else {
7651 Result.getComplexIntReal() = -Result.getComplexIntReal();
7652 Result.getComplexIntImag() = -Result.getComplexIntImag();
7653 }
7654 return true;
7655 case UO_Not:
7656 if (Result.isComplexFloat())
7657 Result.getComplexFloatImag().changeSign();
7658 else
7659 Result.getComplexIntImag() = -Result.getComplexIntImag();
7660 return true;
7661 }
7662}
7663
Eli Friedman7ead5c72012-01-10 04:58:17 +00007664bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7665 if (E->getNumInits() == 2) {
7666 if (E->getType()->isComplexType()) {
7667 Result.makeComplexFloat();
7668 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
7669 return false;
7670 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
7671 return false;
7672 } else {
7673 Result.makeComplexInt();
7674 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
7675 return false;
7676 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
7677 return false;
7678 }
7679 return true;
7680 }
7681 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
7682}
7683
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00007684//===----------------------------------------------------------------------===//
Richard Smith5705f212013-05-23 00:30:41 +00007685// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
7686// implicit conversion.
7687//===----------------------------------------------------------------------===//
7688
7689namespace {
7690class AtomicExprEvaluator :
7691 public ExprEvaluatorBase<AtomicExprEvaluator, bool> {
7692 APValue &Result;
7693public:
7694 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
7695 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7696
7697 bool Success(const APValue &V, const Expr *E) {
7698 Result = V;
7699 return true;
7700 }
7701
7702 bool ZeroInitialization(const Expr *E) {
7703 ImplicitValueInitExpr VIE(
7704 E->getType()->castAs<AtomicType>()->getValueType());
7705 return Evaluate(Result, Info, &VIE);
7706 }
7707
7708 bool VisitCastExpr(const CastExpr *E) {
7709 switch (E->getCastKind()) {
7710 default:
7711 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7712 case CK_NonAtomicToAtomic:
7713 return Evaluate(Result, Info, E->getSubExpr());
7714 }
7715 }
7716};
7717} // end anonymous namespace
7718
7719static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
7720 assert(E->isRValue() && E->getType()->isAtomicType());
7721 return AtomicExprEvaluator(Info, Result).Visit(E);
7722}
7723
7724//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00007725// Void expression evaluation, primarily for a cast to void on the LHS of a
7726// comma operator
7727//===----------------------------------------------------------------------===//
7728
7729namespace {
7730class VoidExprEvaluator
7731 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
7732public:
7733 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
7734
Richard Smith1aa0be82012-03-03 22:46:17 +00007735 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00007736
7737 bool VisitCastExpr(const CastExpr *E) {
7738 switch (E->getCastKind()) {
7739 default:
7740 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7741 case CK_ToVoid:
7742 VisitIgnoredValue(E->getSubExpr());
7743 return true;
7744 }
7745 }
7746};
7747} // end anonymous namespace
7748
7749static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
7750 assert(E->isRValue() && E->getType()->isVoidType());
7751 return VoidExprEvaluator(Info).Visit(E);
7752}
7753
7754//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00007755// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00007756//===----------------------------------------------------------------------===//
7757
Richard Smith1aa0be82012-03-03 22:46:17 +00007758static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00007759 // In C, function designators are not lvalues, but we evaluate them as if they
7760 // are.
Richard Smith5705f212013-05-23 00:30:41 +00007761 QualType T = E->getType();
7762 if (E->isGLValue() || T->isFunctionType()) {
Richard Smithc49bd112011-10-28 17:51:58 +00007763 LValue LV;
7764 if (!EvaluateLValue(E, LV, Info))
7765 return false;
7766 LV.moveInto(Result);
Richard Smith5705f212013-05-23 00:30:41 +00007767 } else if (T->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00007768 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00007769 return false;
Richard Smith5705f212013-05-23 00:30:41 +00007770 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00007771 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00007772 return false;
Richard Smith5705f212013-05-23 00:30:41 +00007773 } else if (T->hasPointerRepresentation()) {
John McCallefdb83e2010-05-07 21:00:08 +00007774 LValue LV;
7775 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00007776 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00007777 LV.moveInto(Result);
Richard Smith5705f212013-05-23 00:30:41 +00007778 } else if (T->isRealFloatingType()) {
John McCallefdb83e2010-05-07 21:00:08 +00007779 llvm::APFloat F(0.0);
7780 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00007781 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00007782 Result = APValue(F);
Richard Smith5705f212013-05-23 00:30:41 +00007783 } else if (T->isAnyComplexType()) {
John McCallefdb83e2010-05-07 21:00:08 +00007784 ComplexValue C;
7785 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00007786 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00007787 C.moveInto(Result);
Richard Smith5705f212013-05-23 00:30:41 +00007788 } else if (T->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00007789 MemberPtr P;
7790 if (!EvaluateMemberPointer(E, P, Info))
7791 return false;
7792 P.moveInto(Result);
7793 return true;
Richard Smith5705f212013-05-23 00:30:41 +00007794 } else if (T->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00007795 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00007796 LV.set(E, Info.CurrentCall->Index);
Richard Smith03ce5f82013-07-24 07:11:57 +00007797 APValue &Value = Info.CurrentCall->createTemporary(E, false);
7798 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00007799 return false;
Richard Smith03ce5f82013-07-24 07:11:57 +00007800 Result = Value;
Richard Smith5705f212013-05-23 00:30:41 +00007801 } else if (T->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00007802 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00007803 LV.set(E, Info.CurrentCall->Index);
Richard Smith03ce5f82013-07-24 07:11:57 +00007804 APValue &Value = Info.CurrentCall->createTemporary(E, false);
7805 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smith180f4792011-11-10 06:34:14 +00007806 return false;
Richard Smith03ce5f82013-07-24 07:11:57 +00007807 Result = Value;
Richard Smith5705f212013-05-23 00:30:41 +00007808 } else if (T->isVoidType()) {
Richard Smith80ad52f2013-01-02 11:42:31 +00007809 if (!Info.getLangOpts().CPlusPlus11)
Richard Smith5cfc7d82012-03-15 04:53:45 +00007810 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smithc1c5f272011-12-13 06:39:58 +00007811 << E->getType();
Richard Smithaa9c3502011-12-07 00:43:50 +00007812 if (!EvaluateVoid(E, Info))
7813 return false;
Richard Smith5705f212013-05-23 00:30:41 +00007814 } else if (T->isAtomicType()) {
7815 if (!EvaluateAtomic(E, Result, Info))
7816 return false;
Richard Smith80ad52f2013-01-02 11:42:31 +00007817 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00007818 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smithc1c5f272011-12-13 06:39:58 +00007819 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00007820 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00007821 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00007822 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00007823 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00007824
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00007825 return true;
7826}
7827
Richard Smith83587db2012-02-15 02:18:13 +00007828/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
7829/// cases, the in-place evaluation is essential, since later initializers for
7830/// an object can indirectly refer to subobjects which were initialized earlier.
7831static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith6391ea22013-05-09 07:14:00 +00007832 const Expr *E, bool AllowNonLiteralTypes) {
7833 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smith51201882011-12-30 21:15:51 +00007834 return false;
7835
7836 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00007837 // Evaluate arrays and record types in-place, so that later initializers can
7838 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00007839 if (E->getType()->isArrayType())
7840 return EvaluateArray(E, This, Result, Info);
7841 else if (E->getType()->isRecordType())
7842 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00007843 }
7844
7845 // For any other type, in-place evaluation is unimportant.
Richard Smith1aa0be82012-03-03 22:46:17 +00007846 return Evaluate(Result, Info, E);
Richard Smith69c2c502011-11-04 05:33:44 +00007847}
7848
Richard Smithf48fdb02011-12-09 22:58:01 +00007849/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
7850/// lvalue-to-rvalue cast if it is an lvalue.
7851static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00007852 if (!CheckLiteralType(Info, E))
7853 return false;
7854
Richard Smith1aa0be82012-03-03 22:46:17 +00007855 if (!::Evaluate(Result, Info, E))
Richard Smithf48fdb02011-12-09 22:58:01 +00007856 return false;
7857
7858 if (E->isGLValue()) {
7859 LValue LV;
Richard Smith1aa0be82012-03-03 22:46:17 +00007860 LV.setFrom(Info.Ctx, Result);
Richard Smith5528ac92013-05-05 23:31:59 +00007861 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00007862 return false;
7863 }
7864
Richard Smith1aa0be82012-03-03 22:46:17 +00007865 // Check this core constant expression is a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +00007866 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf48fdb02011-12-09 22:58:01 +00007867}
Richard Smithc49bd112011-10-28 17:51:58 +00007868
Fariborz Jahanianad48a502013-01-24 22:11:45 +00007869static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
7870 const ASTContext &Ctx, bool &IsConst) {
7871 // Fast-path evaluations of integer literals, since we sometimes see files
7872 // containing vast quantities of these.
7873 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
7874 Result.Val = APValue(APSInt(L->getValue(),
7875 L->getType()->isUnsignedIntegerType()));
7876 IsConst = true;
7877 return true;
7878 }
7879
7880 // FIXME: Evaluating values of large array and record types can cause
7881 // performance problems. Only do so in C++11 for now.
7882 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
7883 Exp->getType()->isRecordType()) &&
7884 !Ctx.getLangOpts().CPlusPlus11) {
7885 IsConst = false;
7886 return true;
7887 }
7888 return false;
7889}
7890
7891
Richard Smith51f47082011-10-29 00:50:52 +00007892/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00007893/// any crazy technique (that has nothing to do with language standards) that
7894/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00007895/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
7896/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00007897bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahanianad48a502013-01-24 22:11:45 +00007898 bool IsConst;
7899 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
7900 return IsConst;
7901
Richard Smithf48fdb02011-12-09 22:58:01 +00007902 EvalInfo Info(Ctx, Result);
7903 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00007904}
7905
Jay Foad4ba2a172011-01-12 09:06:06 +00007906bool Expr::EvaluateAsBooleanCondition(bool &Result,
7907 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00007908 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00007909 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith1aa0be82012-03-03 22:46:17 +00007910 HandleConversionToBool(Scratch.Val, Result);
John McCallcd7a4452010-01-05 23:42:56 +00007911}
7912
Richard Smith80d4b552011-12-28 19:48:30 +00007913bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
7914 SideEffectsKind AllowSideEffects) const {
7915 if (!getType()->isIntegralOrEnumerationType())
7916 return false;
7917
Richard Smithc49bd112011-10-28 17:51:58 +00007918 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00007919 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
7920 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00007921 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00007922
Richard Smithc49bd112011-10-28 17:51:58 +00007923 Result = ExprResult.Val.getInt();
7924 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00007925}
7926
Jay Foad4ba2a172011-01-12 09:06:06 +00007927bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00007928 EvalInfo Info(Ctx, Result);
7929
John McCallefdb83e2010-05-07 21:00:08 +00007930 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00007931 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
7932 !CheckLValueConstantExpression(Info, getExprLoc(),
7933 Ctx.getLValueReferenceType(getType()), LV))
7934 return false;
7935
Richard Smith1aa0be82012-03-03 22:46:17 +00007936 LV.moveInto(Result.Val);
Richard Smith83587db2012-02-15 02:18:13 +00007937 return true;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00007938}
7939
Richard Smith099e7f62011-12-19 06:19:21 +00007940bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
7941 const VarDecl *VD,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00007942 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00007943 // FIXME: Evaluating initializers for large array and record types can cause
7944 // performance problems. Only do so in C++11 for now.
7945 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith80ad52f2013-01-02 11:42:31 +00007946 !Ctx.getLangOpts().CPlusPlus11)
Richard Smith2d6a5672012-01-14 04:30:29 +00007947 return false;
7948
Richard Smith099e7f62011-12-19 06:19:21 +00007949 Expr::EvalStatus EStatus;
7950 EStatus.Diag = &Notes;
7951
7952 EvalInfo InitInfo(Ctx, EStatus);
7953 InitInfo.setEvaluatingDecl(VD, Value);
7954
7955 LValue LVal;
7956 LVal.set(VD);
7957
Richard Smith51201882011-12-30 21:15:51 +00007958 // C++11 [basic.start.init]p2:
7959 // Variables with static storage duration or thread storage duration shall be
7960 // zero-initialized before any other initialization takes place.
7961 // This behavior is not present in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00007962 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smith51201882011-12-30 21:15:51 +00007963 !VD->getType()->isReferenceType()) {
7964 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith6391ea22013-05-09 07:14:00 +00007965 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smith83587db2012-02-15 02:18:13 +00007966 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00007967 return false;
7968 }
7969
Richard Smith6391ea22013-05-09 07:14:00 +00007970 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
7971 /*AllowNonLiteralTypes=*/true) ||
Richard Smith83587db2012-02-15 02:18:13 +00007972 EStatus.HasSideEffects)
7973 return false;
7974
7975 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
7976 Value);
Richard Smith099e7f62011-12-19 06:19:21 +00007977}
7978
Richard Smith51f47082011-10-29 00:50:52 +00007979/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
7980/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00007981bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00007982 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00007983 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00007984}
Anders Carlsson51fe9962008-11-22 21:04:56 +00007985
Fariborz Jahaniana18e70b2013-01-09 23:04:56 +00007986APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00007987 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00007988 EvalResult EvalResult;
Fariborz Jahaniana18e70b2013-01-09 23:04:56 +00007989 EvalResult.Diag = Diag;
Richard Smith51f47082011-10-29 00:50:52 +00007990 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00007991 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00007992 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00007993 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00007994
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00007995 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00007996}
John McCalld905f5a2010-05-07 05:32:02 +00007997
Fariborz Jahanianad48a502013-01-24 22:11:45 +00007998void Expr::EvaluateForOverflow(const ASTContext &Ctx,
7999 SmallVectorImpl<PartialDiagnosticAt> *Diags) const {
8000 bool IsConst;
8001 EvalResult EvalResult;
8002 EvalResult.Diag = Diags;
8003 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
8004 EvalInfo Info(Ctx, EvalResult, true);
8005 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
8006 }
8007}
8008
Richard Smith211c8dd2013-06-05 00:46:14 +00008009bool Expr::EvalResult::isGlobalLValue() const {
8010 assert(Val.isLValue());
8011 return IsGlobalLValue(Val.getLValueBase());
8012}
Abramo Bagnarae17a6432010-05-14 17:07:14 +00008013
8014
John McCalld905f5a2010-05-07 05:32:02 +00008015/// isIntegerConstantExpr - this recursive routine will test if an expression is
8016/// an integer constant expression.
8017
8018/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
8019/// comma, etc
John McCalld905f5a2010-05-07 05:32:02 +00008020
8021// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smithceb59d92012-12-28 13:25:52 +00008022// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
8023// and a (possibly null) SourceLocation indicating the location of the problem.
8024//
John McCalld905f5a2010-05-07 05:32:02 +00008025// Note that to reduce code duplication, this helper does no evaluation
8026// itself; the caller checks whether the expression is evaluatable, and
8027// in the rare cases where CheckICE actually cares about the evaluated
8028// value, it calls into Evalute.
John McCalld905f5a2010-05-07 05:32:02 +00008029
Dan Gohman3c46e8d2010-07-26 21:25:24 +00008030namespace {
8031
Richard Smithceb59d92012-12-28 13:25:52 +00008032enum ICEKind {
8033 /// This expression is an ICE.
8034 IK_ICE,
8035 /// This expression is not an ICE, but if it isn't evaluated, it's
8036 /// a legal subexpression for an ICE. This return value is used to handle
8037 /// the comma operator in C99 mode, and non-constant subexpressions.
8038 IK_ICEIfUnevaluated,
8039 /// This expression is not an ICE, and is not a legal subexpression for one.
8040 IK_NotICE
8041};
8042
John McCalld905f5a2010-05-07 05:32:02 +00008043struct ICEDiag {
Richard Smithceb59d92012-12-28 13:25:52 +00008044 ICEKind Kind;
John McCalld905f5a2010-05-07 05:32:02 +00008045 SourceLocation Loc;
8046
Richard Smithceb59d92012-12-28 13:25:52 +00008047 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCalld905f5a2010-05-07 05:32:02 +00008048};
8049
Dan Gohman3c46e8d2010-07-26 21:25:24 +00008050}
8051
Richard Smithceb59d92012-12-28 13:25:52 +00008052static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
8053
8054static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCalld905f5a2010-05-07 05:32:02 +00008055
8056static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
8057 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00008058 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smithceb59d92012-12-28 13:25:52 +00008059 !EVResult.Val.isInt())
8060 return ICEDiag(IK_NotICE, E->getLocStart());
8061
John McCalld905f5a2010-05-07 05:32:02 +00008062 return NoDiag();
8063}
8064
8065static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
8066 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smithceb59d92012-12-28 13:25:52 +00008067 if (!E->getType()->isIntegralOrEnumerationType())
8068 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00008069
8070 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00008071#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00008072#define STMT(Node, Base) case Expr::Node##Class:
8073#define EXPR(Node, Base)
8074#include "clang/AST/StmtNodes.inc"
8075 case Expr::PredefinedExprClass:
8076 case Expr::FloatingLiteralClass:
8077 case Expr::ImaginaryLiteralClass:
8078 case Expr::StringLiteralClass:
8079 case Expr::ArraySubscriptExprClass:
8080 case Expr::MemberExprClass:
8081 case Expr::CompoundAssignOperatorClass:
8082 case Expr::CompoundLiteralExprClass:
8083 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00008084 case Expr::DesignatedInitExprClass:
8085 case Expr::ImplicitValueInitExprClass:
8086 case Expr::ParenListExprClass:
8087 case Expr::VAArgExprClass:
8088 case Expr::AddrLabelExprClass:
8089 case Expr::StmtExprClass:
8090 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00008091 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00008092 case Expr::CXXDynamicCastExprClass:
8093 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00008094 case Expr::CXXUuidofExprClass:
John McCall76da55d2013-04-16 07:28:30 +00008095 case Expr::MSPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00008096 case Expr::CXXNullPtrLiteralExprClass:
Richard Smith9fcce652012-03-07 08:35:16 +00008097 case Expr::UserDefinedLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00008098 case Expr::CXXThisExprClass:
8099 case Expr::CXXThrowExprClass:
8100 case Expr::CXXNewExprClass:
8101 case Expr::CXXDeleteExprClass:
8102 case Expr::CXXPseudoDestructorExprClass:
8103 case Expr::UnresolvedLookupExprClass:
8104 case Expr::DependentScopeDeclRefExprClass:
8105 case Expr::CXXConstructExprClass:
Richard Smith7c3e6152013-06-12 22:31:48 +00008106 case Expr::CXXStdInitializerListExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00008107 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00008108 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00008109 case Expr::CXXTemporaryObjectExprClass:
8110 case Expr::CXXUnresolvedConstructExprClass:
8111 case Expr::CXXDependentScopeMemberExprClass:
8112 case Expr::UnresolvedMemberExprClass:
8113 case Expr::ObjCStringLiteralClass:
Patrick Beardeb382ec2012-04-19 00:25:12 +00008114 case Expr::ObjCBoxedExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00008115 case Expr::ObjCArrayLiteralClass:
8116 case Expr::ObjCDictionaryLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00008117 case Expr::ObjCEncodeExprClass:
8118 case Expr::ObjCMessageExprClass:
8119 case Expr::ObjCSelectorExprClass:
8120 case Expr::ObjCProtocolExprClass:
8121 case Expr::ObjCIvarRefExprClass:
8122 case Expr::ObjCPropertyRefExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00008123 case Expr::ObjCSubscriptRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00008124 case Expr::ObjCIsaExprClass:
8125 case Expr::ShuffleVectorExprClass:
8126 case Expr::BlockExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00008127 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00008128 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00008129 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00008130 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smith9a4db032012-09-12 00:56:43 +00008131 case Expr::FunctionParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00008132 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00008133 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00008134 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00008135 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00008136 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00008137 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00008138 case Expr::LambdaExprClass:
Richard Smithceb59d92012-12-28 13:25:52 +00008139 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redlcea8d962011-09-24 17:48:14 +00008140
Douglas Gregoree8aff02011-01-04 17:33:58 +00008141 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00008142 case Expr::GNUNullExprClass:
8143 // GCC considers the GNU __null value to be an integral constant expression.
8144 return NoDiag();
8145
John McCall91a57552011-07-15 05:09:51 +00008146 case Expr::SubstNonTypeTemplateParmExprClass:
8147 return
8148 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
8149
John McCalld905f5a2010-05-07 05:32:02 +00008150 case Expr::ParenExprClass:
8151 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00008152 case Expr::GenericSelectionExprClass:
8153 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00008154 case Expr::IntegerLiteralClass:
8155 case Expr::CharacterLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00008156 case Expr::ObjCBoolLiteralExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00008157 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00008158 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00008159 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00008160 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00008161 case Expr::TypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00008162 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00008163 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00008164 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00008165 return NoDiag();
8166 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00008167 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00008168 // C99 6.6/3 allows function calls within unevaluated subexpressions of
8169 // constant expressions, but they can never be ICEs because an ICE cannot
8170 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00008171 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00008172 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00008173 return CheckEvalInICE(E, Ctx);
Richard Smithceb59d92012-12-28 13:25:52 +00008174 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00008175 }
Richard Smith359c89d2012-02-24 22:12:32 +00008176 case Expr::DeclRefExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00008177 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
8178 return NoDiag();
Richard Smith359c89d2012-02-24 22:12:32 +00008179 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikie4e4d0842012-03-11 07:00:24 +00008180 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith359c89d2012-02-24 22:12:32 +00008181 D && IsConstNonVolatile(D->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00008182 // Parameter variables are never constants. Without this check,
8183 // getAnyInitializer() can find a default argument, which leads
8184 // to chaos.
8185 if (isa<ParmVarDecl>(D))
Richard Smithceb59d92012-12-28 13:25:52 +00008186 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00008187
8188 // C++ 7.1.5.1p2
8189 // A variable of non-volatile const-qualified integral or enumeration
8190 // type initialized by an ICE can be used in ICEs.
8191 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00008192 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smithceb59d92012-12-28 13:25:52 +00008193 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithdb1822c2011-11-08 01:31:09 +00008194
Richard Smith099e7f62011-12-19 06:19:21 +00008195 const VarDecl *VD;
8196 // Look for a declaration of this variable that has an initializer, and
8197 // check whether it is an ICE.
8198 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
8199 return NoDiag();
8200 else
Richard Smithceb59d92012-12-28 13:25:52 +00008201 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00008202 }
8203 }
Richard Smithceb59d92012-12-28 13:25:52 +00008204 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith359c89d2012-02-24 22:12:32 +00008205 }
John McCalld905f5a2010-05-07 05:32:02 +00008206 case Expr::UnaryOperatorClass: {
8207 const UnaryOperator *Exp = cast<UnaryOperator>(E);
8208 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00008209 case UO_PostInc:
8210 case UO_PostDec:
8211 case UO_PreInc:
8212 case UO_PreDec:
8213 case UO_AddrOf:
8214 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00008215 // C99 6.6/3 allows increment and decrement within unevaluated
8216 // subexpressions of constant expressions, but they can never be ICEs
8217 // because an ICE cannot contain an lvalue operand.
Richard Smithceb59d92012-12-28 13:25:52 +00008218 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00008219 case UO_Extension:
8220 case UO_LNot:
8221 case UO_Plus:
8222 case UO_Minus:
8223 case UO_Not:
8224 case UO_Real:
8225 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00008226 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00008227 }
Richard Smithceb59d92012-12-28 13:25:52 +00008228
John McCalld905f5a2010-05-07 05:32:02 +00008229 // OffsetOf falls through here.
8230 }
8231 case Expr::OffsetOfExprClass: {
Richard Smithceb59d92012-12-28 13:25:52 +00008232 // Note that per C99, offsetof must be an ICE. And AFAIK, using
8233 // EvaluateAsRValue matches the proposed gcc behavior for cases like
8234 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
8235 // compliance: we should warn earlier for offsetof expressions with
8236 // array subscripts that aren't ICEs, and if the array subscripts
8237 // are ICEs, the value of the offsetof must be an integer constant.
8238 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00008239 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00008240 case Expr::UnaryExprOrTypeTraitExprClass: {
8241 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
8242 if ((Exp->getKind() == UETT_SizeOf) &&
8243 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smithceb59d92012-12-28 13:25:52 +00008244 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00008245 return NoDiag();
8246 }
8247 case Expr::BinaryOperatorClass: {
8248 const BinaryOperator *Exp = cast<BinaryOperator>(E);
8249 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00008250 case BO_PtrMemD:
8251 case BO_PtrMemI:
8252 case BO_Assign:
8253 case BO_MulAssign:
8254 case BO_DivAssign:
8255 case BO_RemAssign:
8256 case BO_AddAssign:
8257 case BO_SubAssign:
8258 case BO_ShlAssign:
8259 case BO_ShrAssign:
8260 case BO_AndAssign:
8261 case BO_XorAssign:
8262 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00008263 // C99 6.6/3 allows assignments within unevaluated subexpressions of
8264 // constant expressions, but they can never be ICEs because an ICE cannot
8265 // contain an lvalue operand.
Richard Smithceb59d92012-12-28 13:25:52 +00008266 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00008267
John McCall2de56d12010-08-25 11:45:40 +00008268 case BO_Mul:
8269 case BO_Div:
8270 case BO_Rem:
8271 case BO_Add:
8272 case BO_Sub:
8273 case BO_Shl:
8274 case BO_Shr:
8275 case BO_LT:
8276 case BO_GT:
8277 case BO_LE:
8278 case BO_GE:
8279 case BO_EQ:
8280 case BO_NE:
8281 case BO_And:
8282 case BO_Xor:
8283 case BO_Or:
8284 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00008285 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8286 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00008287 if (Exp->getOpcode() == BO_Div ||
8288 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00008289 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00008290 // we don't evaluate one.
Richard Smithceb59d92012-12-28 13:25:52 +00008291 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008292 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00008293 if (REval == 0)
Richard Smithceb59d92012-12-28 13:25:52 +00008294 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00008295 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008296 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00008297 if (LEval.isMinSignedValue())
Richard Smithceb59d92012-12-28 13:25:52 +00008298 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00008299 }
8300 }
8301 }
John McCall2de56d12010-08-25 11:45:40 +00008302 if (Exp->getOpcode() == BO_Comma) {
David Blaikie4e4d0842012-03-11 07:00:24 +00008303 if (Ctx.getLangOpts().C99) {
John McCalld905f5a2010-05-07 05:32:02 +00008304 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
8305 // if it isn't evaluated.
Richard Smithceb59d92012-12-28 13:25:52 +00008306 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
8307 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00008308 } else {
8309 // In both C89 and C++, commas in ICEs are illegal.
Richard Smithceb59d92012-12-28 13:25:52 +00008310 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00008311 }
8312 }
Richard Smithceb59d92012-12-28 13:25:52 +00008313 return Worst(LHSResult, RHSResult);
John McCalld905f5a2010-05-07 05:32:02 +00008314 }
John McCall2de56d12010-08-25 11:45:40 +00008315 case BO_LAnd:
8316 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00008317 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8318 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smithceb59d92012-12-28 13:25:52 +00008319 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCalld905f5a2010-05-07 05:32:02 +00008320 // Rare case where the RHS has a comma "side-effect"; we need
8321 // to actually check the condition to see whether the side
8322 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00008323 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008324 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00008325 return RHSResult;
8326 return NoDiag();
8327 }
8328
Richard Smithceb59d92012-12-28 13:25:52 +00008329 return Worst(LHSResult, RHSResult);
John McCalld905f5a2010-05-07 05:32:02 +00008330 }
8331 }
8332 }
8333 case Expr::ImplicitCastExprClass:
8334 case Expr::CStyleCastExprClass:
8335 case Expr::CXXFunctionalCastExprClass:
8336 case Expr::CXXStaticCastExprClass:
8337 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00008338 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00008339 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00008340 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00008341 if (isa<ExplicitCastExpr>(E)) {
8342 if (const FloatingLiteral *FL
8343 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
8344 unsigned DestWidth = Ctx.getIntWidth(E->getType());
8345 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
8346 APSInt IgnoredVal(DestWidth, !DestSigned);
8347 bool Ignored;
8348 // If the value does not fit in the destination type, the behavior is
8349 // undefined, so we are not required to treat it as a constant
8350 // expression.
8351 if (FL->getValue().convertToInteger(IgnoredVal,
8352 llvm::APFloat::rmTowardZero,
8353 &Ignored) & APFloat::opInvalidOp)
Richard Smithceb59d92012-12-28 13:25:52 +00008354 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith2116b142011-12-18 02:33:09 +00008355 return NoDiag();
8356 }
8357 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00008358 switch (cast<CastExpr>(E)->getCastKind()) {
8359 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00008360 case CK_AtomicToNonAtomic:
8361 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00008362 case CK_NoOp:
8363 case CK_IntegralToBoolean:
8364 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00008365 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00008366 default:
Richard Smithceb59d92012-12-28 13:25:52 +00008367 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedmaneea0e812011-09-29 21:49:34 +00008368 }
John McCalld905f5a2010-05-07 05:32:02 +00008369 }
John McCall56ca35d2011-02-17 10:25:35 +00008370 case Expr::BinaryConditionalOperatorClass: {
8371 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
8372 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smithceb59d92012-12-28 13:25:52 +00008373 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCall56ca35d2011-02-17 10:25:35 +00008374 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smithceb59d92012-12-28 13:25:52 +00008375 if (FalseResult.Kind == IK_NotICE) return FalseResult;
8376 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
8377 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith9b403c52012-12-28 12:53:55 +00008378 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00008379 return FalseResult;
8380 }
John McCalld905f5a2010-05-07 05:32:02 +00008381 case Expr::ConditionalOperatorClass: {
8382 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
8383 // If the condition (ignoring parens) is a __builtin_constant_p call,
8384 // then only the true side is actually considered in an integer constant
8385 // expression, and it is fully evaluated. This is an important GNU
8386 // extension. See GCC PR38377 for discussion.
8387 if (const CallExpr *CallCE
8388 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00008389 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
8390 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00008391 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smithceb59d92012-12-28 13:25:52 +00008392 if (CondResult.Kind == IK_NotICE)
John McCalld905f5a2010-05-07 05:32:02 +00008393 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00008394
Richard Smithf48fdb02011-12-09 22:58:01 +00008395 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
8396 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00008397
Richard Smithceb59d92012-12-28 13:25:52 +00008398 if (TrueResult.Kind == IK_NotICE)
John McCalld905f5a2010-05-07 05:32:02 +00008399 return TrueResult;
Richard Smithceb59d92012-12-28 13:25:52 +00008400 if (FalseResult.Kind == IK_NotICE)
John McCalld905f5a2010-05-07 05:32:02 +00008401 return FalseResult;
Richard Smithceb59d92012-12-28 13:25:52 +00008402 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCalld905f5a2010-05-07 05:32:02 +00008403 return CondResult;
Richard Smithceb59d92012-12-28 13:25:52 +00008404 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCalld905f5a2010-05-07 05:32:02 +00008405 return NoDiag();
8406 // Rare case where the diagnostics depend on which side is evaluated
8407 // Note that if we get here, CondResult is 0, and at least one of
8408 // TrueResult and FalseResult is non-zero.
Richard Smithceb59d92012-12-28 13:25:52 +00008409 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCalld905f5a2010-05-07 05:32:02 +00008410 return FalseResult;
John McCalld905f5a2010-05-07 05:32:02 +00008411 return TrueResult;
8412 }
8413 case Expr::CXXDefaultArgExprClass:
8414 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smithc3bf52c2013-04-20 22:23:05 +00008415 case Expr::CXXDefaultInitExprClass:
8416 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00008417 case Expr::ChooseExprClass: {
Eli Friedmana5e66012013-07-20 00:40:58 +00008418 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00008419 }
8420 }
8421
David Blaikie30263482012-01-20 21:50:17 +00008422 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00008423}
8424
Richard Smithf48fdb02011-12-09 22:58:01 +00008425/// Evaluate an expression as a C++11 integral constant expression.
8426static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
8427 const Expr *E,
8428 llvm::APSInt *Value,
8429 SourceLocation *Loc) {
8430 if (!E->getType()->isIntegralOrEnumerationType()) {
8431 if (Loc) *Loc = E->getExprLoc();
8432 return false;
8433 }
8434
Richard Smith4c3fc9b2012-01-18 05:21:49 +00008435 APValue Result;
8436 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00008437 return false;
8438
Richard Smith4c3fc9b2012-01-18 05:21:49 +00008439 assert(Result.isInt() && "pointer cast to int is not an ICE");
8440 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00008441 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00008442}
8443
Richard Smithdd1f29b2011-12-12 09:28:41 +00008444bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smith80ad52f2013-01-02 11:42:31 +00008445 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf48fdb02011-12-09 22:58:01 +00008446 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
8447
Richard Smithceb59d92012-12-28 13:25:52 +00008448 ICEDiag D = CheckICE(this, Ctx);
8449 if (D.Kind != IK_ICE) {
8450 if (Loc) *Loc = D.Loc;
John McCalld905f5a2010-05-07 05:32:02 +00008451 return false;
8452 }
Richard Smithf48fdb02011-12-09 22:58:01 +00008453 return true;
8454}
8455
8456bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
8457 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith80ad52f2013-01-02 11:42:31 +00008458 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf48fdb02011-12-09 22:58:01 +00008459 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
8460
8461 if (!isIntegerConstantExpr(Ctx, Loc))
8462 return false;
8463 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00008464 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00008465 return true;
8466}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00008467
Richard Smith70488e22012-02-14 21:38:30 +00008468bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
Richard Smithceb59d92012-12-28 13:25:52 +00008469 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith70488e22012-02-14 21:38:30 +00008470}
8471
Richard Smith4c3fc9b2012-01-18 05:21:49 +00008472bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
8473 SourceLocation *Loc) const {
8474 // We support this checking in C++98 mode in order to diagnose compatibility
8475 // issues.
David Blaikie4e4d0842012-03-11 07:00:24 +00008476 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00008477
Richard Smith70488e22012-02-14 21:38:30 +00008478 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00008479 Expr::EvalStatus Status;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008480 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith4c3fc9b2012-01-18 05:21:49 +00008481 Status.Diag = &Diags;
8482 EvalInfo Info(Ctx, Status);
8483
8484 APValue Scratch;
8485 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
8486
8487 if (!Diags.empty()) {
8488 IsConstExpr = false;
8489 if (Loc) *Loc = Diags[0].first;
8490 } else if (!IsConstExpr) {
8491 // FIXME: This shouldn't happen.
8492 if (Loc) *Loc = getExprLoc();
8493 }
8494
8495 return IsConstExpr;
8496}
Richard Smith745f5142012-01-27 01:14:48 +00008497
8498bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008499 SmallVectorImpl<
Richard Smith745f5142012-01-27 01:14:48 +00008500 PartialDiagnosticAt> &Diags) {
8501 // FIXME: It would be useful to check constexpr function templates, but at the
8502 // moment the constant expression evaluator cannot cope with the non-rigorous
8503 // ASTs which we build for dependent expressions.
8504 if (FD->isDependentContext())
8505 return true;
8506
8507 Expr::EvalStatus Status;
8508 Status.Diag = &Diags;
8509
8510 EvalInfo Info(FD->getASTContext(), Status);
8511 Info.CheckingPotentialConstantExpression = true;
8512
8513 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8514 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
8515
Richard Smith6391ea22013-05-09 07:14:00 +00008516 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith745f5142012-01-27 01:14:48 +00008517 // is a temporary being used as the 'this' pointer.
8518 LValue This;
8519 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smith83587db2012-02-15 02:18:13 +00008520 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith745f5142012-01-27 01:14:48 +00008521
Richard Smith745f5142012-01-27 01:14:48 +00008522 ArrayRef<const Expr*> Args;
8523
8524 SourceLocation Loc = FD->getLocation();
8525
Richard Smith1aa0be82012-03-03 22:46:17 +00008526 APValue Scratch;
Richard Smith6391ea22013-05-09 07:14:00 +00008527 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
8528 // Evaluate the call as a constant initializer, to allow the construction
8529 // of objects of non-literal types.
8530 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith745f5142012-01-27 01:14:48 +00008531 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith6391ea22013-05-09 07:14:00 +00008532 } else
Richard Smith745f5142012-01-27 01:14:48 +00008533 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
8534 Args, FD->getBody(), Info, Scratch);
8535
8536 return Diags.empty();
8537}