blob: 0fb6d4276108d7a1514dcefefca1a48d1e8b50f4 [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) {
Eli Friedman4e1a82c2013-08-29 23:44:43 +0000370 // FIXME: Force the precision of the source value down so we don't
371 // print digits which are usually useless (we don't really care here if
372 // we truncate a digit by accident in edge cases). Ideally,
373 // APFloat::toString would automatically print the shortest
374 // representation which rounds to the correct value, but it's a bit
375 // tricky to implement.
376 unsigned precision =
377 llvm::APFloat::semanticsPrecision(F.getSemantics());
378 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000379 SmallVector<char, 32> Buffer;
Eli Friedman4e1a82c2013-08-29 23:44:43 +0000380 F.toString(Buffer, precision);
Richard Smith789f9b62012-01-31 04:08:20 +0000381 *Diag << StringRef(Buffer.data(), Buffer.size());
382 }
383 return *this;
384 }
Richard Smithdd1f29b2011-12-12 09:28:41 +0000385 };
386
Richard Smith03ce5f82013-07-24 07:11:57 +0000387 /// A cleanup, and a flag indicating whether it is lifetime-extended.
388 class Cleanup {
389 llvm::PointerIntPair<APValue*, 1, bool> Value;
390
391 public:
392 Cleanup(APValue *Val, bool IsLifetimeExtended)
393 : Value(Val, IsLifetimeExtended) {}
394
395 bool isLifetimeExtended() const { return Value.getInt(); }
396 void endLifetime() {
397 *Value.getPointer() = APValue();
398 }
399 };
400
Richard Smith83587db2012-02-15 02:18:13 +0000401 /// EvalInfo - This is a private struct used by the evaluator to capture
402 /// information about a subexpression as it is folded. It retains information
403 /// about the AST context, but also maintains information about the folded
404 /// expression.
405 ///
406 /// If an expression could be evaluated, it is still possible it is not a C
407 /// "integer constant expression" or constant expression. If not, this struct
408 /// captures information about how and why not.
409 ///
410 /// One bit of information passed *into* the request for constant folding
411 /// indicates whether the subexpression is "evaluated" or not according to C
412 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
413 /// evaluate the expression regardless of what the RHS is, but C only allows
414 /// certain things in certain situations.
Richard Smithbd552ef2011-10-31 05:52:43 +0000415 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000416 ASTContext &Ctx;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +0000417
Richard Smithbd552ef2011-10-31 05:52:43 +0000418 /// EvalStatus - Contains information about the evaluation.
419 Expr::EvalStatus &EvalStatus;
420
421 /// CurrentCall - The top of the constexpr call stack.
422 CallStackFrame *CurrentCall;
423
Richard Smithbd552ef2011-10-31 05:52:43 +0000424 /// CallStackDepth - The number of calls in the call stack right now.
425 unsigned CallStackDepth;
426
Richard Smith83587db2012-02-15 02:18:13 +0000427 /// NextCallIndex - The next call index to assign.
428 unsigned NextCallIndex;
429
Richard Smithe7565632013-05-08 02:12:03 +0000430 /// StepsLeft - The remaining number of evaluation steps we're permitted
431 /// to perform. This is essentially a limit for the number of statements
432 /// we will evaluate.
433 unsigned StepsLeft;
434
Richard Smithbd552ef2011-10-31 05:52:43 +0000435 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000436 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000437 CallStackFrame BottomFrame;
438
Richard Smith03ce5f82013-07-24 07:11:57 +0000439 /// A stack of values whose lifetimes end at the end of some surrounding
440 /// evaluation frame.
441 llvm::SmallVector<Cleanup, 16> CleanupStack;
442
Richard Smith180f4792011-11-10 06:34:14 +0000443 /// EvaluatingDecl - This is the declaration whose initializer is being
444 /// evaluated, if any.
Richard Smith6391ea22013-05-09 07:14:00 +0000445 APValue::LValueBase EvaluatingDecl;
Richard Smith180f4792011-11-10 06:34:14 +0000446
447 /// EvaluatingDeclValue - This is the value being constructed for the
448 /// declaration whose initializer is being evaluated, if any.
449 APValue *EvaluatingDeclValue;
450
Richard Smithc1c5f272011-12-13 06:39:58 +0000451 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
452 /// notes attached to it will also be stored, otherwise they will not be.
453 bool HasActiveDiagnostic;
454
Richard Smith745f5142012-01-27 01:14:48 +0000455 /// CheckingPotentialConstantExpression - Are we checking whether the
456 /// expression is a potential constant expression? If so, some diagnostics
457 /// are suppressed.
458 bool CheckingPotentialConstantExpression;
Richard Smith03ce5f82013-07-24 07:11:57 +0000459
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000460 bool IntOverflowCheckMode;
Richard Smith745f5142012-01-27 01:14:48 +0000461
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000462 EvalInfo(const ASTContext &C, Expr::EvalStatus &S,
Richard Smithe7565632013-05-08 02:12:03 +0000463 bool OverflowCheckMode = false)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000464 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith83587db2012-02-15 02:18:13 +0000465 CallStackDepth(0), NextCallIndex(1),
Richard Smithe7565632013-05-08 02:12:03 +0000466 StepsLeft(getLangOpts().ConstexprStepLimit),
Richard Smith83587db2012-02-15 02:18:13 +0000467 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith6391ea22013-05-09 07:14:00 +0000468 EvaluatingDecl((const ValueDecl*)0), EvaluatingDeclValue(0),
469 HasActiveDiagnostic(false), CheckingPotentialConstantExpression(false),
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000470 IntOverflowCheckMode(OverflowCheckMode) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000471
Richard Smith6391ea22013-05-09 07:14:00 +0000472 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
473 EvaluatingDecl = Base;
Richard Smith180f4792011-11-10 06:34:14 +0000474 EvaluatingDeclValue = &Value;
475 }
476
David Blaikie4e4d0842012-03-11 07:00:24 +0000477 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smithc18c4232011-11-21 19:36:32 +0000478
Richard Smithc1c5f272011-12-13 06:39:58 +0000479 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000480 // Don't perform any constexpr calls (other than the call we're checking)
481 // when checking a potential constant expression.
482 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
483 return false;
Richard Smith83587db2012-02-15 02:18:13 +0000484 if (NextCallIndex == 0) {
485 // NextCallIndex has wrapped around.
486 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
487 return false;
488 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000489 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
490 return true;
491 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
492 << getLangOpts().ConstexprCallDepth;
493 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000494 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000495
Richard Smith83587db2012-02-15 02:18:13 +0000496 CallStackFrame *getCallFrame(unsigned CallIndex) {
497 assert(CallIndex && "no call index in getCallFrame");
498 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
499 // be null in this loop.
500 CallStackFrame *Frame = CurrentCall;
501 while (Frame->Index > CallIndex)
502 Frame = Frame->Caller;
503 return (Frame->Index == CallIndex) ? Frame : 0;
504 }
505
Richard Smithe7565632013-05-08 02:12:03 +0000506 bool nextStep(const Stmt *S) {
507 if (!StepsLeft) {
508 Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
509 return false;
510 }
511 --StepsLeft;
512 return true;
513 }
514
Richard Smithc1c5f272011-12-13 06:39:58 +0000515 private:
516 /// Add a diagnostic to the diagnostics list.
517 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
518 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
519 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
520 return EvalStatus.Diag->back().second;
521 }
522
Richard Smith08d6e032011-12-16 19:06:07 +0000523 /// Add notes containing a call stack to the current point of evaluation.
524 void addCallStack(unsigned Limit);
525
Richard Smithc1c5f272011-12-13 06:39:58 +0000526 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000527 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000528 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
529 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000530 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000531 // If we have a prior diagnostic, it will be noting that the expression
532 // isn't a constant expression. This diagnostic is more important.
533 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000534 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000535 unsigned CallStackNotes = CallStackDepth - 1;
536 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
537 if (Limit)
538 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000539 if (CheckingPotentialConstantExpression)
540 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000541
Richard Smithc1c5f272011-12-13 06:39:58 +0000542 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000543 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000544 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
545 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000546 if (!CheckingPotentialConstantExpression)
547 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000548 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000549 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000550 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000551 return OptionalDiagnostic();
552 }
553
Richard Smith5cfc7d82012-03-15 04:53:45 +0000554 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
555 = diag::note_invalid_subexpr_in_const_expr,
556 unsigned ExtraNotes = 0) {
557 if (EvalStatus.Diag)
558 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
559 HasActiveDiagnostic = false;
560 return OptionalDiagnostic();
561 }
562
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000563 bool getIntOverflowCheckMode() { return IntOverflowCheckMode; }
564
Richard Smithdd1f29b2011-12-12 09:28:41 +0000565 /// Diagnose that the evaluation does not produce a C++11 core constant
566 /// expression.
Richard Smith5cfc7d82012-03-15 04:53:45 +0000567 template<typename LocArg>
568 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smith7098cbd2011-12-21 05:04:46 +0000569 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000570 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000571 // Don't override a previous diagnostic.
Eli Friedman51e47df2012-02-21 22:41:33 +0000572 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
573 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000574 return OptionalDiagnostic();
Eli Friedman51e47df2012-02-21 22:41:33 +0000575 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000576 return Diag(Loc, DiagId, ExtraNotes);
577 }
578
579 /// Add a note to a prior diagnostic.
580 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
581 if (!HasActiveDiagnostic)
582 return OptionalDiagnostic();
583 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000584 }
Richard Smith099e7f62011-12-19 06:19:21 +0000585
586 /// Add a stack of notes to a prior diagnostic.
587 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
588 if (HasActiveDiagnostic) {
589 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
590 Diags.begin(), Diags.end());
591 }
592 }
Richard Smith745f5142012-01-27 01:14:48 +0000593
594 /// Should we continue evaluation as much as possible after encountering a
595 /// construct which can't be folded?
596 bool keepEvaluatingAfterFailure() {
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000597 // Should return true in IntOverflowCheckMode, so that we check for
598 // overflow even if some subexpressions can't be evaluated as constants.
Richard Smithe7565632013-05-08 02:12:03 +0000599 return StepsLeft && (IntOverflowCheckMode ||
600 (CheckingPotentialConstantExpression &&
601 EvalStatus.Diag && EvalStatus.Diag->empty()));
Richard Smith745f5142012-01-27 01:14:48 +0000602 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000603 };
Richard Smithf15fda02012-02-02 01:16:57 +0000604
605 /// Object used to treat all foldable expressions as constant expressions.
606 struct FoldConstant {
607 bool Enabled;
608
609 explicit FoldConstant(EvalInfo &Info)
610 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
611 !Info.EvalStatus.HasSideEffects) {
612 }
613 // Treat the value we've computed since this object was created as constant.
614 void Fold(EvalInfo &Info) {
615 if (Enabled && !Info.EvalStatus.Diag->empty() &&
616 !Info.EvalStatus.HasSideEffects)
617 Info.EvalStatus.Diag->clear();
618 }
619 };
Richard Smith74e1ad92012-02-16 02:46:34 +0000620
621 /// RAII object used to suppress diagnostics and side-effects from a
622 /// speculative evaluation.
623 class SpeculativeEvaluationRAII {
624 EvalInfo &Info;
625 Expr::EvalStatus Old;
626
627 public:
628 SpeculativeEvaluationRAII(EvalInfo &Info,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000629 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = 0)
Richard Smith74e1ad92012-02-16 02:46:34 +0000630 : Info(Info), Old(Info.EvalStatus) {
631 Info.EvalStatus.Diag = NewDiag;
632 }
633 ~SpeculativeEvaluationRAII() {
634 Info.EvalStatus = Old;
635 }
636 };
Richard Smith03ce5f82013-07-24 07:11:57 +0000637
638 /// RAII object wrapping a full-expression or block scope, and handling
639 /// the ending of the lifetime of temporaries created within it.
640 template<bool IsFullExpression>
641 class ScopeRAII {
642 EvalInfo &Info;
643 unsigned OldStackSize;
644 public:
645 ScopeRAII(EvalInfo &Info)
646 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
647 ~ScopeRAII() {
648 // Body moved to a static method to encourage the compiler to inline away
649 // instances of this class.
650 cleanup(Info, OldStackSize);
651 }
652 private:
653 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
654 unsigned NewEnd = OldStackSize;
655 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
656 I != N; ++I) {
657 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
658 // Full-expression cleanup of a lifetime-extended temporary: nothing
659 // to do, just move this cleanup to the right place in the stack.
660 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
661 ++NewEnd;
662 } else {
663 // End the lifetime of the object.
664 Info.CleanupStack[I].endLifetime();
665 }
666 }
667 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
668 Info.CleanupStack.end());
669 }
670 };
671 typedef ScopeRAII<false> BlockScopeRAII;
672 typedef ScopeRAII<true> FullExpressionRAII;
Richard Smith08d6e032011-12-16 19:06:07 +0000673}
Richard Smithbd552ef2011-10-31 05:52:43 +0000674
Richard Smithb4e85ed2012-01-06 16:39:00 +0000675bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
676 CheckSubobjectKind CSK) {
677 if (Invalid)
678 return false;
679 if (isOnePastTheEnd()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000680 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000681 << CSK;
682 setInvalid();
683 return false;
684 }
685 return true;
686}
687
688void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
689 const Expr *E, uint64_t N) {
690 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smith5cfc7d82012-03-15 04:53:45 +0000691 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000692 << static_cast<int>(N) << /*array*/ 0
693 << static_cast<unsigned>(MostDerivedArraySize);
694 else
Richard Smith5cfc7d82012-03-15 04:53:45 +0000695 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000696 << static_cast<int>(N) << /*non-array*/ 1;
697 setInvalid();
698}
699
Richard Smith08d6e032011-12-16 19:06:07 +0000700CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
701 const FunctionDecl *Callee, const LValue *This,
Richard Smithbebf5b12013-04-26 14:36:30 +0000702 APValue *Arguments)
Richard Smith08d6e032011-12-16 19:06:07 +0000703 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smith83587db2012-02-15 02:18:13 +0000704 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smith08d6e032011-12-16 19:06:07 +0000705 Info.CurrentCall = this;
706 ++Info.CallStackDepth;
707}
708
709CallStackFrame::~CallStackFrame() {
710 assert(Info.CurrentCall == this && "calls retired out of order");
711 --Info.CallStackDepth;
712 Info.CurrentCall = Caller;
713}
714
Richard Smith03ce5f82013-07-24 07:11:57 +0000715APValue &CallStackFrame::createTemporary(const void *Key,
716 bool IsLifetimeExtended) {
717 APValue &Result = Temporaries[Key];
718 assert(Result.isUninit() && "temporary created multiple times");
719 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
720 return Result;
721}
722
Richard Smith8a66bf72013-06-03 05:03:02 +0000723static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smith08d6e032011-12-16 19:06:07 +0000724
725void EvalInfo::addCallStack(unsigned Limit) {
726 // Determine which calls to skip, if any.
727 unsigned ActiveCalls = CallStackDepth - 1;
728 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
729 if (Limit && Limit < ActiveCalls) {
730 SkipStart = Limit / 2 + Limit % 2;
731 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000732 }
733
Richard Smith08d6e032011-12-16 19:06:07 +0000734 // Walk the call stack and add the diagnostics.
735 unsigned CallIdx = 0;
736 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
737 Frame = Frame->Caller, ++CallIdx) {
738 // Skip this call?
739 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
740 if (CallIdx == SkipStart) {
741 // Note that we're skipping calls.
742 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
743 << unsigned(ActiveCalls - Limit);
744 }
745 continue;
746 }
747
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000748 SmallVector<char, 128> Buffer;
Richard Smith08d6e032011-12-16 19:06:07 +0000749 llvm::raw_svector_ostream Out(Buffer);
750 describeCall(Frame, Out);
751 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
752 }
753}
754
755namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000756 struct ComplexValue {
757 private:
758 bool IsInt;
759
760 public:
761 APSInt IntReal, IntImag;
762 APFloat FloatReal, FloatImag;
763
764 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
765
766 void makeComplexFloat() { IsInt = false; }
767 bool isComplexFloat() const { return !IsInt; }
768 APFloat &getComplexFloatReal() { return FloatReal; }
769 APFloat &getComplexFloatImag() { return FloatImag; }
770
771 void makeComplexInt() { IsInt = true; }
772 bool isComplexInt() const { return IsInt; }
773 APSInt &getComplexIntReal() { return IntReal; }
774 APSInt &getComplexIntImag() { return IntImag; }
775
Richard Smith1aa0be82012-03-03 22:46:17 +0000776 void moveInto(APValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000777 if (isComplexFloat())
Richard Smith1aa0be82012-03-03 22:46:17 +0000778 v = APValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000779 else
Richard Smith1aa0be82012-03-03 22:46:17 +0000780 v = APValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000781 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000782 void setFrom(const APValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000783 assert(v.isComplexFloat() || v.isComplexInt());
784 if (v.isComplexFloat()) {
785 makeComplexFloat();
786 FloatReal = v.getComplexFloatReal();
787 FloatImag = v.getComplexFloatImag();
788 } else {
789 makeComplexInt();
790 IntReal = v.getComplexIntReal();
791 IntImag = v.getComplexIntImag();
792 }
793 }
John McCallf4cf1a12010-05-07 17:22:02 +0000794 };
John McCallefdb83e2010-05-07 21:00:08 +0000795
796 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000797 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000798 CharUnits Offset;
Richard Smith83587db2012-02-15 02:18:13 +0000799 unsigned CallIndex;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000800 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000801
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000802 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000803 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000804 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith83587db2012-02-15 02:18:13 +0000805 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000806 SubobjectDesignator &getLValueDesignator() { return Designator; }
807 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000808
Richard Smith1aa0be82012-03-03 22:46:17 +0000809 void moveInto(APValue &V) const {
810 if (Designator.Invalid)
811 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
812 else
813 V = APValue(Base, Offset, Designator.Entries,
814 Designator.IsOnePastTheEnd, CallIndex);
John McCallefdb83e2010-05-07 21:00:08 +0000815 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000816 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith47a1eed2011-10-29 20:57:55 +0000817 assert(V.isLValue());
818 Base = V.getLValueBase();
819 Offset = V.getLValueOffset();
Richard Smith83587db2012-02-15 02:18:13 +0000820 CallIndex = V.getLValueCallIndex();
Richard Smith1aa0be82012-03-03 22:46:17 +0000821 Designator = SubobjectDesignator(Ctx, V);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000822 }
823
Richard Smith83587db2012-02-15 02:18:13 +0000824 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000825 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000826 Offset = CharUnits::Zero();
Richard Smith83587db2012-02-15 02:18:13 +0000827 CallIndex = I;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000828 Designator = SubobjectDesignator(getType(B));
829 }
830
831 // Check that this LValue is not based on a null pointer. If it is, produce
832 // a diagnostic and mark the designator as invalid.
833 bool checkNullPointer(EvalInfo &Info, const Expr *E,
834 CheckSubobjectKind CSK) {
835 if (Designator.Invalid)
836 return false;
837 if (!Base) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000838 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000839 << CSK;
840 Designator.setInvalid();
841 return false;
842 }
843 return true;
844 }
845
846 // Check this LValue refers to an object. If not, set the designator to be
847 // invalid and emit a diagnostic.
848 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000849 // Outside C++11, do not build a designator referring to a subobject of
850 // any object: we won't use such a designator for anything.
Richard Smith80ad52f2013-01-02 11:42:31 +0000851 if (!Info.getLangOpts().CPlusPlus11)
Richard Smith5cfc7d82012-03-15 04:53:45 +0000852 Designator.setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000853 return checkNullPointer(Info, E, CSK) &&
854 Designator.checkSubobject(Info, E, CSK);
855 }
856
857 void addDecl(EvalInfo &Info, const Expr *E,
858 const Decl *D, bool Virtual = false) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000859 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
860 Designator.addDeclUnchecked(D, Virtual);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000861 }
862 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000863 if (checkSubobject(Info, E, CSK_ArrayToPointer))
864 Designator.addArrayUnchecked(CAT);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000865 }
Richard Smith86024012012-02-18 22:04:06 +0000866 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000867 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
868 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith86024012012-02-18 22:04:06 +0000869 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000870 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000871 if (checkNullPointer(Info, E, CSK_ArrayIndex))
872 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000873 }
John McCallefdb83e2010-05-07 21:00:08 +0000874 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000875
876 struct MemberPtr {
877 MemberPtr() {}
878 explicit MemberPtr(const ValueDecl *Decl) :
879 DeclAndIsDerivedMember(Decl, false), Path() {}
880
881 /// The member or (direct or indirect) field referred to by this member
882 /// pointer, or 0 if this is a null member pointer.
883 const ValueDecl *getDecl() const {
884 return DeclAndIsDerivedMember.getPointer();
885 }
886 /// Is this actually a member of some type derived from the relevant class?
887 bool isDerivedMember() const {
888 return DeclAndIsDerivedMember.getInt();
889 }
890 /// Get the class which the declaration actually lives in.
891 const CXXRecordDecl *getContainingRecord() const {
892 return cast<CXXRecordDecl>(
893 DeclAndIsDerivedMember.getPointer()->getDeclContext());
894 }
895
Richard Smith1aa0be82012-03-03 22:46:17 +0000896 void moveInto(APValue &V) const {
897 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000898 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000899 void setFrom(const APValue &V) {
Richard Smithe24f5fc2011-11-17 22:56:20 +0000900 assert(V.isMemberPointer());
901 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
902 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
903 Path.clear();
904 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
905 Path.insert(Path.end(), P.begin(), P.end());
906 }
907
908 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
909 /// whether the member is a member of some class derived from the class type
910 /// of the member pointer.
911 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
912 /// Path - The path of base/derived classes from the member declaration's
913 /// class (exclusive) to the class type of the member pointer (inclusive).
914 SmallVector<const CXXRecordDecl*, 4> Path;
915
916 /// Perform a cast towards the class of the Decl (either up or down the
917 /// hierarchy).
918 bool castBack(const CXXRecordDecl *Class) {
919 assert(!Path.empty());
920 const CXXRecordDecl *Expected;
921 if (Path.size() >= 2)
922 Expected = Path[Path.size() - 2];
923 else
924 Expected = getContainingRecord();
925 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
926 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
927 // if B does not contain the original member and is not a base or
928 // derived class of the class containing the original member, the result
929 // of the cast is undefined.
930 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
931 // (D::*). We consider that to be a language defect.
932 return false;
933 }
934 Path.pop_back();
935 return true;
936 }
937 /// Perform a base-to-derived member pointer cast.
938 bool castToDerived(const CXXRecordDecl *Derived) {
939 if (!getDecl())
940 return true;
941 if (!isDerivedMember()) {
942 Path.push_back(Derived);
943 return true;
944 }
945 if (!castBack(Derived))
946 return false;
947 if (Path.empty())
948 DeclAndIsDerivedMember.setInt(false);
949 return true;
950 }
951 /// Perform a derived-to-base member pointer cast.
952 bool castToBase(const CXXRecordDecl *Base) {
953 if (!getDecl())
954 return true;
955 if (Path.empty())
956 DeclAndIsDerivedMember.setInt(true);
957 if (isDerivedMember()) {
958 Path.push_back(Base);
959 return true;
960 }
961 return castBack(Base);
962 }
963 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000964
Richard Smithb02e4622012-02-01 01:42:44 +0000965 /// Compare two member pointers, which are assumed to be of the same type.
966 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
967 if (!LHS.getDecl() || !RHS.getDecl())
968 return !LHS.getDecl() && !RHS.getDecl();
969 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
970 return false;
971 return LHS.Path == RHS.Path;
972 }
John McCallf4cf1a12010-05-07 17:22:02 +0000973}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000974
Richard Smith1aa0be82012-03-03 22:46:17 +0000975static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith83587db2012-02-15 02:18:13 +0000976static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
977 const LValue &This, const Expr *E,
Richard Smith83587db2012-02-15 02:18:13 +0000978 bool AllowNonLiteralTypes = false);
John McCallefdb83e2010-05-07 21:00:08 +0000979static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
980static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000981static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
982 EvalInfo &Info);
983static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000984static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith1aa0be82012-03-03 22:46:17 +0000985static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000986 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000987static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000988static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith5705f212013-05-23 00:30:41 +0000989static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000990
991//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000992// Misc utilities
993//===----------------------------------------------------------------------===//
994
Richard Smith8a66bf72013-06-03 05:03:02 +0000995/// Produce a string describing the given constexpr call.
996static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
997 unsigned ArgIndex = 0;
998 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
999 !isa<CXXConstructorDecl>(Frame->Callee) &&
1000 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1001
1002 if (!IsMemberCall)
1003 Out << *Frame->Callee << '(';
1004
1005 if (Frame->This && IsMemberCall) {
1006 APValue Val;
1007 Frame->This->moveInto(Val);
1008 Val.printPretty(Out, Frame->Info.Ctx,
1009 Frame->This->Designator.MostDerivedType);
1010 // FIXME: Add parens around Val if needed.
1011 Out << "->" << *Frame->Callee << '(';
1012 IsMemberCall = false;
1013 }
1014
1015 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1016 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1017 if (ArgIndex > (unsigned)IsMemberCall)
1018 Out << ", ";
1019
1020 const ParmVarDecl *Param = *I;
1021 const APValue &Arg = Frame->Arguments[ArgIndex];
1022 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1023
1024 if (ArgIndex == 0 && IsMemberCall)
1025 Out << "->" << *Frame->Callee << '(';
1026 }
1027
1028 Out << ')';
1029}
1030
Richard Smitha10b9782013-04-22 15:31:51 +00001031/// Evaluate an expression to see if it had side-effects, and discard its
1032/// result.
Richard Smithce617152013-05-06 05:56:11 +00001033/// \return \c true if the caller should keep evaluating.
1034static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smitha10b9782013-04-22 15:31:51 +00001035 APValue Scratch;
Richard Smithce617152013-05-06 05:56:11 +00001036 if (!Evaluate(Scratch, Info, E)) {
Richard Smitha10b9782013-04-22 15:31:51 +00001037 Info.EvalStatus.HasSideEffects = true;
Richard Smithce617152013-05-06 05:56:11 +00001038 return Info.keepEvaluatingAfterFailure();
1039 }
1040 return true;
Richard Smitha10b9782013-04-22 15:31:51 +00001041}
1042
Richard Smitha49a7fe2013-05-07 23:34:45 +00001043/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1044/// return its existing value.
1045static int64_t getExtValue(const APSInt &Value) {
1046 return Value.isSigned() ? Value.getSExtValue()
1047 : static_cast<int64_t>(Value.getZExtValue());
1048}
1049
Richard Smith180f4792011-11-10 06:34:14 +00001050/// Should this call expression be treated as a string literal?
1051static bool IsStringLiteralCall(const CallExpr *E) {
1052 unsigned Builtin = E->isBuiltinCall();
1053 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1054 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1055}
1056
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001057static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +00001058 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1059 // constant expression of pointer type that evaluates to...
1060
1061 // ... a null pointer value, or a prvalue core constant expression of type
1062 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001063 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +00001064
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001065 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1066 // ... the address of an object with static storage duration,
1067 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1068 return VD->hasGlobalStorage();
1069 // ... the address of a function,
1070 return isa<FunctionDecl>(D);
1071 }
1072
1073 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +00001074 switch (E->getStmtClass()) {
1075 default:
1076 return false;
Richard Smithb78ae972012-02-18 04:58:18 +00001077 case Expr::CompoundLiteralExprClass: {
1078 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1079 return CLE->isFileScope() && CLE->isLValue();
1080 }
Richard Smith211c8dd2013-06-05 00:46:14 +00001081 case Expr::MaterializeTemporaryExprClass:
1082 // A materialized temporary might have been lifetime-extended to static
1083 // storage duration.
1084 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smith180f4792011-11-10 06:34:14 +00001085 // A string literal has static storage duration.
1086 case Expr::StringLiteralClass:
1087 case Expr::PredefinedExprClass:
1088 case Expr::ObjCStringLiteralClass:
1089 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +00001090 case Expr::CXXTypeidExprClass:
Francois Pichete275a182012-04-16 04:08:35 +00001091 case Expr::CXXUuidofExprClass:
Richard Smith180f4792011-11-10 06:34:14 +00001092 return true;
1093 case Expr::CallExprClass:
1094 return IsStringLiteralCall(cast<CallExpr>(E));
1095 // For GCC compatibility, &&label has static storage duration.
1096 case Expr::AddrLabelExprClass:
1097 return true;
1098 // A Block literal expression may be used as the initialization value for
1099 // Block variables at global or local static scope.
1100 case Expr::BlockExprClass:
1101 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +00001102 case Expr::ImplicitValueInitExprClass:
1103 // FIXME:
1104 // We can never form an lvalue with an implicit value initialization as its
1105 // base through expression evaluation, so these only appear in one case: the
1106 // implicit variable declaration we invent when checking whether a constexpr
1107 // constructor can produce a constant expression. We must assume that such
1108 // an expression might be a global lvalue.
1109 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001110 }
John McCall42c8f872010-05-10 23:27:23 +00001111}
1112
Richard Smith83587db2012-02-15 02:18:13 +00001113static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1114 assert(Base && "no location for a null lvalue");
1115 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1116 if (VD)
1117 Info.Note(VD->getLocation(), diag::note_declared_at);
1118 else
Ted Kremenek890f0f12012-08-23 20:46:57 +00001119 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smith83587db2012-02-15 02:18:13 +00001120 diag::note_constexpr_temporary_here);
1121}
1122
Richard Smith9a17a682011-11-07 05:07:52 +00001123/// Check that this reference or pointer core constant expression is a valid
Richard Smith1aa0be82012-03-03 22:46:17 +00001124/// value for an address or reference constant expression. Return true if we
1125/// can fold this expression, whether or not it's a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +00001126static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1127 QualType Type, const LValue &LVal) {
1128 bool IsReferenceType = Type->isReferenceType();
1129
Richard Smithc1c5f272011-12-13 06:39:58 +00001130 APValue::LValueBase Base = LVal.getLValueBase();
1131 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1132
Richard Smithb78ae972012-02-18 04:58:18 +00001133 // Check that the object is a global. Note that the fake 'this' object we
1134 // manufacture when checking potential constant expressions is conservatively
1135 // assumed to be global here.
Richard Smithc1c5f272011-12-13 06:39:58 +00001136 if (!IsGlobalLValue(Base)) {
Richard Smith80ad52f2013-01-02 11:42:31 +00001137 if (Info.getLangOpts().CPlusPlus11) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001138 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001139 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1140 << IsReferenceType << !Designator.Entries.empty()
1141 << !!VD << VD;
1142 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001143 } else {
Richard Smith83587db2012-02-15 02:18:13 +00001144 Info.Diag(Loc);
Richard Smithc1c5f272011-12-13 06:39:58 +00001145 }
Richard Smith61e61622012-01-12 06:08:57 +00001146 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +00001147 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001148 }
Richard Smith83587db2012-02-15 02:18:13 +00001149 assert((Info.CheckingPotentialConstantExpression ||
1150 LVal.getLValueCallIndex() == 0) &&
1151 "have call index for global lvalue");
Richard Smithb4e85ed2012-01-06 16:39:00 +00001152
Hans Wennborg48def652012-08-29 18:27:29 +00001153 // Check if this is a thread-local variable.
1154 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1155 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
Richard Smith38afbc72013-04-13 02:43:54 +00001156 if (Var->getTLSKind())
Hans Wennborg48def652012-08-29 18:27:29 +00001157 return false;
1158 }
1159 }
1160
Richard Smithb4e85ed2012-01-06 16:39:00 +00001161 // Allow address constant expressions to be past-the-end pointers. This is
1162 // an extension: the standard requires them to point to an object.
1163 if (!IsReferenceType)
1164 return true;
1165
1166 // A reference constant expression must refer to an object.
1167 if (!Base) {
1168 // FIXME: diagnostic
Richard Smith83587db2012-02-15 02:18:13 +00001169 Info.CCEDiag(Loc);
Richard Smith61e61622012-01-12 06:08:57 +00001170 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001171 }
1172
Richard Smithc1c5f272011-12-13 06:39:58 +00001173 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +00001174 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001175 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001176 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smithc1c5f272011-12-13 06:39:58 +00001177 << !Designator.Entries.empty() << !!VD << VD;
Richard Smith83587db2012-02-15 02:18:13 +00001178 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001179 }
1180
Richard Smith9a17a682011-11-07 05:07:52 +00001181 return true;
1182}
1183
Richard Smith51201882011-12-30 21:15:51 +00001184/// Check that this core constant expression is of literal type, and if not,
1185/// produce an appropriate diagnostic.
Richard Smith6391ea22013-05-09 07:14:00 +00001186static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1187 const LValue *This = 0) {
Richard Smitha10b9782013-04-22 15:31:51 +00001188 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smith51201882011-12-30 21:15:51 +00001189 return true;
1190
Richard Smith6391ea22013-05-09 07:14:00 +00001191 // C++1y: A constant initializer for an object o [...] may also invoke
1192 // constexpr constructors for o and its subobjects even if those objects
1193 // are of non-literal class types.
1194 if (Info.getLangOpts().CPlusPlus1y && This &&
Richard Smithc45c8dd2013-05-16 05:04:51 +00001195 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith6391ea22013-05-09 07:14:00 +00001196 return true;
1197
Richard Smith51201882011-12-30 21:15:51 +00001198 // Prvalue constant expressions must be of literal types.
Richard Smith80ad52f2013-01-02 11:42:31 +00001199 if (Info.getLangOpts().CPlusPlus11)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001200 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smith51201882011-12-30 21:15:51 +00001201 << E->getType();
1202 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001203 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith51201882011-12-30 21:15:51 +00001204 return false;
1205}
1206
Richard Smith47a1eed2011-10-29 20:57:55 +00001207/// Check that this core constant expression value is a valid value for a
Richard Smith83587db2012-02-15 02:18:13 +00001208/// constant expression. If not, report an appropriate diagnostic. Does not
1209/// check that the expression is of literal type.
1210static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1211 QualType Type, const APValue &Value) {
Richard Smith3ed4d1c2013-06-18 17:51:51 +00001212 if (Value.isUninit()) {
Richard Smith37a84f62013-06-20 03:00:05 +00001213 Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1214 << true << Type;
Richard Smith3ed4d1c2013-06-18 17:51:51 +00001215 return false;
1216 }
1217
Richard Smith83587db2012-02-15 02:18:13 +00001218 // Core issue 1454: For a literal constant expression of array or class type,
1219 // each subobject of its value shall have been initialized by a constant
1220 // expression.
1221 if (Value.isArray()) {
1222 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1223 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1224 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1225 Value.getArrayInitializedElt(I)))
1226 return false;
1227 }
1228 if (!Value.hasArrayFiller())
1229 return true;
1230 return CheckConstantExpression(Info, DiagLoc, EltTy,
1231 Value.getArrayFiller());
Richard Smith9a17a682011-11-07 05:07:52 +00001232 }
Richard Smith83587db2012-02-15 02:18:13 +00001233 if (Value.isUnion() && Value.getUnionField()) {
1234 return CheckConstantExpression(Info, DiagLoc,
1235 Value.getUnionField()->getType(),
1236 Value.getUnionValue());
1237 }
1238 if (Value.isStruct()) {
1239 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1240 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1241 unsigned BaseIndex = 0;
1242 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1243 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1244 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1245 Value.getStructBase(BaseIndex)))
1246 return false;
1247 }
1248 }
1249 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1250 I != E; ++I) {
David Blaikie262bc182012-04-30 02:36:29 +00001251 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1252 Value.getStructField(I->getFieldIndex())))
Richard Smith83587db2012-02-15 02:18:13 +00001253 return false;
1254 }
1255 }
1256
1257 if (Value.isLValue()) {
Richard Smith83587db2012-02-15 02:18:13 +00001258 LValue LVal;
Richard Smith1aa0be82012-03-03 22:46:17 +00001259 LVal.setFrom(Info.Ctx, Value);
Richard Smith83587db2012-02-15 02:18:13 +00001260 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1261 }
1262
1263 // Everything else is fine.
1264 return true;
Richard Smith47a1eed2011-10-29 20:57:55 +00001265}
1266
Richard Smith9e36b532011-10-31 05:11:32 +00001267const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001268 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001269}
1270
1271static bool IsLiteralLValue(const LValue &Value) {
Richard Smith211c8dd2013-06-05 00:46:14 +00001272 if (Value.CallIndex)
1273 return false;
1274 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1275 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith9e36b532011-10-31 05:11:32 +00001276}
1277
Richard Smith65ac5982011-11-01 21:06:14 +00001278static bool IsWeakLValue(const LValue &Value) {
1279 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001280 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001281}
1282
Richard Smith1aa0be82012-03-03 22:46:17 +00001283static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001284 // A null base expression indicates a null pointer. These are always
1285 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001286 if (!Value.getLValueBase()) {
1287 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001288 return true;
1289 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001290
Richard Smithe24f5fc2011-11-17 22:56:20 +00001291 // We have a non-null base. These are generally known to be true, but if it's
1292 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001293 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001294 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001295 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001296}
1297
Richard Smith1aa0be82012-03-03 22:46:17 +00001298static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001299 switch (Val.getKind()) {
1300 case APValue::Uninitialized:
1301 return false;
1302 case APValue::Int:
1303 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001304 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001305 case APValue::Float:
1306 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001307 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001308 case APValue::ComplexInt:
1309 Result = Val.getComplexIntReal().getBoolValue() ||
1310 Val.getComplexIntImag().getBoolValue();
1311 return true;
1312 case APValue::ComplexFloat:
1313 Result = !Val.getComplexFloatReal().isZero() ||
1314 !Val.getComplexFloatImag().isZero();
1315 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001316 case APValue::LValue:
1317 return EvalPointerValueAsBool(Val, Result);
1318 case APValue::MemberPointer:
1319 Result = Val.getMemberPointerDecl();
1320 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001321 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001322 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001323 case APValue::Struct:
1324 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001325 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001326 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001327 }
1328
Richard Smithc49bd112011-10-28 17:51:58 +00001329 llvm_unreachable("unknown APValue kind");
1330}
1331
1332static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1333 EvalInfo &Info) {
1334 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith1aa0be82012-03-03 22:46:17 +00001335 APValue Val;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001336 if (!Evaluate(Val, Info, E))
Richard Smithc49bd112011-10-28 17:51:58 +00001337 return false;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001338 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001339}
1340
Richard Smithc1c5f272011-12-13 06:39:58 +00001341template<typename T>
Eli Friedman26dc97c2012-07-17 21:03:05 +00001342static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +00001343 const T &SrcValue, QualType DestType) {
Eli Friedman26dc97c2012-07-17 21:03:05 +00001344 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001345 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001346}
1347
1348static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1349 QualType SrcType, const APFloat &Value,
1350 QualType DestType, APSInt &Result) {
1351 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001352 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001353 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001354
Richard Smithc1c5f272011-12-13 06:39:58 +00001355 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001356 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001357 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1358 & APFloat::opInvalidOp)
Eli Friedman26dc97c2012-07-17 21:03:05 +00001359 HandleOverflow(Info, E, Value, DestType);
Richard Smithc1c5f272011-12-13 06:39:58 +00001360 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001361}
1362
Richard Smithc1c5f272011-12-13 06:39:58 +00001363static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1364 QualType SrcType, QualType DestType,
1365 APFloat &Result) {
1366 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001367 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001368 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1369 APFloat::rmNearestTiesToEven, &ignored)
1370 & APFloat::opOverflow)
Eli Friedman26dc97c2012-07-17 21:03:05 +00001371 HandleOverflow(Info, E, Value, DestType);
Richard Smithc1c5f272011-12-13 06:39:58 +00001372 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001373}
1374
Richard Smithf72fccf2012-01-30 22:27:01 +00001375static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1376 QualType DestType, QualType SrcType,
1377 APSInt &Value) {
1378 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001379 APSInt Result = Value;
1380 // Figure out if this is a truncate, extend or noop cast.
1381 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001382 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001383 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001384 return Result;
1385}
1386
Richard Smithc1c5f272011-12-13 06:39:58 +00001387static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1388 QualType SrcType, const APSInt &Value,
1389 QualType DestType, APFloat &Result) {
1390 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1391 if (Result.convertFromAPInt(Value, Value.isSigned(),
1392 APFloat::rmNearestTiesToEven)
1393 & APFloat::opOverflow)
Eli Friedman26dc97c2012-07-17 21:03:05 +00001394 HandleOverflow(Info, E, Value, DestType);
Richard Smithc1c5f272011-12-13 06:39:58 +00001395 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001396}
1397
Richard Smith3835a4e2013-08-06 07:09:20 +00001398static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1399 APValue &Value, const FieldDecl *FD) {
1400 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1401
1402 if (!Value.isInt()) {
1403 // Trying to store a pointer-cast-to-integer into a bitfield.
1404 // FIXME: In this case, we should provide the diagnostic for casting
1405 // a pointer to an integer.
1406 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1407 Info.Diag(E);
1408 return false;
1409 }
1410
1411 APSInt &Int = Value.getInt();
1412 unsigned OldBitWidth = Int.getBitWidth();
1413 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1414 if (NewBitWidth < OldBitWidth)
1415 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1416 return true;
1417}
1418
Eli Friedmane6a24e82011-12-22 03:51:45 +00001419static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1420 llvm::APInt &Res) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001421 APValue SVal;
Eli Friedmane6a24e82011-12-22 03:51:45 +00001422 if (!Evaluate(SVal, Info, E))
1423 return false;
1424 if (SVal.isInt()) {
1425 Res = SVal.getInt();
1426 return true;
1427 }
1428 if (SVal.isFloat()) {
1429 Res = SVal.getFloat().bitcastToAPInt();
1430 return true;
1431 }
1432 if (SVal.isVector()) {
1433 QualType VecTy = E->getType();
1434 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1435 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1436 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1437 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1438 Res = llvm::APInt::getNullValue(VecSize);
1439 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1440 APValue &Elt = SVal.getVectorElt(i);
1441 llvm::APInt EltAsInt;
1442 if (Elt.isInt()) {
1443 EltAsInt = Elt.getInt();
1444 } else if (Elt.isFloat()) {
1445 EltAsInt = Elt.getFloat().bitcastToAPInt();
1446 } else {
1447 // Don't try to handle vectors of anything other than int or float
1448 // (not sure if it's possible to hit this case).
Richard Smith5cfc7d82012-03-15 04:53:45 +00001449 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001450 return false;
1451 }
1452 unsigned BaseEltSize = EltAsInt.getBitWidth();
1453 if (BigEndian)
1454 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1455 else
1456 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1457 }
1458 return true;
1459 }
1460 // Give up if the input isn't an int, float, or vector. For example, we
1461 // reject "(v4i16)(intptr_t)&a".
Richard Smith5cfc7d82012-03-15 04:53:45 +00001462 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001463 return false;
1464}
1465
Richard Smithd20afcb2013-05-07 04:50:00 +00001466/// Perform the given integer operation, which is known to need at most BitWidth
1467/// bits, and check for overflow in the original type (if that type was not an
1468/// unsigned type).
1469template<typename Operation>
1470static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1471 const APSInt &LHS, const APSInt &RHS,
1472 unsigned BitWidth, Operation Op) {
1473 if (LHS.isUnsigned())
1474 return Op(LHS, RHS);
1475
1476 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1477 APSInt Result = Value.trunc(LHS.getBitWidth());
1478 if (Result.extend(BitWidth) != Value) {
1479 if (Info.getIntOverflowCheckMode())
1480 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1481 diag::warn_integer_constant_overflow)
1482 << Result.toString(10) << E->getType();
1483 else
1484 HandleOverflow(Info, E, Value, E->getType());
1485 }
1486 return Result;
1487}
1488
1489/// Perform the given binary integer operation.
1490static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1491 BinaryOperatorKind Opcode, APSInt RHS,
1492 APSInt &Result) {
1493 switch (Opcode) {
1494 default:
1495 Info.Diag(E);
1496 return false;
1497 case BO_Mul:
1498 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1499 std::multiplies<APSInt>());
1500 return true;
1501 case BO_Add:
1502 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1503 std::plus<APSInt>());
1504 return true;
1505 case BO_Sub:
1506 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1507 std::minus<APSInt>());
1508 return true;
1509 case BO_And: Result = LHS & RHS; return true;
1510 case BO_Xor: Result = LHS ^ RHS; return true;
1511 case BO_Or: Result = LHS | RHS; return true;
1512 case BO_Div:
1513 case BO_Rem:
1514 if (RHS == 0) {
1515 Info.Diag(E, diag::note_expr_divide_by_zero);
1516 return false;
1517 }
1518 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1519 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1520 LHS.isSigned() && LHS.isMinSignedValue())
1521 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1522 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1523 return true;
1524 case BO_Shl: {
1525 if (Info.getLangOpts().OpenCL)
1526 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1527 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1528 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1529 RHS.isUnsigned());
1530 else if (RHS.isSigned() && RHS.isNegative()) {
1531 // During constant-folding, a negative shift is an opposite shift. Such
1532 // a shift is not a constant expression.
1533 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1534 RHS = -RHS;
1535 goto shift_right;
1536 }
1537 shift_left:
1538 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1539 // the shifted type.
1540 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1541 if (SA != RHS) {
1542 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1543 << RHS << E->getType() << LHS.getBitWidth();
1544 } else if (LHS.isSigned()) {
1545 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1546 // operand, and must not overflow the corresponding unsigned type.
1547 if (LHS.isNegative())
1548 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1549 else if (LHS.countLeadingZeros() < SA)
1550 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1551 }
1552 Result = LHS << SA;
1553 return true;
1554 }
1555 case BO_Shr: {
1556 if (Info.getLangOpts().OpenCL)
1557 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1558 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1559 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1560 RHS.isUnsigned());
1561 else if (RHS.isSigned() && RHS.isNegative()) {
1562 // During constant-folding, a negative shift is an opposite shift. Such a
1563 // shift is not a constant expression.
1564 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1565 RHS = -RHS;
1566 goto shift_left;
1567 }
1568 shift_right:
1569 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1570 // shifted type.
1571 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1572 if (SA != RHS)
1573 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1574 << RHS << E->getType() << LHS.getBitWidth();
1575 Result = LHS >> SA;
1576 return true;
1577 }
1578
1579 case BO_LT: Result = LHS < RHS; return true;
1580 case BO_GT: Result = LHS > RHS; return true;
1581 case BO_LE: Result = LHS <= RHS; return true;
1582 case BO_GE: Result = LHS >= RHS; return true;
1583 case BO_EQ: Result = LHS == RHS; return true;
1584 case BO_NE: Result = LHS != RHS; return true;
1585 }
1586}
1587
Richard Smitha49a7fe2013-05-07 23:34:45 +00001588/// Perform the given binary floating-point operation, in-place, on LHS.
1589static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1590 APFloat &LHS, BinaryOperatorKind Opcode,
1591 const APFloat &RHS) {
1592 switch (Opcode) {
1593 default:
1594 Info.Diag(E);
1595 return false;
1596 case BO_Mul:
1597 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1598 break;
1599 case BO_Add:
1600 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1601 break;
1602 case BO_Sub:
1603 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1604 break;
1605 case BO_Div:
1606 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1607 break;
1608 }
1609
1610 if (LHS.isInfinity() || LHS.isNaN())
1611 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1612 return true;
1613}
1614
Richard Smithb4e85ed2012-01-06 16:39:00 +00001615/// Cast an lvalue referring to a base subobject to a derived class, by
1616/// truncating the lvalue's path to the given length.
1617static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1618 const RecordDecl *TruncatedType,
1619 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001620 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001621
1622 // Check we actually point to a derived class object.
1623 if (TruncatedElements == D.Entries.size())
1624 return true;
1625 assert(TruncatedElements >= D.MostDerivedPathLength &&
1626 "not casting to a derived class");
1627 if (!Result.checkSubobject(Info, E, CSK_Derived))
1628 return false;
1629
1630 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001631 const RecordDecl *RD = TruncatedType;
1632 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCall8d59dee2012-05-01 00:38:49 +00001633 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001634 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1635 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001636 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001637 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001638 else
Richard Smith180f4792011-11-10 06:34:14 +00001639 Result.Offset -= Layout.getBaseClassOffset(Base);
1640 RD = Base;
1641 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001642 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001643 return true;
1644}
1645
John McCall8d59dee2012-05-01 00:38:49 +00001646static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001647 const CXXRecordDecl *Derived,
1648 const CXXRecordDecl *Base,
1649 const ASTRecordLayout *RL = 0) {
John McCall8d59dee2012-05-01 00:38:49 +00001650 if (!RL) {
1651 if (Derived->isInvalidDecl()) return false;
1652 RL = &Info.Ctx.getASTRecordLayout(Derived);
1653 }
1654
Richard Smith180f4792011-11-10 06:34:14 +00001655 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001656 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCall8d59dee2012-05-01 00:38:49 +00001657 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001658}
1659
Richard Smithb4e85ed2012-01-06 16:39:00 +00001660static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001661 const CXXRecordDecl *DerivedDecl,
1662 const CXXBaseSpecifier *Base) {
1663 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1664
John McCall8d59dee2012-05-01 00:38:49 +00001665 if (!Base->isVirtual())
1666 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001667
Richard Smithb4e85ed2012-01-06 16:39:00 +00001668 SubobjectDesignator &D = Obj.Designator;
1669 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001670 return false;
1671
Richard Smithb4e85ed2012-01-06 16:39:00 +00001672 // Extract most-derived object and corresponding type.
1673 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1674 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1675 return false;
1676
1677 // Find the virtual base class.
John McCall8d59dee2012-05-01 00:38:49 +00001678 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001679 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1680 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001681 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001682 return true;
1683}
1684
Richard Smith8a66bf72013-06-03 05:03:02 +00001685static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1686 QualType Type, LValue &Result) {
1687 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1688 PathE = E->path_end();
1689 PathI != PathE; ++PathI) {
1690 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1691 *PathI))
1692 return false;
1693 Type = (*PathI)->getType();
1694 }
1695 return true;
1696}
1697
Richard Smith180f4792011-11-10 06:34:14 +00001698/// Update LVal to refer to the given field, which must be a member of the type
1699/// currently described by LVal.
John McCall8d59dee2012-05-01 00:38:49 +00001700static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001701 const FieldDecl *FD,
1702 const ASTRecordLayout *RL = 0) {
John McCall8d59dee2012-05-01 00:38:49 +00001703 if (!RL) {
1704 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001705 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCall8d59dee2012-05-01 00:38:49 +00001706 }
Richard Smith180f4792011-11-10 06:34:14 +00001707
1708 unsigned I = FD->getFieldIndex();
1709 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001710 LVal.addDecl(Info, E, FD);
John McCall8d59dee2012-05-01 00:38:49 +00001711 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001712}
1713
Richard Smithd9b02e72012-01-25 22:15:11 +00001714/// Update LVal to refer to the given indirect field.
John McCall8d59dee2012-05-01 00:38:49 +00001715static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smithd9b02e72012-01-25 22:15:11 +00001716 LValue &LVal,
1717 const IndirectFieldDecl *IFD) {
1718 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1719 CE = IFD->chain_end(); C != CE; ++C)
John McCall8d59dee2012-05-01 00:38:49 +00001720 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1721 return false;
1722 return true;
Richard Smithd9b02e72012-01-25 22:15:11 +00001723}
1724
Richard Smith180f4792011-11-10 06:34:14 +00001725/// Get the size of the given type in char units.
Richard Smith74e1ad92012-02-16 02:46:34 +00001726static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1727 QualType Type, CharUnits &Size) {
Richard Smith180f4792011-11-10 06:34:14 +00001728 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1729 // extension.
1730 if (Type->isVoidType() || Type->isFunctionType()) {
1731 Size = CharUnits::One();
1732 return true;
1733 }
1734
1735 if (!Type->isConstantSizeType()) {
1736 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith74e1ad92012-02-16 02:46:34 +00001737 // FIXME: Better diagnostic.
1738 Info.Diag(Loc);
Richard Smith180f4792011-11-10 06:34:14 +00001739 return false;
1740 }
1741
1742 Size = Info.Ctx.getTypeSizeInChars(Type);
1743 return true;
1744}
1745
1746/// Update a pointer value to model pointer arithmetic.
1747/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001748/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001749/// \param LVal - The pointer value to be updated.
1750/// \param EltTy - The pointee type represented by LVal.
1751/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001752static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1753 LValue &LVal, QualType EltTy,
1754 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001755 CharUnits SizeOfPointee;
Richard Smith74e1ad92012-02-16 02:46:34 +00001756 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smith180f4792011-11-10 06:34:14 +00001757 return false;
1758
1759 // Compute the new offset in the appropriate width.
1760 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001761 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001762 return true;
1763}
1764
Richard Smith86024012012-02-18 22:04:06 +00001765/// Update an lvalue to refer to a component of a complex number.
1766/// \param Info - Information about the ongoing evaluation.
1767/// \param LVal - The lvalue to be updated.
1768/// \param EltTy - The complex number's component type.
1769/// \param Imag - False for the real component, true for the imaginary.
1770static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1771 LValue &LVal, QualType EltTy,
1772 bool Imag) {
1773 if (Imag) {
1774 CharUnits SizeOfComponent;
1775 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1776 return false;
1777 LVal.Offset += SizeOfComponent;
1778 }
1779 LVal.addComplex(Info, E, EltTy, Imag);
1780 return true;
1781}
1782
Richard Smith03f96112011-10-24 17:54:18 +00001783/// Try to evaluate the initializer for a variable declaration.
Richard Smithb476a142013-05-05 21:17:10 +00001784///
1785/// \param Info Information about the ongoing evaluation.
1786/// \param E An expression to be used when printing diagnostics.
1787/// \param VD The variable whose initializer should be obtained.
1788/// \param Frame The frame in which the variable was created. Must be null
1789/// if this variable is not local to the evaluation.
1790/// \param Result Filled in with a pointer to the value of the variable.
1791static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1792 const VarDecl *VD, CallStackFrame *Frame,
1793 APValue *&Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001794 // If this is a parameter to an active constexpr function call, perform
1795 // argument substitution.
1796 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001797 // Assume arguments of a potential constant expression are unknown
1798 // constant expressions.
1799 if (Info.CheckingPotentialConstantExpression)
1800 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001801 if (!Frame || !Frame->Arguments) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001802 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001803 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001804 }
Richard Smithb476a142013-05-05 21:17:10 +00001805 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smith177dce72011-11-01 16:57:24 +00001806 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001807 }
Richard Smith03f96112011-10-24 17:54:18 +00001808
Richard Smitha10b9782013-04-22 15:31:51 +00001809 // If this is a local variable, dig out its value.
Richard Smithb476a142013-05-05 21:17:10 +00001810 if (Frame) {
Richard Smith03ce5f82013-07-24 07:11:57 +00001811 Result = Frame->getTemporary(VD);
1812 assert(Result && "missing value for local variable");
1813 return true;
Richard Smitha10b9782013-04-22 15:31:51 +00001814 }
1815
Richard Smith099e7f62011-12-19 06:19:21 +00001816 // Dig out the initializer, and use the declaration which it's attached to.
1817 const Expr *Init = VD->getAnyInitializer(VD);
1818 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001819 // If we're checking a potential constant expression, the variable could be
1820 // initialized later.
1821 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001822 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001823 return false;
1824 }
1825
Richard Smith180f4792011-11-10 06:34:14 +00001826 // If we're currently evaluating the initializer of this declaration, use that
1827 // in-flight value.
Richard Smith6391ea22013-05-09 07:14:00 +00001828 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smithb476a142013-05-05 21:17:10 +00001829 Result = Info.EvaluatingDeclValue;
Richard Smith03ce5f82013-07-24 07:11:57 +00001830 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001831 }
1832
Richard Smith65ac5982011-11-01 21:06:14 +00001833 // Never evaluate the initializer of a weak variable. We can't be sure that
1834 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001835 if (VD->isWeak()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001836 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001837 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001838 }
Richard Smith65ac5982011-11-01 21:06:14 +00001839
Richard Smith099e7f62011-12-19 06:19:21 +00001840 // Check that we can fold the initializer. In C++, we will have already done
1841 // this in the cases where it matters for conformance.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001842 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith099e7f62011-12-19 06:19:21 +00001843 if (!VD->evaluateValue(Notes)) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001844 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001845 Notes.size() + 1) << VD;
1846 Info.Note(VD->getLocation(), diag::note_declared_at);
1847 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001848 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001849 } else if (!VD->checkInitIsICE()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001850 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001851 Notes.size() + 1) << VD;
1852 Info.Note(VD->getLocation(), diag::note_declared_at);
1853 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001854 }
Richard Smith03f96112011-10-24 17:54:18 +00001855
Richard Smithb476a142013-05-05 21:17:10 +00001856 Result = VD->getEvaluatedValue();
Richard Smith47a1eed2011-10-29 20:57:55 +00001857 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001858}
1859
Richard Smithc49bd112011-10-28 17:51:58 +00001860static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001861 Qualifiers Quals = T.getQualifiers();
1862 return Quals.hasConst() && !Quals.hasVolatile();
1863}
1864
Richard Smith59efe262011-11-11 04:05:33 +00001865/// Get the base index of the given base class within an APValue representing
1866/// the given derived class.
1867static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1868 const CXXRecordDecl *Base) {
1869 Base = Base->getCanonicalDecl();
1870 unsigned Index = 0;
1871 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1872 E = Derived->bases_end(); I != E; ++I, ++Index) {
1873 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1874 return Index;
1875 }
1876
1877 llvm_unreachable("base class missing from derived class's bases list");
1878}
1879
Richard Smithbebf5b12013-04-26 14:36:30 +00001880/// Extract the value of a character from a string literal.
1881static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1882 uint64_t Index) {
Richard Smithf3908f22012-02-17 03:35:37 +00001883 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smithbebf5b12013-04-26 14:36:30 +00001884 const StringLiteral *S = cast<StringLiteral>(Lit);
1885 const ConstantArrayType *CAT =
1886 Info.Ctx.getAsConstantArrayType(S->getType());
1887 assert(CAT && "string literal isn't an array");
1888 QualType CharType = CAT->getElementType();
Richard Smithfe587202012-04-15 02:50:59 +00001889 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smithf3908f22012-02-17 03:35:37 +00001890
1891 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smithfe587202012-04-15 02:50:59 +00001892 CharType->isUnsignedIntegerType());
Richard Smithf3908f22012-02-17 03:35:37 +00001893 if (Index < S->getLength())
1894 Value = S->getCodeUnit(Index);
1895 return Value;
1896}
1897
Richard Smithbebf5b12013-04-26 14:36:30 +00001898// Expand a string literal into an array of characters.
1899static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
1900 APValue &Result) {
1901 const StringLiteral *S = cast<StringLiteral>(Lit);
1902 const ConstantArrayType *CAT =
1903 Info.Ctx.getAsConstantArrayType(S->getType());
1904 assert(CAT && "string literal isn't an array");
1905 QualType CharType = CAT->getElementType();
1906 assert(CharType->isIntegerType() && "unexpected character type");
1907
1908 unsigned Elts = CAT->getSize().getZExtValue();
1909 Result = APValue(APValue::UninitArray(),
1910 std::min(S->getLength(), Elts), Elts);
1911 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1912 CharType->isUnsignedIntegerType());
1913 if (Result.hasArrayFiller())
1914 Result.getArrayFiller() = APValue(Value);
1915 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
1916 Value = S->getCodeUnit(I);
1917 Result.getArrayInitializedElt(I) = APValue(Value);
1918 }
1919}
1920
1921// Expand an array so that it has more than Index filled elements.
1922static void expandArray(APValue &Array, unsigned Index) {
1923 unsigned Size = Array.getArraySize();
1924 assert(Index < Size);
1925
1926 // Always at least double the number of elements for which we store a value.
1927 unsigned OldElts = Array.getArrayInitializedElts();
1928 unsigned NewElts = std::max(Index+1, OldElts * 2);
1929 NewElts = std::min(Size, std::max(NewElts, 8u));
1930
1931 // Copy the data across.
1932 APValue NewValue(APValue::UninitArray(), NewElts, Size);
1933 for (unsigned I = 0; I != OldElts; ++I)
1934 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
1935 for (unsigned I = OldElts; I != NewElts; ++I)
1936 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
1937 if (NewValue.hasArrayFiller())
1938 NewValue.getArrayFiller() = Array.getArrayFiller();
1939 Array.swap(NewValue);
1940}
1941
Richard Smitha49a7fe2013-05-07 23:34:45 +00001942/// Kinds of access we can perform on an object, for diagnostics.
Richard Smithbebf5b12013-04-26 14:36:30 +00001943enum AccessKinds {
1944 AK_Read,
Richard Smith5528ac92013-05-05 23:31:59 +00001945 AK_Assign,
1946 AK_Increment,
1947 AK_Decrement
Richard Smithbebf5b12013-04-26 14:36:30 +00001948};
1949
Richard Smithb476a142013-05-05 21:17:10 +00001950/// A handle to a complete object (an object that is not a subobject of
1951/// another object).
1952struct CompleteObject {
1953 /// The value of the complete object.
1954 APValue *Value;
1955 /// The type of the complete object.
1956 QualType Type;
1957
1958 CompleteObject() : Value(0) {}
1959 CompleteObject(APValue *Value, QualType Type)
1960 : Value(Value), Type(Type) {
1961 assert(Value && "missing value for complete object");
1962 }
1963
David Blaikie7247c882013-05-15 07:37:26 +00001964 LLVM_EXPLICIT operator bool() const { return Value; }
Richard Smithb476a142013-05-05 21:17:10 +00001965};
1966
Richard Smithbebf5b12013-04-26 14:36:30 +00001967/// Find the designated sub-object of an rvalue.
1968template<typename SubobjectHandler>
1969typename SubobjectHandler::result_type
Richard Smithb476a142013-05-05 21:17:10 +00001970findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smithbebf5b12013-04-26 14:36:30 +00001971 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001972 if (Sub.Invalid)
1973 // A diagnostic will have already been produced.
Richard Smithbebf5b12013-04-26 14:36:30 +00001974 return handler.failed();
Richard Smithb4e85ed2012-01-06 16:39:00 +00001975 if (Sub.isOnePastTheEnd()) {
Richard Smithbebf5b12013-04-26 14:36:30 +00001976 if (Info.getLangOpts().CPlusPlus11)
1977 Info.Diag(E, diag::note_constexpr_access_past_end)
1978 << handler.AccessKind;
1979 else
1980 Info.Diag(E);
1981 return handler.failed();
Richard Smith7098cbd2011-12-21 05:04:46 +00001982 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001983
Richard Smithb476a142013-05-05 21:17:10 +00001984 APValue *O = Obj.Value;
1985 QualType ObjType = Obj.Type;
Richard Smith3835a4e2013-08-06 07:09:20 +00001986 const FieldDecl *LastField = 0;
1987
Richard Smith180f4792011-11-10 06:34:14 +00001988 // Walk the designator's path to find the subobject.
Richard Smith03ce5f82013-07-24 07:11:57 +00001989 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
1990 if (O->isUninit()) {
1991 if (!Info.CheckingPotentialConstantExpression)
1992 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
1993 return handler.failed();
1994 }
1995
Richard Smith3835a4e2013-08-06 07:09:20 +00001996 if (I == N) {
1997 if (!handler.found(*O, ObjType))
1998 return false;
Richard Smith03ce5f82013-07-24 07:11:57 +00001999
Richard Smith3835a4e2013-08-06 07:09:20 +00002000 // If we modified a bit-field, truncate it to the right width.
2001 if (handler.AccessKind != AK_Read &&
2002 LastField && LastField->isBitField() &&
2003 !truncateBitfieldValue(Info, E, *O, LastField))
2004 return false;
2005
2006 return true;
2007 }
2008
2009 LastField = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00002010 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00002011 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00002012 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00002013 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00002014 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00002015 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00002016 // Note, it should not be possible to form a pointer with a valid
2017 // designator which points more than one past the end of the array.
Richard Smithbebf5b12013-04-26 14:36:30 +00002018 if (Info.getLangOpts().CPlusPlus11)
2019 Info.Diag(E, diag::note_constexpr_access_past_end)
2020 << handler.AccessKind;
2021 else
2022 Info.Diag(E);
2023 return handler.failed();
Richard Smithf48fdb02011-12-09 22:58:01 +00002024 }
Richard Smithbebf5b12013-04-26 14:36:30 +00002025
2026 ObjType = CAT->getElementType();
2027
Richard Smithf3908f22012-02-17 03:35:37 +00002028 // An array object is represented as either an Array APValue or as an
2029 // LValue which refers to a string literal.
2030 if (O->isLValue()) {
2031 assert(I == N - 1 && "extracting subobject of character?");
2032 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smithbebf5b12013-04-26 14:36:30 +00002033 if (handler.AccessKind != AK_Read)
2034 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2035 *O);
2036 else
2037 return handler.foundString(*O, ObjType, Index);
2038 }
2039
2040 if (O->getArrayInitializedElts() > Index)
Richard Smithcc5d4f62011-11-07 09:22:26 +00002041 O = &O->getArrayInitializedElt(Index);
Richard Smithbebf5b12013-04-26 14:36:30 +00002042 else if (handler.AccessKind != AK_Read) {
2043 expandArray(*O, Index);
2044 O = &O->getArrayInitializedElt(Index);
2045 } else
Richard Smithcc5d4f62011-11-07 09:22:26 +00002046 O = &O->getArrayFiller();
Richard Smith86024012012-02-18 22:04:06 +00002047 } else if (ObjType->isAnyComplexType()) {
2048 // Next subobject is a complex number.
2049 uint64_t Index = Sub.Entries[I].ArrayIndex;
2050 if (Index > 1) {
Richard Smithbebf5b12013-04-26 14:36:30 +00002051 if (Info.getLangOpts().CPlusPlus11)
2052 Info.Diag(E, diag::note_constexpr_access_past_end)
2053 << handler.AccessKind;
2054 else
2055 Info.Diag(E);
2056 return handler.failed();
Richard Smith86024012012-02-18 22:04:06 +00002057 }
Richard Smithbebf5b12013-04-26 14:36:30 +00002058
2059 bool WasConstQualified = ObjType.isConstQualified();
2060 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2061 if (WasConstQualified)
2062 ObjType.addConst();
2063
Richard Smith86024012012-02-18 22:04:06 +00002064 assert(I == N - 1 && "extracting subobject of scalar?");
2065 if (O->isComplexInt()) {
Richard Smithbebf5b12013-04-26 14:36:30 +00002066 return handler.found(Index ? O->getComplexIntImag()
2067 : O->getComplexIntReal(), ObjType);
Richard Smith86024012012-02-18 22:04:06 +00002068 } else {
2069 assert(O->isComplexFloat());
Richard Smithbebf5b12013-04-26 14:36:30 +00002070 return handler.found(Index ? O->getComplexFloatImag()
2071 : O->getComplexFloatReal(), ObjType);
Richard Smith86024012012-02-18 22:04:06 +00002072 }
Richard Smith180f4792011-11-10 06:34:14 +00002073 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithbebf5b12013-04-26 14:36:30 +00002074 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002075 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smithb4e5e282012-02-09 03:29:58 +00002076 << Field;
2077 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smithbebf5b12013-04-26 14:36:30 +00002078 return handler.failed();
Richard Smithb4e5e282012-02-09 03:29:58 +00002079 }
2080
Richard Smith180f4792011-11-10 06:34:14 +00002081 // Next subobject is a class, struct or union field.
2082 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2083 if (RD->isUnion()) {
2084 const FieldDecl *UnionField = O->getUnionField();
2085 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00002086 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smithbebf5b12013-04-26 14:36:30 +00002087 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2088 << handler.AccessKind << Field << !UnionField << UnionField;
2089 return handler.failed();
Richard Smithf48fdb02011-12-09 22:58:01 +00002090 }
Richard Smith180f4792011-11-10 06:34:14 +00002091 O = &O->getUnionValue();
2092 } else
2093 O = &O->getStructField(Field->getFieldIndex());
Richard Smithbebf5b12013-04-26 14:36:30 +00002094
2095 bool WasConstQualified = ObjType.isConstQualified();
Richard Smith180f4792011-11-10 06:34:14 +00002096 ObjType = Field->getType();
Richard Smithbebf5b12013-04-26 14:36:30 +00002097 if (WasConstQualified && !Field->isMutable())
2098 ObjType.addConst();
Richard Smith7098cbd2011-12-21 05:04:46 +00002099
2100 if (ObjType.isVolatileQualified()) {
2101 if (Info.getLangOpts().CPlusPlus) {
2102 // FIXME: Include a description of the path to the volatile subobject.
Richard Smithbebf5b12013-04-26 14:36:30 +00002103 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2104 << handler.AccessKind << 2 << Field;
Richard Smith7098cbd2011-12-21 05:04:46 +00002105 Info.Note(Field->getLocation(), diag::note_declared_at);
2106 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002107 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00002108 }
Richard Smithbebf5b12013-04-26 14:36:30 +00002109 return handler.failed();
Richard Smith7098cbd2011-12-21 05:04:46 +00002110 }
Richard Smith3835a4e2013-08-06 07:09:20 +00002111
2112 LastField = Field;
Richard Smithcc5d4f62011-11-07 09:22:26 +00002113 } else {
Richard Smith180f4792011-11-10 06:34:14 +00002114 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00002115 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2116 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2117 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smithbebf5b12013-04-26 14:36:30 +00002118
2119 bool WasConstQualified = ObjType.isConstQualified();
Richard Smith59efe262011-11-11 04:05:33 +00002120 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithbebf5b12013-04-26 14:36:30 +00002121 if (WasConstQualified)
2122 ObjType.addConst();
Richard Smithcc5d4f62011-11-07 09:22:26 +00002123 }
2124 }
Richard Smithbebf5b12013-04-26 14:36:30 +00002125}
2126
Benjamin Kramer888d3452013-04-26 22:01:47 +00002127namespace {
Richard Smithbebf5b12013-04-26 14:36:30 +00002128struct ExtractSubobjectHandler {
2129 EvalInfo &Info;
Richard Smithb476a142013-05-05 21:17:10 +00002130 APValue &Result;
Richard Smithbebf5b12013-04-26 14:36:30 +00002131
2132 static const AccessKinds AccessKind = AK_Read;
2133
2134 typedef bool result_type;
2135 bool failed() { return false; }
2136 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smithb476a142013-05-05 21:17:10 +00002137 Result = Subobj;
Richard Smithbebf5b12013-04-26 14:36:30 +00002138 return true;
2139 }
2140 bool found(APSInt &Value, QualType SubobjType) {
Richard Smithb476a142013-05-05 21:17:10 +00002141 Result = APValue(Value);
Richard Smithbebf5b12013-04-26 14:36:30 +00002142 return true;
2143 }
2144 bool found(APFloat &Value, QualType SubobjType) {
Richard Smithb476a142013-05-05 21:17:10 +00002145 Result = APValue(Value);
Richard Smithbebf5b12013-04-26 14:36:30 +00002146 return true;
2147 }
2148 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smithb476a142013-05-05 21:17:10 +00002149 Result = APValue(extractStringLiteralCharacter(
Richard Smithbebf5b12013-04-26 14:36:30 +00002150 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2151 return true;
2152 }
2153};
Richard Smithb476a142013-05-05 21:17:10 +00002154} // end anonymous namespace
2155
Richard Smithbebf5b12013-04-26 14:36:30 +00002156const AccessKinds ExtractSubobjectHandler::AccessKind;
2157
2158/// Extract the designated sub-object of an rvalue.
2159static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smithb476a142013-05-05 21:17:10 +00002160 const CompleteObject &Obj,
2161 const SubobjectDesignator &Sub,
2162 APValue &Result) {
2163 ExtractSubobjectHandler Handler = { Info, Result };
2164 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithbebf5b12013-04-26 14:36:30 +00002165}
2166
Richard Smithb476a142013-05-05 21:17:10 +00002167namespace {
Richard Smithbebf5b12013-04-26 14:36:30 +00002168struct ModifySubobjectHandler {
2169 EvalInfo &Info;
2170 APValue &NewVal;
2171 const Expr *E;
2172
2173 typedef bool result_type;
2174 static const AccessKinds AccessKind = AK_Assign;
2175
2176 bool checkConst(QualType QT) {
2177 // Assigning to a const object has undefined behavior.
2178 if (QT.isConstQualified()) {
2179 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2180 return false;
2181 }
2182 return true;
2183 }
2184
2185 bool failed() { return false; }
2186 bool found(APValue &Subobj, QualType SubobjType) {
2187 if (!checkConst(SubobjType))
2188 return false;
2189 // We've been given ownership of NewVal, so just swap it in.
2190 Subobj.swap(NewVal);
2191 return true;
2192 }
2193 bool found(APSInt &Value, QualType SubobjType) {
2194 if (!checkConst(SubobjType))
2195 return false;
2196 if (!NewVal.isInt()) {
2197 // Maybe trying to write a cast pointer value into a complex?
2198 Info.Diag(E);
2199 return false;
2200 }
2201 Value = NewVal.getInt();
2202 return true;
2203 }
2204 bool found(APFloat &Value, QualType SubobjType) {
2205 if (!checkConst(SubobjType))
2206 return false;
2207 Value = NewVal.getFloat();
2208 return true;
2209 }
2210 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2211 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2212 }
2213};
Benjamin Kramer888d3452013-04-26 22:01:47 +00002214} // end anonymous namespace
Richard Smithbebf5b12013-04-26 14:36:30 +00002215
Richard Smithb476a142013-05-05 21:17:10 +00002216const AccessKinds ModifySubobjectHandler::AccessKind;
2217
Richard Smithbebf5b12013-04-26 14:36:30 +00002218/// Update the designated sub-object of an rvalue to the given value.
2219static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smithb476a142013-05-05 21:17:10 +00002220 const CompleteObject &Obj,
Richard Smithbebf5b12013-04-26 14:36:30 +00002221 const SubobjectDesignator &Sub,
2222 APValue &NewVal) {
2223 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smithb476a142013-05-05 21:17:10 +00002224 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithcc5d4f62011-11-07 09:22:26 +00002225}
2226
Richard Smithf15fda02012-02-02 01:16:57 +00002227/// Find the position where two subobject designators diverge, or equivalently
2228/// the length of the common initial subsequence.
2229static unsigned FindDesignatorMismatch(QualType ObjType,
2230 const SubobjectDesignator &A,
2231 const SubobjectDesignator &B,
2232 bool &WasArrayIndex) {
2233 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2234 for (/**/; I != N; ++I) {
Richard Smith86024012012-02-18 22:04:06 +00002235 if (!ObjType.isNull() &&
2236 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smithf15fda02012-02-02 01:16:57 +00002237 // Next subobject is an array element.
2238 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2239 WasArrayIndex = true;
2240 return I;
2241 }
Richard Smith86024012012-02-18 22:04:06 +00002242 if (ObjType->isAnyComplexType())
2243 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2244 else
2245 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smithf15fda02012-02-02 01:16:57 +00002246 } else {
2247 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2248 WasArrayIndex = false;
2249 return I;
2250 }
2251 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2252 // Next subobject is a field.
2253 ObjType = FD->getType();
2254 else
2255 // Next subobject is a base class.
2256 ObjType = QualType();
2257 }
2258 }
2259 WasArrayIndex = false;
2260 return I;
2261}
2262
2263/// Determine whether the given subobject designators refer to elements of the
2264/// same array object.
2265static bool AreElementsOfSameArray(QualType ObjType,
2266 const SubobjectDesignator &A,
2267 const SubobjectDesignator &B) {
2268 if (A.Entries.size() != B.Entries.size())
2269 return false;
2270
2271 bool IsArray = A.MostDerivedArraySize != 0;
2272 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2273 // A is a subobject of the array element.
2274 return false;
2275
2276 // If A (and B) designates an array element, the last entry will be the array
2277 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2278 // of length 1' case, and the entire path must match.
2279 bool WasArrayIndex;
2280 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2281 return CommonLength >= A.Entries.size() - IsArray;
2282}
2283
Richard Smithb476a142013-05-05 21:17:10 +00002284/// Find the complete object to which an LValue refers.
2285CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
2286 const LValue &LVal, QualType LValType) {
2287 if (!LVal.Base) {
2288 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2289 return CompleteObject();
2290 }
2291
2292 CallStackFrame *Frame = 0;
2293 if (LVal.CallIndex) {
2294 Frame = Info.getCallFrame(LVal.CallIndex);
2295 if (!Frame) {
2296 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2297 << AK << LVal.Base.is<const ValueDecl*>();
2298 NoteLValueLocation(Info, LVal.Base);
2299 return CompleteObject();
2300 }
Richard Smithb476a142013-05-05 21:17:10 +00002301 }
2302
2303 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2304 // is not a constant expression (even if the object is non-volatile). We also
2305 // apply this rule to C++98, in order to conform to the expected 'volatile'
2306 // semantics.
2307 if (LValType.isVolatileQualified()) {
2308 if (Info.getLangOpts().CPlusPlus)
2309 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2310 << AK << LValType;
2311 else
2312 Info.Diag(E);
2313 return CompleteObject();
2314 }
2315
2316 // Compute value storage location and type of base object.
2317 APValue *BaseVal = 0;
Richard Smith8a66bf72013-06-03 05:03:02 +00002318 QualType BaseType = getType(LVal.Base);
Richard Smithb476a142013-05-05 21:17:10 +00002319
2320 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2321 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2322 // In C++11, constexpr, non-volatile variables initialized with constant
2323 // expressions are constant expressions too. Inside constexpr functions,
2324 // parameters are constant expressions even if they're non-const.
2325 // In C++1y, objects local to a constant expression (those with a Frame) are
2326 // both readable and writable inside constant expressions.
2327 // In C, such things can also be folded, although they are not ICEs.
2328 const VarDecl *VD = dyn_cast<VarDecl>(D);
2329 if (VD) {
2330 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2331 VD = VDef;
2332 }
2333 if (!VD || VD->isInvalidDecl()) {
2334 Info.Diag(E);
2335 return CompleteObject();
2336 }
2337
2338 // Accesses of volatile-qualified objects are not allowed.
Richard Smithb476a142013-05-05 21:17:10 +00002339 if (BaseType.isVolatileQualified()) {
2340 if (Info.getLangOpts().CPlusPlus) {
2341 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2342 << AK << 1 << VD;
2343 Info.Note(VD->getLocation(), diag::note_declared_at);
2344 } else {
2345 Info.Diag(E);
2346 }
2347 return CompleteObject();
2348 }
2349
2350 // Unless we're looking at a local variable or argument in a constexpr call,
2351 // the variable we're reading must be const.
2352 if (!Frame) {
Richard Smith6391ea22013-05-09 07:14:00 +00002353 if (Info.getLangOpts().CPlusPlus1y &&
2354 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2355 // OK, we can read and modify an object if we're in the process of
2356 // evaluating its initializer, because its lifetime began in this
2357 // evaluation.
2358 } else if (AK != AK_Read) {
2359 // All the remaining cases only permit reading.
2360 Info.Diag(E, diag::note_constexpr_modify_global);
2361 return CompleteObject();
2362 } else if (VD->isConstexpr()) {
Richard Smithb476a142013-05-05 21:17:10 +00002363 // OK, we can read this variable.
2364 } else if (BaseType->isIntegralOrEnumerationType()) {
2365 if (!BaseType.isConstQualified()) {
2366 if (Info.getLangOpts().CPlusPlus) {
2367 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2368 Info.Note(VD->getLocation(), diag::note_declared_at);
2369 } else {
2370 Info.Diag(E);
2371 }
2372 return CompleteObject();
2373 }
2374 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2375 // We support folding of const floating-point types, in order to make
2376 // static const data members of such types (supported as an extension)
2377 // more useful.
2378 if (Info.getLangOpts().CPlusPlus11) {
2379 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2380 Info.Note(VD->getLocation(), diag::note_declared_at);
2381 } else {
2382 Info.CCEDiag(E);
2383 }
2384 } else {
2385 // FIXME: Allow folding of values of any literal type in all languages.
2386 if (Info.getLangOpts().CPlusPlus11) {
2387 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2388 Info.Note(VD->getLocation(), diag::note_declared_at);
2389 } else {
2390 Info.Diag(E);
2391 }
2392 return CompleteObject();
2393 }
2394 }
2395
2396 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2397 return CompleteObject();
2398 } else {
2399 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2400
2401 if (!Frame) {
Richard Smith211c8dd2013-06-05 00:46:14 +00002402 if (const MaterializeTemporaryExpr *MTE =
2403 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2404 assert(MTE->getStorageDuration() == SD_Static &&
2405 "should have a frame for a non-global materialized temporary");
Richard Smithb476a142013-05-05 21:17:10 +00002406
Richard Smith211c8dd2013-06-05 00:46:14 +00002407 // Per C++1y [expr.const]p2:
2408 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2409 // - a [...] glvalue of integral or enumeration type that refers to
2410 // a non-volatile const object [...]
2411 // [...]
2412 // - a [...] glvalue of literal type that refers to a non-volatile
2413 // object whose lifetime began within the evaluation of e.
2414 //
2415 // C++11 misses the 'began within the evaluation of e' check and
2416 // instead allows all temporaries, including things like:
2417 // int &&r = 1;
2418 // int x = ++r;
2419 // constexpr int k = r;
2420 // Therefore we use the C++1y rules in C++11 too.
2421 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2422 const ValueDecl *ED = MTE->getExtendingDecl();
2423 if (!(BaseType.isConstQualified() &&
2424 BaseType->isIntegralOrEnumerationType()) &&
2425 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2426 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2427 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2428 return CompleteObject();
2429 }
2430
2431 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2432 assert(BaseVal && "got reference to unevaluated temporary");
2433 } else {
2434 Info.Diag(E);
2435 return CompleteObject();
2436 }
2437 } else {
Richard Smith03ce5f82013-07-24 07:11:57 +00002438 BaseVal = Frame->getTemporary(Base);
2439 assert(BaseVal && "missing value for temporary");
Richard Smith211c8dd2013-06-05 00:46:14 +00002440 }
Richard Smithb476a142013-05-05 21:17:10 +00002441
2442 // Volatile temporary objects cannot be accessed in constant expressions.
2443 if (BaseType.isVolatileQualified()) {
2444 if (Info.getLangOpts().CPlusPlus) {
2445 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2446 << AK << 0;
2447 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2448 } else {
2449 Info.Diag(E);
2450 }
2451 return CompleteObject();
2452 }
2453 }
2454
Richard Smith6391ea22013-05-09 07:14:00 +00002455 // During the construction of an object, it is not yet 'const'.
2456 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2457 // and this doesn't do quite the right thing for const subobjects of the
2458 // object under construction.
2459 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2460 BaseType = Info.Ctx.getCanonicalType(BaseType);
2461 BaseType.removeLocalConst();
2462 }
2463
Richard Smithb476a142013-05-05 21:17:10 +00002464 // In C++1y, we can't safely access any mutable state when checking a
2465 // potential constant expression.
2466 if (Frame && Info.getLangOpts().CPlusPlus1y &&
2467 Info.CheckingPotentialConstantExpression)
2468 return CompleteObject();
2469
2470 return CompleteObject(BaseVal, BaseType);
2471}
2472
Richard Smith5528ac92013-05-05 23:31:59 +00002473/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2474/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2475/// glvalue referred to by an entity of reference type.
Richard Smith180f4792011-11-10 06:34:14 +00002476///
2477/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00002478/// \param Conv - The expression for which we are performing the conversion.
2479/// Used for diagnostics.
Richard Smithbebf5b12013-04-26 14:36:30 +00002480/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2481/// case of a non-class type).
Richard Smith180f4792011-11-10 06:34:14 +00002482/// \param LVal - The glvalue on which we are attempting to perform this action.
2483/// \param RVal - The produced value will be placed here.
Richard Smith5528ac92013-05-05 23:31:59 +00002484static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf48fdb02011-12-09 22:58:01 +00002485 QualType Type,
Richard Smith1aa0be82012-03-03 22:46:17 +00002486 const LValue &LVal, APValue &RVal) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002487 if (LVal.Designator.Invalid)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002488 return false;
2489
Richard Smithb476a142013-05-05 21:17:10 +00002490 // Check for special cases where there is no existing APValue to look at.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002491 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithb476a142013-05-05 21:17:10 +00002492 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2493 !Type.isVolatileQualified()) {
2494 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2495 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2496 // initializer until now for such expressions. Such an expression can't be
2497 // an ICE in C, so this only matters for fold.
2498 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2499 if (Type.isVolatileQualified()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002500 Info.Diag(Conv);
Richard Smith0a3bdb62011-11-04 02:25:55 +00002501 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002502 }
Richard Smithb476a142013-05-05 21:17:10 +00002503 APValue Lit;
2504 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2505 return false;
2506 CompleteObject LitObj(&Lit, Base->getType());
2507 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2508 } else if (isa<StringLiteral>(Base)) {
2509 // We represent a string literal array as an lvalue pointing at the
2510 // corresponding expression, rather than building an array of chars.
2511 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2512 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2513 CompleteObject StrObj(&Str, Base->getType());
2514 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith0a3bdb62011-11-04 02:25:55 +00002515 }
Richard Smithc49bd112011-10-28 17:51:58 +00002516 }
2517
Richard Smithb476a142013-05-05 21:17:10 +00002518 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2519 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smithbebf5b12013-04-26 14:36:30 +00002520}
2521
2522/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith5528ac92013-05-05 23:31:59 +00002523static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smithbebf5b12013-04-26 14:36:30 +00002524 QualType LValType, APValue &Val) {
Richard Smithbebf5b12013-04-26 14:36:30 +00002525 if (LVal.Designator.Invalid)
Richard Smithbebf5b12013-04-26 14:36:30 +00002526 return false;
2527
Richard Smithb476a142013-05-05 21:17:10 +00002528 if (!Info.getLangOpts().CPlusPlus1y) {
2529 Info.Diag(E);
Richard Smithbebf5b12013-04-26 14:36:30 +00002530 return false;
2531 }
2532
Richard Smithb476a142013-05-05 21:17:10 +00002533 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2534 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smithc49bd112011-10-28 17:51:58 +00002535}
2536
Richard Smith5528ac92013-05-05 23:31:59 +00002537static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2538 return T->isSignedIntegerType() &&
2539 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2540}
2541
2542namespace {
Richard Smithd20afcb2013-05-07 04:50:00 +00002543struct CompoundAssignSubobjectHandler {
2544 EvalInfo &Info;
2545 const Expr *E;
2546 QualType PromotedLHSType;
2547 BinaryOperatorKind Opcode;
2548 const APValue &RHS;
2549
2550 static const AccessKinds AccessKind = AK_Assign;
2551
2552 typedef bool result_type;
2553
2554 bool checkConst(QualType QT) {
2555 // Assigning to a const object has undefined behavior.
2556 if (QT.isConstQualified()) {
2557 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2558 return false;
2559 }
2560 return true;
2561 }
2562
2563 bool failed() { return false; }
2564 bool found(APValue &Subobj, QualType SubobjType) {
2565 switch (Subobj.getKind()) {
2566 case APValue::Int:
2567 return found(Subobj.getInt(), SubobjType);
2568 case APValue::Float:
2569 return found(Subobj.getFloat(), SubobjType);
2570 case APValue::ComplexInt:
2571 case APValue::ComplexFloat:
2572 // FIXME: Implement complex compound assignment.
2573 Info.Diag(E);
2574 return false;
2575 case APValue::LValue:
2576 return foundPointer(Subobj, SubobjType);
2577 default:
2578 // FIXME: can this happen?
2579 Info.Diag(E);
2580 return false;
2581 }
2582 }
2583 bool found(APSInt &Value, QualType SubobjType) {
2584 if (!checkConst(SubobjType))
2585 return false;
2586
2587 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2588 // We don't support compound assignment on integer-cast-to-pointer
2589 // values.
2590 Info.Diag(E);
2591 return false;
2592 }
2593
2594 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2595 SubobjType, Value);
2596 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2597 return false;
2598 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2599 return true;
2600 }
2601 bool found(APFloat &Value, QualType SubobjType) {
Richard Smitha49a7fe2013-05-07 23:34:45 +00002602 return checkConst(SubobjType) &&
2603 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2604 Value) &&
2605 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2606 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smithd20afcb2013-05-07 04:50:00 +00002607 }
2608 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2609 if (!checkConst(SubobjType))
2610 return false;
2611
2612 QualType PointeeType;
2613 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2614 PointeeType = PT->getPointeeType();
Richard Smitha49a7fe2013-05-07 23:34:45 +00002615
2616 if (PointeeType.isNull() || !RHS.isInt() ||
2617 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smithd20afcb2013-05-07 04:50:00 +00002618 Info.Diag(E);
2619 return false;
2620 }
2621
Richard Smitha49a7fe2013-05-07 23:34:45 +00002622 int64_t Offset = getExtValue(RHS.getInt());
2623 if (Opcode == BO_Sub)
2624 Offset = -Offset;
2625
2626 LValue LVal;
2627 LVal.setFrom(Info.Ctx, Subobj);
2628 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2629 return false;
2630 LVal.moveInto(Subobj);
2631 return true;
Richard Smithd20afcb2013-05-07 04:50:00 +00002632 }
2633 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2634 llvm_unreachable("shouldn't encounter string elements here");
2635 }
2636};
2637} // end anonymous namespace
2638
2639const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2640
2641/// Perform a compound assignment of LVal <op>= RVal.
2642static bool handleCompoundAssignment(
2643 EvalInfo &Info, const Expr *E,
2644 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2645 BinaryOperatorKind Opcode, const APValue &RVal) {
2646 if (LVal.Designator.Invalid)
2647 return false;
2648
2649 if (!Info.getLangOpts().CPlusPlus1y) {
2650 Info.Diag(E);
2651 return false;
2652 }
2653
2654 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2655 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2656 RVal };
2657 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2658}
2659
2660namespace {
Richard Smith5528ac92013-05-05 23:31:59 +00002661struct IncDecSubobjectHandler {
2662 EvalInfo &Info;
2663 const Expr *E;
2664 AccessKinds AccessKind;
2665 APValue *Old;
2666
2667 typedef bool result_type;
2668
2669 bool checkConst(QualType QT) {
2670 // Assigning to a const object has undefined behavior.
2671 if (QT.isConstQualified()) {
2672 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2673 return false;
2674 }
2675 return true;
2676 }
2677
2678 bool failed() { return false; }
2679 bool found(APValue &Subobj, QualType SubobjType) {
2680 // Stash the old value. Also clear Old, so we don't clobber it later
2681 // if we're post-incrementing a complex.
2682 if (Old) {
2683 *Old = Subobj;
2684 Old = 0;
2685 }
2686
2687 switch (Subobj.getKind()) {
2688 case APValue::Int:
2689 return found(Subobj.getInt(), SubobjType);
2690 case APValue::Float:
2691 return found(Subobj.getFloat(), SubobjType);
2692 case APValue::ComplexInt:
2693 return found(Subobj.getComplexIntReal(),
2694 SubobjType->castAs<ComplexType>()->getElementType()
2695 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2696 case APValue::ComplexFloat:
2697 return found(Subobj.getComplexFloatReal(),
2698 SubobjType->castAs<ComplexType>()->getElementType()
2699 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2700 case APValue::LValue:
2701 return foundPointer(Subobj, SubobjType);
2702 default:
2703 // FIXME: can this happen?
2704 Info.Diag(E);
2705 return false;
2706 }
2707 }
2708 bool found(APSInt &Value, QualType SubobjType) {
2709 if (!checkConst(SubobjType))
2710 return false;
2711
2712 if (!SubobjType->isIntegerType()) {
2713 // We don't support increment / decrement on integer-cast-to-pointer
2714 // values.
2715 Info.Diag(E);
2716 return false;
2717 }
2718
2719 if (Old) *Old = APValue(Value);
2720
2721 // bool arithmetic promotes to int, and the conversion back to bool
2722 // doesn't reduce mod 2^n, so special-case it.
2723 if (SubobjType->isBooleanType()) {
2724 if (AccessKind == AK_Increment)
2725 Value = 1;
2726 else
2727 Value = !Value;
2728 return true;
2729 }
2730
2731 bool WasNegative = Value.isNegative();
2732 if (AccessKind == AK_Increment) {
2733 ++Value;
2734
2735 if (!WasNegative && Value.isNegative() &&
2736 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2737 APSInt ActualValue(Value, /*IsUnsigned*/true);
2738 HandleOverflow(Info, E, ActualValue, SubobjType);
2739 }
2740 } else {
2741 --Value;
2742
2743 if (WasNegative && !Value.isNegative() &&
2744 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2745 unsigned BitWidth = Value.getBitWidth();
2746 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2747 ActualValue.setBit(BitWidth);
2748 HandleOverflow(Info, E, ActualValue, SubobjType);
2749 }
2750 }
2751 return true;
2752 }
2753 bool found(APFloat &Value, QualType SubobjType) {
2754 if (!checkConst(SubobjType))
2755 return false;
2756
2757 if (Old) *Old = APValue(Value);
2758
2759 APFloat One(Value.getSemantics(), 1);
2760 if (AccessKind == AK_Increment)
2761 Value.add(One, APFloat::rmNearestTiesToEven);
2762 else
2763 Value.subtract(One, APFloat::rmNearestTiesToEven);
2764 return true;
2765 }
2766 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2767 if (!checkConst(SubobjType))
2768 return false;
2769
2770 QualType PointeeType;
2771 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2772 PointeeType = PT->getPointeeType();
2773 else {
2774 Info.Diag(E);
2775 return false;
2776 }
2777
2778 LValue LVal;
2779 LVal.setFrom(Info.Ctx, Subobj);
2780 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2781 AccessKind == AK_Increment ? 1 : -1))
2782 return false;
2783 LVal.moveInto(Subobj);
2784 return true;
2785 }
2786 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2787 llvm_unreachable("shouldn't encounter string elements here");
2788 }
2789};
2790} // end anonymous namespace
2791
2792/// Perform an increment or decrement on LVal.
2793static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
2794 QualType LValType, bool IsIncrement, APValue *Old) {
2795 if (LVal.Designator.Invalid)
2796 return false;
2797
2798 if (!Info.getLangOpts().CPlusPlus1y) {
2799 Info.Diag(E);
2800 return false;
2801 }
2802
2803 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
2804 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
2805 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
2806 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2807}
2808
Richard Smith59efe262011-11-11 04:05:33 +00002809/// Build an lvalue for the object argument of a member function call.
2810static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2811 LValue &This) {
2812 if (Object->getType()->isPointerType())
2813 return EvaluatePointer(Object, This, Info);
2814
2815 if (Object->isGLValue())
2816 return EvaluateLValue(Object, This, Info);
2817
Richard Smitha10b9782013-04-22 15:31:51 +00002818 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002819 return EvaluateTemporary(Object, This, Info);
2820
2821 return false;
2822}
2823
2824/// HandleMemberPointerAccess - Evaluate a member access operation and build an
2825/// lvalue referring to the result.
2826///
2827/// \param Info - Information about the ongoing evaluation.
Richard Smith8a66bf72013-06-03 05:03:02 +00002828/// \param LV - An lvalue referring to the base of the member pointer.
2829/// \param RHS - The member pointer expression.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002830/// \param IncludeMember - Specifies whether the member itself is included in
2831/// the resulting LValue subobject designator. This is not possible when
2832/// creating a bound member function.
2833/// \return The field or method declaration to which the member pointer refers,
2834/// or 0 if evaluation fails.
2835static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith8a66bf72013-06-03 05:03:02 +00002836 QualType LVType,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002837 LValue &LV,
Richard Smith8a66bf72013-06-03 05:03:02 +00002838 const Expr *RHS,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002839 bool IncludeMember = true) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002840 MemberPtr MemPtr;
Richard Smith8a66bf72013-06-03 05:03:02 +00002841 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002842 return 0;
2843
2844 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2845 // member value, the behavior is undefined.
Richard Smith8a66bf72013-06-03 05:03:02 +00002846 if (!MemPtr.getDecl()) {
2847 // FIXME: Specific diagnostic.
2848 Info.Diag(RHS);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002849 return 0;
Richard Smith8a66bf72013-06-03 05:03:02 +00002850 }
Richard Smith745f5142012-01-27 01:14:48 +00002851
Richard Smithe24f5fc2011-11-17 22:56:20 +00002852 if (MemPtr.isDerivedMember()) {
2853 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002854 // The end of the derived-to-base path for the base object must match the
2855 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002856 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith8a66bf72013-06-03 05:03:02 +00002857 LV.Designator.Entries.size()) {
2858 Info.Diag(RHS);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002859 return 0;
Richard Smith8a66bf72013-06-03 05:03:02 +00002860 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002861 unsigned PathLengthToMember =
2862 LV.Designator.Entries.size() - MemPtr.Path.size();
2863 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
2864 const CXXRecordDecl *LVDecl = getAsBaseClass(
2865 LV.Designator.Entries[PathLengthToMember + I]);
2866 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith8a66bf72013-06-03 05:03:02 +00002867 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
2868 Info.Diag(RHS);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002869 return 0;
Richard Smith8a66bf72013-06-03 05:03:02 +00002870 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002871 }
2872
2873 // Truncate the lvalue to the appropriate derived class.
Richard Smith8a66bf72013-06-03 05:03:02 +00002874 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00002875 PathLengthToMember))
2876 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002877 } else if (!MemPtr.Path.empty()) {
2878 // Extend the LValue path with the member pointer's path.
2879 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
2880 MemPtr.Path.size() + IncludeMember);
2881
2882 // Walk down to the appropriate base class.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002883 if (const PointerType *PT = LVType->getAs<PointerType>())
2884 LVType = PT->getPointeeType();
2885 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
2886 assert(RD && "member pointer access on non-class-type expression");
2887 // The first class in the path is that of the lvalue.
2888 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
2889 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith8a66bf72013-06-03 05:03:02 +00002890 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
John McCall8d59dee2012-05-01 00:38:49 +00002891 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002892 RD = Base;
2893 }
2894 // Finally cast to the class containing the member.
Richard Smith8a66bf72013-06-03 05:03:02 +00002895 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
2896 MemPtr.getContainingRecord()))
John McCall8d59dee2012-05-01 00:38:49 +00002897 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002898 }
2899
2900 // Add the member. Note that we cannot build bound member functions here.
2901 if (IncludeMember) {
John McCall8d59dee2012-05-01 00:38:49 +00002902 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith8a66bf72013-06-03 05:03:02 +00002903 if (!HandleLValueMember(Info, RHS, LV, FD))
John McCall8d59dee2012-05-01 00:38:49 +00002904 return 0;
2905 } else if (const IndirectFieldDecl *IFD =
2906 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith8a66bf72013-06-03 05:03:02 +00002907 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
John McCall8d59dee2012-05-01 00:38:49 +00002908 return 0;
2909 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002910 llvm_unreachable("can't construct reference to bound member function");
John McCall8d59dee2012-05-01 00:38:49 +00002911 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002912 }
2913
2914 return MemPtr.getDecl();
2915}
2916
Richard Smith8a66bf72013-06-03 05:03:02 +00002917static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
2918 const BinaryOperator *BO,
2919 LValue &LV,
2920 bool IncludeMember = true) {
2921 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
2922
2923 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
2924 if (Info.keepEvaluatingAfterFailure()) {
2925 MemberPtr MemPtr;
2926 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
2927 }
2928 return 0;
2929 }
2930
2931 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
2932 BO->getRHS(), IncludeMember);
2933}
2934
Richard Smithe24f5fc2011-11-17 22:56:20 +00002935/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
2936/// the provided lvalue, which currently refers to the base object.
2937static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
2938 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002939 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002940 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002941 return false;
2942
Richard Smithb4e85ed2012-01-06 16:39:00 +00002943 QualType TargetQT = E->getType();
2944 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2945 TargetQT = PT->getPointeeType();
2946
2947 // Check this cast lands within the final derived-to-base subobject path.
2948 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002949 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002950 << D.MostDerivedType << TargetQT;
2951 return false;
2952 }
2953
Richard Smithe24f5fc2011-11-17 22:56:20 +00002954 // Check the type of the final cast. We don't need to check the path,
2955 // since a cast can only be formed if the path is unique.
2956 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002957 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2958 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002959 if (NewEntriesSize == D.MostDerivedPathLength)
2960 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2961 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00002962 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00002963 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002964 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002965 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002966 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002967 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002968
2969 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002970 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00002971}
2972
Mike Stumpc4c90452009-10-27 22:09:17 +00002973namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00002974enum EvalStmtResult {
2975 /// Evaluation failed.
2976 ESR_Failed,
2977 /// Hit a 'return' statement.
2978 ESR_Returned,
2979 /// Evaluation succeeded.
Richard Smithce617152013-05-06 05:56:11 +00002980 ESR_Succeeded,
2981 /// Hit a 'continue' statement.
2982 ESR_Continue,
2983 /// Hit a 'break' statement.
Richard Smith284b3cb2013-05-12 17:32:42 +00002984 ESR_Break,
2985 /// Still scanning for 'case' or 'default' statement.
2986 ESR_CaseNotFound
Richard Smithd0dccea2011-10-28 22:34:42 +00002987};
2988}
2989
Richard Smitha10b9782013-04-22 15:31:51 +00002990static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
2991 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2992 // We don't need to evaluate the initializer for a static local.
2993 if (!VD->hasLocalStorage())
2994 return true;
2995
2996 LValue Result;
2997 Result.set(VD, Info.CurrentCall->Index);
Richard Smith03ce5f82013-07-24 07:11:57 +00002998 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smitha10b9782013-04-22 15:31:51 +00002999
Richard Smith37a84f62013-06-20 03:00:05 +00003000 if (!VD->getInit()) {
3001 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3002 << false << VD->getType();
3003 Val = APValue();
3004 return false;
3005 }
3006
Richard Smitha10b9782013-04-22 15:31:51 +00003007 if (!EvaluateInPlace(Val, Info, Result, VD->getInit())) {
3008 // Wipe out any partially-computed value, to allow tracking that this
3009 // evaluation failed.
3010 Val = APValue();
3011 return false;
3012 }
3013 }
3014
3015 return true;
3016}
3017
Richard Smithce617152013-05-06 05:56:11 +00003018/// Evaluate a condition (either a variable declaration or an expression).
3019static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3020 const Expr *Cond, bool &Result) {
Richard Smith03ce5f82013-07-24 07:11:57 +00003021 FullExpressionRAII Scope(Info);
Richard Smithce617152013-05-06 05:56:11 +00003022 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3023 return false;
3024 return EvaluateAsBooleanCondition(Cond, Result, Info);
3025}
3026
3027static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith284b3cb2013-05-12 17:32:42 +00003028 const Stmt *S, const SwitchCase *SC = 0);
Richard Smithce617152013-05-06 05:56:11 +00003029
3030/// Evaluate the body of a loop, and translate the result as appropriate.
3031static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
Richard Smith284b3cb2013-05-12 17:32:42 +00003032 const Stmt *Body,
3033 const SwitchCase *Case = 0) {
Richard Smith03ce5f82013-07-24 07:11:57 +00003034 BlockScopeRAII Scope(Info);
Richard Smith284b3cb2013-05-12 17:32:42 +00003035 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smithce617152013-05-06 05:56:11 +00003036 case ESR_Break:
3037 return ESR_Succeeded;
3038 case ESR_Succeeded:
3039 case ESR_Continue:
3040 return ESR_Continue;
3041 case ESR_Failed:
3042 case ESR_Returned:
Richard Smith284b3cb2013-05-12 17:32:42 +00003043 case ESR_CaseNotFound:
Richard Smithce617152013-05-06 05:56:11 +00003044 return ESR;
3045 }
Hans Wennborgdbce2c62013-05-06 15:13:34 +00003046 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smithce617152013-05-06 05:56:11 +00003047}
3048
Richard Smith284b3cb2013-05-12 17:32:42 +00003049/// Evaluate a switch statement.
3050static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
3051 const SwitchStmt *SS) {
Richard Smith03ce5f82013-07-24 07:11:57 +00003052 BlockScopeRAII Scope(Info);
3053
Richard Smith284b3cb2013-05-12 17:32:42 +00003054 // Evaluate the switch condition.
Richard Smith284b3cb2013-05-12 17:32:42 +00003055 APSInt Value;
Richard Smith03ce5f82013-07-24 07:11:57 +00003056 {
3057 FullExpressionRAII Scope(Info);
3058 if (SS->getConditionVariable() &&
3059 !EvaluateDecl(Info, SS->getConditionVariable()))
3060 return ESR_Failed;
3061 if (!EvaluateInteger(SS->getCond(), Value, Info))
3062 return ESR_Failed;
3063 }
Richard Smith284b3cb2013-05-12 17:32:42 +00003064
3065 // Find the switch case corresponding to the value of the condition.
3066 // FIXME: Cache this lookup.
3067 const SwitchCase *Found = 0;
3068 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3069 SC = SC->getNextSwitchCase()) {
3070 if (isa<DefaultStmt>(SC)) {
3071 Found = SC;
3072 continue;
3073 }
3074
3075 const CaseStmt *CS = cast<CaseStmt>(SC);
3076 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3077 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3078 : LHS;
3079 if (LHS <= Value && Value <= RHS) {
3080 Found = SC;
3081 break;
3082 }
3083 }
3084
3085 if (!Found)
3086 return ESR_Succeeded;
3087
3088 // Search the switch body for the switch case and evaluate it from there.
3089 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3090 case ESR_Break:
3091 return ESR_Succeeded;
3092 case ESR_Succeeded:
3093 case ESR_Continue:
3094 case ESR_Failed:
3095 case ESR_Returned:
3096 return ESR;
3097 case ESR_CaseNotFound:
Richard Smith37a84f62013-06-20 03:00:05 +00003098 // This can only happen if the switch case is nested within a statement
3099 // expression. We have no intention of supporting that.
3100 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3101 return ESR_Failed;
Richard Smith284b3cb2013-05-12 17:32:42 +00003102 }
Richard Smith1071b9f2013-05-13 20:33:30 +00003103 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith284b3cb2013-05-12 17:32:42 +00003104}
3105
Richard Smithd0dccea2011-10-28 22:34:42 +00003106// Evaluate a statement.
Richard Smith1aa0be82012-03-03 22:46:17 +00003107static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith284b3cb2013-05-12 17:32:42 +00003108 const Stmt *S, const SwitchCase *Case) {
Richard Smithe7565632013-05-08 02:12:03 +00003109 if (!Info.nextStep(S))
3110 return ESR_Failed;
3111
Richard Smith284b3cb2013-05-12 17:32:42 +00003112 // If we're hunting down a 'case' or 'default' label, recurse through
3113 // substatements until we hit the label.
3114 if (Case) {
3115 // FIXME: We don't start the lifetime of objects whose initialization we
3116 // jump over. However, such objects must be of class type with a trivial
3117 // default constructor that initialize all subobjects, so must be empty,
3118 // so this almost never matters.
3119 switch (S->getStmtClass()) {
3120 case Stmt::CompoundStmtClass:
3121 // FIXME: Precompute which substatement of a compound statement we
3122 // would jump to, and go straight there rather than performing a
3123 // linear scan each time.
3124 case Stmt::LabelStmtClass:
3125 case Stmt::AttributedStmtClass:
3126 case Stmt::DoStmtClass:
3127 break;
3128
3129 case Stmt::CaseStmtClass:
3130 case Stmt::DefaultStmtClass:
3131 if (Case == S)
3132 Case = 0;
3133 break;
3134
3135 case Stmt::IfStmtClass: {
3136 // FIXME: Precompute which side of an 'if' we would jump to, and go
3137 // straight there rather than scanning both sides.
3138 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith03ce5f82013-07-24 07:11:57 +00003139
3140 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3141 // preceded by our switch label.
3142 BlockScopeRAII Scope(Info);
3143
Richard Smith284b3cb2013-05-12 17:32:42 +00003144 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3145 if (ESR != ESR_CaseNotFound || !IS->getElse())
3146 return ESR;
3147 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3148 }
3149
3150 case Stmt::WhileStmtClass: {
3151 EvalStmtResult ESR =
3152 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3153 if (ESR != ESR_Continue)
3154 return ESR;
3155 break;
3156 }
3157
3158 case Stmt::ForStmtClass: {
3159 const ForStmt *FS = cast<ForStmt>(S);
3160 EvalStmtResult ESR =
3161 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3162 if (ESR != ESR_Continue)
3163 return ESR;
Richard Smith03ce5f82013-07-24 07:11:57 +00003164 if (FS->getInc()) {
3165 FullExpressionRAII IncScope(Info);
3166 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3167 return ESR_Failed;
3168 }
Richard Smith284b3cb2013-05-12 17:32:42 +00003169 break;
3170 }
3171
3172 case Stmt::DeclStmtClass:
3173 // FIXME: If the variable has initialization that can't be jumped over,
3174 // bail out of any immediately-surrounding compound-statement too.
3175 default:
3176 return ESR_CaseNotFound;
3177 }
3178 }
3179
Richard Smithd0dccea2011-10-28 22:34:42 +00003180 switch (S->getStmtClass()) {
3181 default:
Richard Smitha10b9782013-04-22 15:31:51 +00003182 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smitha10b9782013-04-22 15:31:51 +00003183 // Don't bother evaluating beyond an expression-statement which couldn't
3184 // be evaluated.
Richard Smith03ce5f82013-07-24 07:11:57 +00003185 FullExpressionRAII Scope(Info);
Richard Smithce617152013-05-06 05:56:11 +00003186 if (!EvaluateIgnoredValue(Info, E))
Richard Smitha10b9782013-04-22 15:31:51 +00003187 return ESR_Failed;
3188 return ESR_Succeeded;
3189 }
3190
3191 Info.Diag(S->getLocStart());
Richard Smithd0dccea2011-10-28 22:34:42 +00003192 return ESR_Failed;
3193
3194 case Stmt::NullStmtClass:
Richard Smithd0dccea2011-10-28 22:34:42 +00003195 return ESR_Succeeded;
3196
Richard Smitha10b9782013-04-22 15:31:51 +00003197 case Stmt::DeclStmtClass: {
3198 const DeclStmt *DS = cast<DeclStmt>(S);
3199 for (DeclStmt::const_decl_iterator DclIt = DS->decl_begin(),
Richard Smith03ce5f82013-07-24 07:11:57 +00003200 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
3201 // Each declaration initialization is its own full-expression.
3202 // FIXME: This isn't quite right; if we're performing aggregate
3203 // initialization, each braced subexpression is its own full-expression.
3204 FullExpressionRAII Scope(Info);
Richard Smitha10b9782013-04-22 15:31:51 +00003205 if (!EvaluateDecl(Info, *DclIt) && !Info.keepEvaluatingAfterFailure())
3206 return ESR_Failed;
Richard Smith03ce5f82013-07-24 07:11:57 +00003207 }
Richard Smitha10b9782013-04-22 15:31:51 +00003208 return ESR_Succeeded;
3209 }
3210
Richard Smithc1c5f272011-12-13 06:39:58 +00003211 case Stmt::ReturnStmtClass: {
Richard Smithc1c5f272011-12-13 06:39:58 +00003212 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith03ce5f82013-07-24 07:11:57 +00003213 FullExpressionRAII Scope(Info);
Richard Smitha10b9782013-04-22 15:31:51 +00003214 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smithc1c5f272011-12-13 06:39:58 +00003215 return ESR_Failed;
3216 return ESR_Returned;
3217 }
Richard Smithd0dccea2011-10-28 22:34:42 +00003218
3219 case Stmt::CompoundStmtClass: {
Richard Smith03ce5f82013-07-24 07:11:57 +00003220 BlockScopeRAII Scope(Info);
3221
Richard Smithd0dccea2011-10-28 22:34:42 +00003222 const CompoundStmt *CS = cast<CompoundStmt>(S);
3223 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
3224 BE = CS->body_end(); BI != BE; ++BI) {
Richard Smith284b3cb2013-05-12 17:32:42 +00003225 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI, Case);
3226 if (ESR == ESR_Succeeded)
3227 Case = 0;
3228 else if (ESR != ESR_CaseNotFound)
Richard Smithd0dccea2011-10-28 22:34:42 +00003229 return ESR;
3230 }
Richard Smith284b3cb2013-05-12 17:32:42 +00003231 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smithd0dccea2011-10-28 22:34:42 +00003232 }
Richard Smitha10b9782013-04-22 15:31:51 +00003233
3234 case Stmt::IfStmtClass: {
3235 const IfStmt *IS = cast<IfStmt>(S);
3236
3237 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith03ce5f82013-07-24 07:11:57 +00003238 BlockScopeRAII Scope(Info);
Richard Smitha10b9782013-04-22 15:31:51 +00003239 bool Cond;
Richard Smithce617152013-05-06 05:56:11 +00003240 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smitha10b9782013-04-22 15:31:51 +00003241 return ESR_Failed;
3242
3243 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3244 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3245 if (ESR != ESR_Succeeded)
3246 return ESR;
3247 }
3248 return ESR_Succeeded;
3249 }
Richard Smithce617152013-05-06 05:56:11 +00003250
3251 case Stmt::WhileStmtClass: {
3252 const WhileStmt *WS = cast<WhileStmt>(S);
3253 while (true) {
Richard Smith03ce5f82013-07-24 07:11:57 +00003254 BlockScopeRAII Scope(Info);
Richard Smithce617152013-05-06 05:56:11 +00003255 bool Continue;
3256 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3257 Continue))
3258 return ESR_Failed;
3259 if (!Continue)
3260 break;
3261
3262 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3263 if (ESR != ESR_Continue)
3264 return ESR;
3265 }
3266 return ESR_Succeeded;
3267 }
3268
3269 case Stmt::DoStmtClass: {
3270 const DoStmt *DS = cast<DoStmt>(S);
3271 bool Continue;
3272 do {
Richard Smith284b3cb2013-05-12 17:32:42 +00003273 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smithce617152013-05-06 05:56:11 +00003274 if (ESR != ESR_Continue)
3275 return ESR;
Richard Smith284b3cb2013-05-12 17:32:42 +00003276 Case = 0;
Richard Smithce617152013-05-06 05:56:11 +00003277
Richard Smith03ce5f82013-07-24 07:11:57 +00003278 FullExpressionRAII CondScope(Info);
Richard Smithce617152013-05-06 05:56:11 +00003279 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3280 return ESR_Failed;
3281 } while (Continue);
3282 return ESR_Succeeded;
3283 }
3284
3285 case Stmt::ForStmtClass: {
3286 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith03ce5f82013-07-24 07:11:57 +00003287 BlockScopeRAII Scope(Info);
Richard Smithce617152013-05-06 05:56:11 +00003288 if (FS->getInit()) {
3289 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3290 if (ESR != ESR_Succeeded)
3291 return ESR;
3292 }
3293 while (true) {
Richard Smith03ce5f82013-07-24 07:11:57 +00003294 BlockScopeRAII Scope(Info);
Richard Smithce617152013-05-06 05:56:11 +00003295 bool Continue = true;
3296 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3297 FS->getCond(), Continue))
3298 return ESR_Failed;
3299 if (!Continue)
3300 break;
3301
3302 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3303 if (ESR != ESR_Continue)
3304 return ESR;
3305
Richard Smith03ce5f82013-07-24 07:11:57 +00003306 if (FS->getInc()) {
3307 FullExpressionRAII IncScope(Info);
3308 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3309 return ESR_Failed;
3310 }
Richard Smithce617152013-05-06 05:56:11 +00003311 }
3312 return ESR_Succeeded;
3313 }
3314
Richard Smith692eafd2013-05-06 06:51:17 +00003315 case Stmt::CXXForRangeStmtClass: {
3316 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith03ce5f82013-07-24 07:11:57 +00003317 BlockScopeRAII Scope(Info);
Richard Smith692eafd2013-05-06 06:51:17 +00003318
3319 // Initialize the __range variable.
3320 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3321 if (ESR != ESR_Succeeded)
3322 return ESR;
3323
3324 // Create the __begin and __end iterators.
3325 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3326 if (ESR != ESR_Succeeded)
3327 return ESR;
3328
3329 while (true) {
3330 // Condition: __begin != __end.
Richard Smith03ce5f82013-07-24 07:11:57 +00003331 {
3332 bool Continue = true;
3333 FullExpressionRAII CondExpr(Info);
3334 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3335 return ESR_Failed;
3336 if (!Continue)
3337 break;
3338 }
Richard Smith692eafd2013-05-06 06:51:17 +00003339
3340 // User's variable declaration, initialized by *__begin.
Richard Smith03ce5f82013-07-24 07:11:57 +00003341 BlockScopeRAII InnerScope(Info);
Richard Smith692eafd2013-05-06 06:51:17 +00003342 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3343 if (ESR != ESR_Succeeded)
3344 return ESR;
3345
3346 // Loop body.
3347 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3348 if (ESR != ESR_Continue)
3349 return ESR;
3350
3351 // Increment: ++__begin
3352 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3353 return ESR_Failed;
3354 }
3355
3356 return ESR_Succeeded;
3357 }
3358
Richard Smith284b3cb2013-05-12 17:32:42 +00003359 case Stmt::SwitchStmtClass:
3360 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3361
Richard Smithce617152013-05-06 05:56:11 +00003362 case Stmt::ContinueStmtClass:
3363 return ESR_Continue;
3364
3365 case Stmt::BreakStmtClass:
3366 return ESR_Break;
Richard Smith284b3cb2013-05-12 17:32:42 +00003367
3368 case Stmt::LabelStmtClass:
3369 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3370
3371 case Stmt::AttributedStmtClass:
3372 // As a general principle, C++11 attributes can be ignored without
3373 // any semantic impact.
3374 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3375 Case);
3376
3377 case Stmt::CaseStmtClass:
3378 case Stmt::DefaultStmtClass:
3379 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smithd0dccea2011-10-28 22:34:42 +00003380 }
3381}
3382
Richard Smith61802452011-12-22 02:22:31 +00003383/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3384/// default constructor. If so, we'll fold it whether or not it's marked as
3385/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3386/// so we need special handling.
3387static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00003388 const CXXConstructorDecl *CD,
3389 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00003390 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3391 return false;
3392
Richard Smith4c3fc9b2012-01-18 05:21:49 +00003393 // Value-initialization does not call a trivial default constructor, so such a
3394 // call is a core constant expression whether or not the constructor is
3395 // constexpr.
3396 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003397 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00003398 // FIXME: If DiagDecl is an implicitly-declared special member function,
3399 // we should be much more explicit about why it's not constexpr.
3400 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3401 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3402 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00003403 } else {
3404 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3405 }
3406 }
3407 return true;
3408}
3409
Richard Smithc1c5f272011-12-13 06:39:58 +00003410/// CheckConstexprFunction - Check that a function can be called in a constant
3411/// expression.
3412static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3413 const FunctionDecl *Declaration,
3414 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00003415 // Potential constant expressions can contain calls to declared, but not yet
3416 // defined, constexpr functions.
3417 if (Info.CheckingPotentialConstantExpression && !Definition &&
3418 Declaration->isConstexpr())
3419 return false;
3420
Richard Smithf039e3e2013-05-14 05:18:44 +00003421 // Bail out with no diagnostic if the function declaration itself is invalid.
3422 // We will have produced a relevant diagnostic while parsing it.
3423 if (Declaration->isInvalidDecl())
3424 return false;
3425
Richard Smithc1c5f272011-12-13 06:39:58 +00003426 // Can we evaluate this function call?
3427 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3428 return true;
3429
Richard Smith80ad52f2013-01-02 11:42:31 +00003430 if (Info.getLangOpts().CPlusPlus11) {
Richard Smithc1c5f272011-12-13 06:39:58 +00003431 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00003432 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3433 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00003434 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3435 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3436 << DiagDecl;
3437 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3438 } else {
3439 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3440 }
3441 return false;
3442}
3443
Richard Smith180f4792011-11-10 06:34:14 +00003444namespace {
Richard Smith1aa0be82012-03-03 22:46:17 +00003445typedef SmallVector<APValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00003446}
3447
3448/// EvaluateArgs - Evaluate the arguments to a function call.
3449static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3450 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00003451 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003452 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00003453 I != E; ++I) {
3454 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3455 // If we're checking for a potential constant expression, evaluate all
3456 // initializers even if some of them fail.
3457 if (!Info.keepEvaluatingAfterFailure())
3458 return false;
3459 Success = false;
3460 }
3461 }
3462 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003463}
3464
Richard Smithd0dccea2011-10-28 22:34:42 +00003465/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00003466static bool HandleFunctionCall(SourceLocation CallLoc,
3467 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00003468 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith1aa0be82012-03-03 22:46:17 +00003469 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00003470 ArgVector ArgValues(Args.size());
3471 if (!EvaluateArgs(Args, ArgValues, Info))
3472 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00003473
Richard Smith745f5142012-01-27 01:14:48 +00003474 if (!Info.CheckCallLimit(CallLoc))
3475 return false;
3476
3477 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smitha8942d72013-05-07 03:19:20 +00003478
3479 // For a trivial copy or move assignment, perform an APValue copy. This is
3480 // essential for unions, where the operations performed by the assignment
3481 // operator cannot be represented as statements.
3482 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3483 if (MD && MD->isDefaulted() && MD->isTrivial()) {
3484 assert(This &&
3485 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3486 LValue RHS;
3487 RHS.setFrom(Info.Ctx, ArgValues[0]);
3488 APValue RHSValue;
3489 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3490 RHS, RHSValue))
3491 return false;
3492 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3493 RHSValue))
3494 return false;
3495 This->moveInto(Result);
3496 return true;
3497 }
3498
Richard Smitha10b9782013-04-22 15:31:51 +00003499 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smithbebf5b12013-04-26 14:36:30 +00003500 if (ESR == ESR_Succeeded) {
3501 if (Callee->getResultType()->isVoidType())
3502 return true;
Richard Smitha10b9782013-04-22 15:31:51 +00003503 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smithbebf5b12013-04-26 14:36:30 +00003504 }
Richard Smitha10b9782013-04-22 15:31:51 +00003505 return ESR == ESR_Returned;
Richard Smithd0dccea2011-10-28 22:34:42 +00003506}
3507
Richard Smith180f4792011-11-10 06:34:14 +00003508/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00003509static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00003510 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00003511 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00003512 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00003513 ArgVector ArgValues(Args.size());
3514 if (!EvaluateArgs(Args, ArgValues, Info))
3515 return false;
3516
Richard Smith745f5142012-01-27 01:14:48 +00003517 if (!Info.CheckCallLimit(CallLoc))
3518 return false;
3519
Richard Smith86c3ae42012-02-13 03:54:03 +00003520 const CXXRecordDecl *RD = Definition->getParent();
3521 if (RD->getNumVBases()) {
3522 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3523 return false;
3524 }
3525
Richard Smith745f5142012-01-27 01:14:48 +00003526 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00003527
3528 // If it's a delegating constructor, just delegate.
3529 if (Definition->isDelegatingConstructor()) {
3530 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smitha10b9782013-04-22 15:31:51 +00003531 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3532 return false;
3533 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smith180f4792011-11-10 06:34:14 +00003534 }
3535
Richard Smith610a60c2012-01-10 04:32:03 +00003536 // For a trivial copy or move constructor, perform an APValue copy. This is
3537 // essential for unions, where the operations performed by the constructor
3538 // cannot be represented by ctor-initializers.
Richard Smith610a60c2012-01-10 04:32:03 +00003539 if (Definition->isDefaulted() &&
Douglas Gregorf6cfe8b2012-02-24 07:55:51 +00003540 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3541 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith610a60c2012-01-10 04:32:03 +00003542 LValue RHS;
Richard Smith1aa0be82012-03-03 22:46:17 +00003543 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5528ac92013-05-05 23:31:59 +00003544 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith1aa0be82012-03-03 22:46:17 +00003545 RHS, Result);
Richard Smith610a60c2012-01-10 04:32:03 +00003546 }
3547
3548 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00003549 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00003550 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3551 std::distance(RD->field_begin(), RD->field_end()));
3552
John McCall8d59dee2012-05-01 00:38:49 +00003553 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00003554 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3555
Richard Smith03ce5f82013-07-24 07:11:57 +00003556 // A scope for temporaries lifetime-extended by reference members.
3557 BlockScopeRAII LifetimeExtendedScope(Info);
3558
Richard Smith745f5142012-01-27 01:14:48 +00003559 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003560 unsigned BasesSeen = 0;
3561#ifndef NDEBUG
3562 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3563#endif
3564 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
3565 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00003566 LValue Subobject = This;
3567 APValue *Value = &Result;
3568
3569 // Determine the subobject to initialize.
Richard Smith3835a4e2013-08-06 07:09:20 +00003570 FieldDecl *FD = 0;
Richard Smith180f4792011-11-10 06:34:14 +00003571 if ((*I)->isBaseInitializer()) {
3572 QualType BaseType((*I)->getBaseClass(), 0);
3573#ifndef NDEBUG
3574 // Non-virtual base classes are initialized in the order in the class
Richard Smith86c3ae42012-02-13 03:54:03 +00003575 // definition. We have already checked for virtual base classes.
Richard Smith180f4792011-11-10 06:34:14 +00003576 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3577 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3578 "base class initializers not in expected order");
3579 ++BaseIt;
3580#endif
John McCall8d59dee2012-05-01 00:38:49 +00003581 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
3582 BaseType->getAsCXXRecordDecl(), &Layout))
3583 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003584 Value = &Result.getStructBase(BasesSeen++);
Richard Smith3835a4e2013-08-06 07:09:20 +00003585 } else if ((FD = (*I)->getMember())) {
John McCall8d59dee2012-05-01 00:38:49 +00003586 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
3587 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003588 if (RD->isUnion()) {
3589 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00003590 Value = &Result.getUnionValue();
3591 } else {
3592 Value = &Result.getStructField(FD->getFieldIndex());
3593 }
Richard Smithd9b02e72012-01-25 22:15:11 +00003594 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00003595 // Walk the indirect field decl's chain to find the object to initialize,
3596 // and make sure we've initialized every step along it.
3597 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
3598 CE = IFD->chain_end();
3599 C != CE; ++C) {
Richard Smith3835a4e2013-08-06 07:09:20 +00003600 FD = cast<FieldDecl>(*C);
Richard Smithd9b02e72012-01-25 22:15:11 +00003601 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3602 // Switch the union field if it differs. This happens if we had
3603 // preceding zero-initialization, and we're now initializing a union
3604 // subobject other than the first.
3605 // FIXME: In this case, the values of the other subobjects are
3606 // specified, since zero-initialization sets all padding bits to zero.
3607 if (Value->isUninit() ||
3608 (Value->isUnion() && Value->getUnionField() != FD)) {
3609 if (CD->isUnion())
3610 *Value = APValue(FD);
3611 else
3612 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
3613 std::distance(CD->field_begin(), CD->field_end()));
3614 }
John McCall8d59dee2012-05-01 00:38:49 +00003615 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
3616 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00003617 if (CD->isUnion())
3618 Value = &Value->getUnionValue();
3619 else
3620 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00003621 }
Richard Smith180f4792011-11-10 06:34:14 +00003622 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00003623 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00003624 }
Richard Smith745f5142012-01-27 01:14:48 +00003625
Richard Smith03ce5f82013-07-24 07:11:57 +00003626 FullExpressionRAII InitScope(Info);
Richard Smith3835a4e2013-08-06 07:09:20 +00003627 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit()) ||
3628 (FD && FD->isBitField() && !truncateBitfieldValue(Info, (*I)->getInit(),
3629 *Value, FD))) {
Richard Smith745f5142012-01-27 01:14:48 +00003630 // If we're checking for a potential constant expression, evaluate all
3631 // initializers even if some of them fail.
3632 if (!Info.keepEvaluatingAfterFailure())
3633 return false;
3634 Success = false;
3635 }
Richard Smith180f4792011-11-10 06:34:14 +00003636 }
3637
Richard Smitha10b9782013-04-22 15:31:51 +00003638 return Success &&
3639 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smith180f4792011-11-10 06:34:14 +00003640}
3641
Eli Friedman4efaa272008-11-12 09:44:48 +00003642//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003643// Generic Evaluation
3644//===----------------------------------------------------------------------===//
3645namespace {
3646
Richard Smithf48fdb02011-12-09 22:58:01 +00003647// FIXME: RetTy is always bool. Remove it.
3648template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003649class ExprEvaluatorBase
3650 : public ConstStmtVisitor<Derived, RetTy> {
3651private:
Richard Smith1aa0be82012-03-03 22:46:17 +00003652 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003653 return static_cast<Derived*>(this)->Success(V, E);
3654 }
Richard Smith51201882011-12-30 21:15:51 +00003655 RetTy DerivedZeroInitialization(const Expr *E) {
3656 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00003657 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003658
Richard Smith74e1ad92012-02-16 02:46:34 +00003659 // Check whether a conditional operator with a non-constant condition is a
3660 // potential constant expression. If neither arm is a potential constant
3661 // expression, then the conditional operator is not either.
3662 template<typename ConditionalOperator>
3663 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
3664 assert(Info.CheckingPotentialConstantExpression);
3665
3666 // Speculatively evaluate both arms.
3667 {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003668 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith74e1ad92012-02-16 02:46:34 +00003669 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3670
3671 StmtVisitorTy::Visit(E->getFalseExpr());
3672 if (Diag.empty())
3673 return;
3674
3675 Diag.clear();
3676 StmtVisitorTy::Visit(E->getTrueExpr());
3677 if (Diag.empty())
3678 return;
3679 }
3680
3681 Error(E, diag::note_constexpr_conditional_never_const);
3682 }
3683
3684
3685 template<typename ConditionalOperator>
3686 bool HandleConditionalOperator(const ConditionalOperator *E) {
3687 bool BoolResult;
3688 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
3689 if (Info.CheckingPotentialConstantExpression)
3690 CheckPotentialConstantConditional(E);
3691 return false;
3692 }
3693
3694 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3695 return StmtVisitorTy::Visit(EvalExpr);
3696 }
3697
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003698protected:
3699 EvalInfo &Info;
3700 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
3701 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3702
Richard Smithdd1f29b2011-12-12 09:28:41 +00003703 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00003704 return Info.CCEDiag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00003705 }
3706
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003707 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
3708
3709public:
3710 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3711
3712 EvalInfo &getEvalInfo() { return Info; }
3713
Richard Smithf48fdb02011-12-09 22:58:01 +00003714 /// Report an evaluation error. This should only be called when an error is
3715 /// first discovered. When propagating an error, just return false.
3716 bool Error(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00003717 Info.Diag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00003718 return false;
3719 }
3720 bool Error(const Expr *E) {
3721 return Error(E, diag::note_invalid_subexpr_in_const_expr);
3722 }
3723
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003724 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003725 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003726 }
3727 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00003728 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003729 }
3730
3731 RetTy VisitParenExpr(const ParenExpr *E)
3732 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3733 RetTy VisitUnaryExtension(const UnaryOperator *E)
3734 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3735 RetTy VisitUnaryPlus(const UnaryOperator *E)
3736 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3737 RetTy VisitChooseExpr(const ChooseExpr *E)
Eli Friedmana5e66012013-07-20 00:40:58 +00003738 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003739 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
3740 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00003741 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
3742 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00003743 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
3744 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith1fca5472013-09-13 20:51:45 +00003745 RetTy VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
3746 // The initializer may not have been parsed yet, or might be erroneous.
3747 if (!E->getExpr())
3748 return Error(E);
3749 return StmtVisitorTy::Visit(E->getExpr());
3750 }
Richard Smithbc6abe92011-12-19 22:12:41 +00003751 // We cannot create any objects for which cleanups are required, so there is
3752 // nothing to do here; all cleanups must come from unevaluated subexpressions.
3753 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
3754 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003755
Richard Smithc216a012011-12-12 12:46:16 +00003756 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
3757 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3758 return static_cast<Derived*>(this)->VisitCastExpr(E);
3759 }
3760 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
3761 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3762 return static_cast<Derived*>(this)->VisitCastExpr(E);
3763 }
3764
Richard Smithe24f5fc2011-11-17 22:56:20 +00003765 RetTy VisitBinaryOperator(const BinaryOperator *E) {
3766 switch (E->getOpcode()) {
3767 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00003768 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003769
3770 case BO_Comma:
3771 VisitIgnoredValue(E->getLHS());
3772 return StmtVisitorTy::Visit(E->getRHS());
3773
3774 case BO_PtrMemD:
3775 case BO_PtrMemI: {
3776 LValue Obj;
3777 if (!HandleMemberPointerAccess(Info, E, Obj))
3778 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00003779 APValue Result;
Richard Smith5528ac92013-05-05 23:31:59 +00003780 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00003781 return false;
3782 return DerivedSuccess(Result, E);
3783 }
3784 }
3785 }
3786
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003787 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smithe92b1f42012-06-26 08:12:11 +00003788 // Evaluate and cache the common expression. We treat it as a temporary,
3789 // even though it's not quite the same thing.
Richard Smith03ce5f82013-07-24 07:11:57 +00003790 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smithe92b1f42012-06-26 08:12:11 +00003791 Info, E->getCommon()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003792 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003793
Richard Smith74e1ad92012-02-16 02:46:34 +00003794 return HandleConditionalOperator(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003795 }
3796
3797 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00003798 bool IsBcpCall = false;
3799 // If the condition (ignoring parens) is a __builtin_constant_p call,
3800 // the result is a constant expression if it can be folded without
3801 // side-effects. This is an important GNU extension. See GCC PR38377
3802 // for discussion.
3803 if (const CallExpr *CallCE =
3804 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
3805 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
3806 IsBcpCall = true;
3807
3808 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3809 // constant expression; we can't check whether it's potentially foldable.
3810 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
3811 return false;
3812
3813 FoldConstant Fold(Info);
3814
Richard Smith74e1ad92012-02-16 02:46:34 +00003815 if (!HandleConditionalOperator(E))
Richard Smithf15fda02012-02-02 01:16:57 +00003816 return false;
3817
3818 if (IsBcpCall)
3819 Fold.Fold(Info);
3820
3821 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003822 }
3823
3824 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith03ce5f82013-07-24 07:11:57 +00003825 if (APValue *Value = Info.CurrentCall->getTemporary(E))
3826 return DerivedSuccess(*Value, E);
3827
3828 const Expr *Source = E->getSourceExpr();
3829 if (!Source)
3830 return Error(E);
3831 if (Source == E) { // sanity checking.
3832 assert(0 && "OpaqueValueExpr recursively refers to itself");
3833 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00003834 }
Richard Smith03ce5f82013-07-24 07:11:57 +00003835 return StmtVisitorTy::Visit(Source);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003836 }
Richard Smithf10d9172011-10-11 21:43:33 +00003837
Richard Smithd0dccea2011-10-28 22:34:42 +00003838 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003839 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00003840 QualType CalleeType = Callee->getType();
3841
Richard Smithd0dccea2011-10-28 22:34:42 +00003842 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00003843 LValue *This = 0, ThisVal;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003844 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith86c3ae42012-02-13 03:54:03 +00003845 bool HasQualifier = false;
Richard Smith6c957872011-11-10 09:31:24 +00003846
Richard Smith59efe262011-11-11 04:05:33 +00003847 // Extract function decl and 'this' pointer from the callee.
3848 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00003849 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003850 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3851 // Explicit bound member calls, such as x.f() or p->g();
3852 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00003853 return false;
3854 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00003855 This = &ThisVal;
Richard Smith86c3ae42012-02-13 03:54:03 +00003856 HasQualifier = ME->hasQualifier();
Richard Smithe24f5fc2011-11-17 22:56:20 +00003857 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
3858 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00003859 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
3860 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003861 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003862 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00003863 return Error(Callee);
3864
3865 FD = dyn_cast<FunctionDecl>(Member);
3866 if (!FD)
3867 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00003868 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003869 LValue Call;
3870 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003871 return false;
Richard Smith59efe262011-11-11 04:05:33 +00003872
Richard Smithb4e85ed2012-01-06 16:39:00 +00003873 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00003874 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003875 FD = dyn_cast_or_null<FunctionDecl>(
3876 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00003877 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00003878 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00003879
3880 // Overloaded operator calls to member functions are represented as normal
3881 // calls with '*this' as the first argument.
3882 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
3883 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00003884 // FIXME: When selecting an implicit conversion for an overloaded
3885 // operator delete, we sometimes try to evaluate calls to conversion
3886 // operators without a 'this' parameter!
3887 if (Args.empty())
3888 return Error(E);
3889
Richard Smith59efe262011-11-11 04:05:33 +00003890 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
3891 return false;
3892 This = &ThisVal;
3893 Args = Args.slice(1);
3894 }
3895
3896 // Don't call function pointers which have been cast to some other type.
3897 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003898 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00003899 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00003900 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00003901
Richard Smithb04035a2012-02-01 02:39:43 +00003902 if (This && !This->checkSubobject(Info, E, CSK_This))
3903 return false;
3904
Richard Smith86c3ae42012-02-13 03:54:03 +00003905 // DR1358 allows virtual constexpr functions in some cases. Don't allow
3906 // calls to such functions in constant expressions.
3907 if (This && !HasQualifier &&
3908 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
3909 return Error(E, diag::note_constexpr_virtual_call);
3910
Richard Smithc1c5f272011-12-13 06:39:58 +00003911 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00003912 Stmt *Body = FD->getBody(Definition);
Richard Smith1aa0be82012-03-03 22:46:17 +00003913 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00003914
Richard Smithc1c5f272011-12-13 06:39:58 +00003915 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00003916 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
3917 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00003918 return false;
3919
Richard Smith83587db2012-02-15 02:18:13 +00003920 return DerivedSuccess(Result, E);
Richard Smithd0dccea2011-10-28 22:34:42 +00003921 }
3922
Richard Smithc49bd112011-10-28 17:51:58 +00003923 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
3924 return StmtVisitorTy::Visit(E->getInitializer());
3925 }
Richard Smithf10d9172011-10-11 21:43:33 +00003926 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00003927 if (E->getNumInits() == 0)
3928 return DerivedZeroInitialization(E);
3929 if (E->getNumInits() == 1)
3930 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00003931 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00003932 }
3933 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00003934 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00003935 }
3936 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00003937 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00003938 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00003939 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00003940 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003941 }
Richard Smithf10d9172011-10-11 21:43:33 +00003942
Richard Smith180f4792011-11-10 06:34:14 +00003943 /// A member expression where the object is a prvalue is itself a prvalue.
3944 RetTy VisitMemberExpr(const MemberExpr *E) {
3945 assert(!E->isArrow() && "missing call to bound member function?");
3946
Richard Smith1aa0be82012-03-03 22:46:17 +00003947 APValue Val;
Richard Smith180f4792011-11-10 06:34:14 +00003948 if (!Evaluate(Val, Info, E->getBase()))
3949 return false;
3950
3951 QualType BaseTy = E->getBase()->getType();
3952
3953 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00003954 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003955 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek890f0f12012-08-23 20:46:57 +00003956 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smith180f4792011-11-10 06:34:14 +00003957 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3958
Richard Smithb476a142013-05-05 21:17:10 +00003959 CompleteObject Obj(&Val, BaseTy);
Richard Smithb4e85ed2012-01-06 16:39:00 +00003960 SubobjectDesignator Designator(BaseTy);
3961 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00003962
Richard Smithb476a142013-05-05 21:17:10 +00003963 APValue Result;
3964 return extractSubobject(Info, E, Obj, Designator, Result) &&
3965 DerivedSuccess(Result, E);
Richard Smith180f4792011-11-10 06:34:14 +00003966 }
3967
Richard Smithc49bd112011-10-28 17:51:58 +00003968 RetTy VisitCastExpr(const CastExpr *E) {
3969 switch (E->getCastKind()) {
3970 default:
3971 break;
3972
Richard Smith5705f212013-05-23 00:30:41 +00003973 case CK_AtomicToNonAtomic: {
3974 APValue AtomicVal;
3975 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
3976 return false;
3977 return DerivedSuccess(AtomicVal, E);
3978 }
3979
Richard Smithc49bd112011-10-28 17:51:58 +00003980 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00003981 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00003982 return StmtVisitorTy::Visit(E->getSubExpr());
3983
3984 case CK_LValueToRValue: {
3985 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00003986 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
3987 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00003988 APValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00003989 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith5528ac92013-05-05 23:31:59 +00003990 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smith9ec71972012-02-05 01:23:16 +00003991 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00003992 return false;
3993 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00003994 }
3995 }
3996
Richard Smithf48fdb02011-12-09 22:58:01 +00003997 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00003998 }
3999
Richard Smith5528ac92013-05-05 23:31:59 +00004000 RetTy VisitUnaryPostInc(const UnaryOperator *UO) {
4001 return VisitUnaryPostIncDec(UO);
4002 }
4003 RetTy VisitUnaryPostDec(const UnaryOperator *UO) {
4004 return VisitUnaryPostIncDec(UO);
4005 }
4006 RetTy VisitUnaryPostIncDec(const UnaryOperator *UO) {
4007 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4008 return Error(UO);
4009
4010 LValue LVal;
4011 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4012 return false;
4013 APValue RVal;
4014 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4015 UO->isIncrementOp(), &RVal))
4016 return false;
4017 return DerivedSuccess(RVal, UO);
4018 }
4019
Richard Smith37a84f62013-06-20 03:00:05 +00004020 RetTy VisitStmtExpr(const StmtExpr *E) {
4021 // We will have checked the full-expressions inside the statement expression
4022 // when they were completed, and don't need to check them again now.
4023 if (Info.getIntOverflowCheckMode())
4024 return Error(E);
4025
Richard Smith03ce5f82013-07-24 07:11:57 +00004026 BlockScopeRAII Scope(Info);
Richard Smith37a84f62013-06-20 03:00:05 +00004027 const CompoundStmt *CS = E->getSubStmt();
4028 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4029 BE = CS->body_end();
4030 /**/; ++BI) {
4031 if (BI + 1 == BE) {
4032 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4033 if (!FinalExpr) {
4034 Info.Diag((*BI)->getLocStart(),
4035 diag::note_constexpr_stmt_expr_unsupported);
4036 return false;
4037 }
4038 return this->Visit(FinalExpr);
4039 }
4040
4041 APValue ReturnValue;
4042 EvalStmtResult ESR = EvaluateStmt(ReturnValue, Info, *BI);
4043 if (ESR != ESR_Succeeded) {
4044 // FIXME: If the statement-expression terminated due to 'return',
4045 // 'break', or 'continue', it would be nice to propagate that to
4046 // the outer statement evaluation rather than bailing out.
4047 if (ESR != ESR_Failed)
4048 Info.Diag((*BI)->getLocStart(),
4049 diag::note_constexpr_stmt_expr_unsupported);
4050 return false;
4051 }
4052 }
4053 }
4054
Richard Smith8327fad2011-10-24 18:44:57 +00004055 /// Visit a value which is evaluated, but whose value is ignored.
4056 void VisitIgnoredValue(const Expr *E) {
Richard Smitha10b9782013-04-22 15:31:51 +00004057 EvaluateIgnoredValue(Info, E);
Richard Smith8327fad2011-10-24 18:44:57 +00004058 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004059};
4060
4061}
4062
4063//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00004064// Common base class for lvalue and temporary evaluation.
4065//===----------------------------------------------------------------------===//
4066namespace {
4067template<class Derived>
4068class LValueExprEvaluatorBase
4069 : public ExprEvaluatorBase<Derived, bool> {
4070protected:
4071 LValue &Result;
4072 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4073 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
4074
4075 bool Success(APValue::LValueBase B) {
4076 Result.set(B);
4077 return true;
4078 }
4079
4080public:
4081 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4082 ExprEvaluatorBaseTy(Info), Result(Result) {}
4083
Richard Smith1aa0be82012-03-03 22:46:17 +00004084 bool Success(const APValue &V, const Expr *E) {
4085 Result.setFrom(this->Info.Ctx, V);
Richard Smithe24f5fc2011-11-17 22:56:20 +00004086 return true;
4087 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00004088
Richard Smithe24f5fc2011-11-17 22:56:20 +00004089 bool VisitMemberExpr(const MemberExpr *E) {
4090 // Handle non-static data members.
4091 QualType BaseTy;
4092 if (E->isArrow()) {
4093 if (!EvaluatePointer(E->getBase(), Result, this->Info))
4094 return false;
Ted Kremenek890f0f12012-08-23 20:46:57 +00004095 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00004096 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00004097 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00004098 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
4099 return false;
4100 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00004101 } else {
4102 if (!this->Visit(E->getBase()))
4103 return false;
4104 BaseTy = E->getBase()->getType();
4105 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00004106
Richard Smithd9b02e72012-01-25 22:15:11 +00004107 const ValueDecl *MD = E->getMemberDecl();
4108 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4109 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4110 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4111 (void)BaseTy;
John McCall8d59dee2012-05-01 00:38:49 +00004112 if (!HandleLValueMember(this->Info, E, Result, FD))
4113 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00004114 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCall8d59dee2012-05-01 00:38:49 +00004115 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4116 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00004117 } else
4118 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00004119
Richard Smithd9b02e72012-01-25 22:15:11 +00004120 if (MD->getType()->isReferenceType()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00004121 APValue RefValue;
Richard Smith5528ac92013-05-05 23:31:59 +00004122 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00004123 RefValue))
4124 return false;
4125 return Success(RefValue, E);
4126 }
4127 return true;
4128 }
4129
4130 bool VisitBinaryOperator(const BinaryOperator *E) {
4131 switch (E->getOpcode()) {
4132 default:
4133 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4134
4135 case BO_PtrMemD:
4136 case BO_PtrMemI:
4137 return HandleMemberPointerAccess(this->Info, E, Result);
4138 }
4139 }
4140
4141 bool VisitCastExpr(const CastExpr *E) {
4142 switch (E->getCastKind()) {
4143 default:
4144 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4145
4146 case CK_DerivedToBase:
Richard Smith8a66bf72013-06-03 05:03:02 +00004147 case CK_UncheckedDerivedToBase:
Richard Smithe24f5fc2011-11-17 22:56:20 +00004148 if (!this->Visit(E->getSubExpr()))
4149 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00004150
4151 // Now figure out the necessary offset to add to the base LV to get from
4152 // the derived class to the base class.
Richard Smith8a66bf72013-06-03 05:03:02 +00004153 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4154 Result);
Richard Smithe24f5fc2011-11-17 22:56:20 +00004155 }
4156 }
4157};
4158}
4159
4160//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00004161// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00004162//
4163// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4164// function designators (in C), decl references to void objects (in C), and
4165// temporaries (if building with -Wno-address-of-temporary).
4166//
4167// LValue evaluation produces values comprising a base expression of one of the
4168// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004169// - Declarations
4170// * VarDecl
4171// * FunctionDecl
4172// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00004173// * CompoundLiteralExpr in C
4174// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00004175// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00004176// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00004177// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00004178// * ObjCEncodeExpr
4179// * AddrLabelExpr
4180// * BlockExpr
4181// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004182// - Locals and temporaries
Richard Smith8a66bf72013-06-03 05:03:02 +00004183// * MaterializeTemporaryExpr
Richard Smith83587db2012-02-15 02:18:13 +00004184// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith8a66bf72013-06-03 05:03:02 +00004185// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4186// from the AST (FIXME).
Richard Smith211c8dd2013-06-05 00:46:14 +00004187// * A MaterializeTemporaryExpr that has static storage duration, with no
4188// CallIndex, for a lifetime-extended temporary.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004189// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00004190//===----------------------------------------------------------------------===//
4191namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004192class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00004193 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00004194public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00004195 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4196 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00004197
Richard Smithc49bd112011-10-28 17:51:58 +00004198 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith5528ac92013-05-05 23:31:59 +00004199 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smithc49bd112011-10-28 17:51:58 +00004200
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004201 bool VisitDeclRefExpr(const DeclRefExpr *E);
4202 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00004203 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004204 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4205 bool VisitMemberExpr(const MemberExpr *E);
4206 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4207 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00004208 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichete275a182012-04-16 04:08:35 +00004209 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004210 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4211 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith86024012012-02-18 22:04:06 +00004212 bool VisitUnaryReal(const UnaryOperator *E);
4213 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith5528ac92013-05-05 23:31:59 +00004214 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4215 return VisitUnaryPreIncDec(UO);
4216 }
4217 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4218 return VisitUnaryPreIncDec(UO);
4219 }
Richard Smithb476a142013-05-05 21:17:10 +00004220 bool VisitBinAssign(const BinaryOperator *BO);
4221 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlsson26bc2202009-10-03 16:30:22 +00004222
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004223 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00004224 switch (E->getCastKind()) {
4225 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00004226 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00004227
Eli Friedmandb924222011-10-11 00:13:24 +00004228 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00004229 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00004230 if (!Visit(E->getSubExpr()))
4231 return false;
4232 Result.Designator.setInvalid();
4233 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00004234
Richard Smithe24f5fc2011-11-17 22:56:20 +00004235 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00004236 if (!Visit(E->getSubExpr()))
4237 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00004238 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00004239 }
4240 }
Eli Friedman4efaa272008-11-12 09:44:48 +00004241};
4242} // end anonymous namespace
4243
Richard Smithc49bd112011-10-28 17:51:58 +00004244/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smitha07a6c32013-05-01 19:00:39 +00004245/// expressions which are not glvalues, in two cases:
4246/// * function designators in C, and
4247/// * "extern void" objects
4248static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4249 assert(E->isGLValue() || E->getType()->isFunctionType() ||
4250 E->getType()->isVoidType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004251 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004252}
4253
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004254bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004255 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
4256 return Success(FD);
4257 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00004258 return VisitVarDecl(E, VD);
4259 return Error(E);
4260}
Richard Smith436c8892011-10-24 23:14:33 +00004261
Richard Smithc49bd112011-10-28 17:51:58 +00004262bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithb476a142013-05-05 21:17:10 +00004263 CallStackFrame *Frame = 0;
4264 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4265 Frame = Info.CurrentCall;
4266
Richard Smith177dce72011-11-01 16:57:24 +00004267 if (!VD->getType()->isReferenceType()) {
Richard Smithb476a142013-05-05 21:17:10 +00004268 if (Frame) {
4269 Result.set(VD, Frame->Index);
Richard Smith177dce72011-11-01 16:57:24 +00004270 return true;
4271 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004272 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00004273 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00004274
Richard Smithb476a142013-05-05 21:17:10 +00004275 APValue *V;
4276 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf48fdb02011-12-09 22:58:01 +00004277 return false;
Richard Smith03ce5f82013-07-24 07:11:57 +00004278 if (V->isUninit()) {
4279 if (!Info.CheckingPotentialConstantExpression)
4280 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4281 return false;
4282 }
Richard Smithb476a142013-05-05 21:17:10 +00004283 return Success(*V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00004284}
4285
Richard Smithbd552ef2011-10-31 05:52:43 +00004286bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4287 const MaterializeTemporaryExpr *E) {
Richard Smith8a66bf72013-06-03 05:03:02 +00004288 // Walk through the expression to find the materialized temporary itself.
4289 SmallVector<const Expr *, 2> CommaLHSs;
4290 SmallVector<SubobjectAdjustment, 2> Adjustments;
4291 const Expr *Inner = E->GetTemporaryExpr()->
4292 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smithe24f5fc2011-11-17 22:56:20 +00004293
Richard Smith8a66bf72013-06-03 05:03:02 +00004294 // If we passed any comma operators, evaluate their LHSs.
4295 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4296 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4297 return false;
4298
Richard Smith211c8dd2013-06-05 00:46:14 +00004299 // A materialized temporary with static storage duration can appear within the
4300 // result of a constant expression evaluation, so we need to preserve its
4301 // value for use outside this evaluation.
4302 APValue *Value;
4303 if (E->getStorageDuration() == SD_Static) {
4304 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smith3282b842013-06-14 03:07:01 +00004305 *Value = APValue();
Richard Smith211c8dd2013-06-05 00:46:14 +00004306 Result.set(E);
4307 } else {
Richard Smith03ce5f82013-07-24 07:11:57 +00004308 Value = &Info.CurrentCall->
4309 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smith211c8dd2013-06-05 00:46:14 +00004310 Result.set(E, Info.CurrentCall->Index);
4311 }
4312
Richard Smithf69dd332013-06-06 08:19:16 +00004313 QualType Type = Inner->getType();
4314
Richard Smith8a66bf72013-06-03 05:03:02 +00004315 // Materialize the temporary itself.
Richard Smithf69dd332013-06-06 08:19:16 +00004316 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4317 (E->getStorageDuration() == SD_Static &&
4318 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4319 *Value = APValue();
Richard Smith8a66bf72013-06-03 05:03:02 +00004320 return false;
Richard Smithf69dd332013-06-06 08:19:16 +00004321 }
Richard Smith8a66bf72013-06-03 05:03:02 +00004322
4323 // Adjust our lvalue to refer to the desired subobject.
Richard Smith8a66bf72013-06-03 05:03:02 +00004324 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4325 --I;
4326 switch (Adjustments[I].Kind) {
4327 case SubobjectAdjustment::DerivedToBaseAdjustment:
4328 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4329 Type, Result))
4330 return false;
4331 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4332 break;
4333
4334 case SubobjectAdjustment::FieldAdjustment:
4335 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4336 return false;
4337 Type = Adjustments[I].Field->getType();
4338 break;
4339
4340 case SubobjectAdjustment::MemberPointerAdjustment:
4341 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4342 Adjustments[I].Ptr.RHS))
4343 return false;
4344 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4345 break;
4346 }
4347 }
4348
4349 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00004350}
4351
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004352bool
4353LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004354 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4355 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4356 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00004357 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004358}
4359
Richard Smith47d21452011-12-27 12:18:28 +00004360bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith9be36ab2012-10-17 23:52:07 +00004361 if (!E->isPotentiallyEvaluated())
Richard Smith47d21452011-12-27 12:18:28 +00004362 return Success(E);
Richard Smith9be36ab2012-10-17 23:52:07 +00004363
4364 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4365 << E->getExprOperand()->getType()
4366 << E->getExprOperand()->getSourceRange();
4367 return false;
Richard Smith47d21452011-12-27 12:18:28 +00004368}
4369
Francois Pichete275a182012-04-16 04:08:35 +00004370bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4371 return Success(E);
Richard Smithb476a142013-05-05 21:17:10 +00004372}
Francois Pichete275a182012-04-16 04:08:35 +00004373
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004374bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004375 // Handle static data members.
4376 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4377 VisitIgnoredValue(E->getBase());
4378 return VisitVarDecl(E, VD);
4379 }
4380
Richard Smithd0dccea2011-10-28 22:34:42 +00004381 // Handle static member functions.
4382 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4383 if (MD->isStatic()) {
4384 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004385 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00004386 }
4387 }
4388
Richard Smith180f4792011-11-10 06:34:14 +00004389 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00004390 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004391}
4392
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004393bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004394 // FIXME: Deal with vectors as array subscript bases.
4395 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004396 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004397
Anders Carlsson3068d112008-11-16 19:01:22 +00004398 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00004399 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004400
Anders Carlsson3068d112008-11-16 19:01:22 +00004401 APSInt Index;
4402 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00004403 return false;
Anders Carlsson3068d112008-11-16 19:01:22 +00004404
Richard Smitha49a7fe2013-05-07 23:34:45 +00004405 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4406 getExtValue(Index));
Anders Carlsson3068d112008-11-16 19:01:22 +00004407}
Eli Friedman4efaa272008-11-12 09:44:48 +00004408
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004409bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00004410 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00004411}
4412
Richard Smith86024012012-02-18 22:04:06 +00004413bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4414 if (!Visit(E->getSubExpr()))
4415 return false;
4416 // __real is a no-op on scalar lvalues.
4417 if (E->getSubExpr()->getType()->isAnyComplexType())
4418 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4419 return true;
4420}
4421
4422bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4423 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4424 "lvalue __imag__ on scalar?");
4425 if (!Visit(E->getSubExpr()))
4426 return false;
4427 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4428 return true;
4429}
4430
Richard Smith5528ac92013-05-05 23:31:59 +00004431bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4432 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smithb476a142013-05-05 21:17:10 +00004433 return Error(UO);
4434
4435 if (!this->Visit(UO->getSubExpr()))
4436 return false;
4437
Richard Smith5528ac92013-05-05 23:31:59 +00004438 return handleIncDec(
4439 this->Info, UO, Result, UO->getSubExpr()->getType(),
4440 UO->isIncrementOp(), 0);
Richard Smithb476a142013-05-05 21:17:10 +00004441}
4442
4443bool LValueExprEvaluator::VisitCompoundAssignOperator(
4444 const CompoundAssignOperator *CAO) {
Richard Smith5528ac92013-05-05 23:31:59 +00004445 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smithb476a142013-05-05 21:17:10 +00004446 return Error(CAO);
4447
Richard Smithb476a142013-05-05 21:17:10 +00004448 APValue RHS;
Richard Smith5528ac92013-05-05 23:31:59 +00004449
4450 // The overall lvalue result is the result of evaluating the LHS.
4451 if (!this->Visit(CAO->getLHS())) {
4452 if (Info.keepEvaluatingAfterFailure())
4453 Evaluate(RHS, this->Info, CAO->getRHS());
4454 return false;
4455 }
4456
Richard Smithb476a142013-05-05 21:17:10 +00004457 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4458 return false;
4459
Richard Smithd20afcb2013-05-07 04:50:00 +00004460 return handleCompoundAssignment(
4461 this->Info, CAO,
4462 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4463 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smithb476a142013-05-05 21:17:10 +00004464}
4465
4466bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Richard Smith5528ac92013-05-05 23:31:59 +00004467 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4468 return Error(E);
4469
Richard Smithb476a142013-05-05 21:17:10 +00004470 APValue NewVal;
Richard Smith5528ac92013-05-05 23:31:59 +00004471
4472 if (!this->Visit(E->getLHS())) {
4473 if (Info.keepEvaluatingAfterFailure())
4474 Evaluate(NewVal, this->Info, E->getRHS());
4475 return false;
4476 }
4477
Richard Smithb476a142013-05-05 21:17:10 +00004478 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4479 return false;
Richard Smith5528ac92013-05-05 23:31:59 +00004480
4481 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smithb476a142013-05-05 21:17:10 +00004482 NewVal);
4483}
4484
Eli Friedman4efaa272008-11-12 09:44:48 +00004485//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004486// Pointer Evaluation
4487//===----------------------------------------------------------------------===//
4488
Anders Carlssonc754aa62008-07-08 05:13:58 +00004489namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004490class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004491 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00004492 LValue &Result;
4493
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004494 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004495 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00004496 return true;
4497 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00004498public:
Mike Stump1eb44332009-09-09 15:08:12 +00004499
John McCallefdb83e2010-05-07 21:00:08 +00004500 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004501 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004502
Richard Smith1aa0be82012-03-03 22:46:17 +00004503 bool Success(const APValue &V, const Expr *E) {
4504 Result.setFrom(Info.Ctx, V);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004505 return true;
4506 }
Richard Smith51201882011-12-30 21:15:51 +00004507 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00004508 return Success((Expr*)0);
4509 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00004510
John McCallefdb83e2010-05-07 21:00:08 +00004511 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004512 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00004513 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004514 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00004515 { return Success(E); }
Patrick Beardeb382ec2012-04-19 00:25:12 +00004516 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004517 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004518 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00004519 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004520 bool VisitCallExpr(const CallExpr *E);
4521 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00004522 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00004523 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00004524 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00004525 }
Richard Smith180f4792011-11-10 06:34:14 +00004526 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith8a66bf72013-06-03 05:03:02 +00004527 // Can't look at 'this' when checking a potential constant expression.
4528 if (Info.CheckingPotentialConstantExpression)
4529 return false;
Richard Smith180f4792011-11-10 06:34:14 +00004530 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00004531 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00004532 Result = *Info.CurrentCall->This;
4533 return true;
4534 }
John McCall56ca35d2011-02-17 10:25:35 +00004535
Eli Friedmanba98d6b2009-03-23 04:56:01 +00004536 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00004537};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004538} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00004539
John McCallefdb83e2010-05-07 21:00:08 +00004540static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004541 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004542 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004543}
4544
John McCallefdb83e2010-05-07 21:00:08 +00004545bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00004546 if (E->getOpcode() != BO_Add &&
4547 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00004548 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004549
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004550 const Expr *PExp = E->getLHS();
4551 const Expr *IExp = E->getRHS();
4552 if (IExp->getType()->isPointerType())
4553 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00004554
Richard Smith745f5142012-01-27 01:14:48 +00004555 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4556 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00004557 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004558
John McCallefdb83e2010-05-07 21:00:08 +00004559 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00004560 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00004561 return false;
Richard Smitha49a7fe2013-05-07 23:34:45 +00004562
4563 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith0a3bdb62011-11-04 02:25:55 +00004564 if (E->getOpcode() == BO_Sub)
4565 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004566
Ted Kremenek890f0f12012-08-23 20:46:57 +00004567 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00004568 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4569 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004570}
Eli Friedman4efaa272008-11-12 09:44:48 +00004571
John McCallefdb83e2010-05-07 21:00:08 +00004572bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4573 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00004574}
Mike Stump1eb44332009-09-09 15:08:12 +00004575
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004576bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4577 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004578
Eli Friedman09a8a0e2009-12-27 05:43:15 +00004579 switch (E->getCastKind()) {
4580 default:
4581 break;
4582
John McCall2de56d12010-08-25 11:45:40 +00004583 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00004584 case CK_CPointerToObjCPointerCast:
4585 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00004586 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00004587 if (!Visit(SubExpr))
4588 return false;
Richard Smithc216a012011-12-12 12:46:16 +00004589 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4590 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4591 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00004592 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00004593 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00004594 if (SubExpr->getType()->isVoidPointerType())
4595 CCEDiag(E, diag::note_constexpr_invalid_cast)
4596 << 3 << SubExpr->getType();
4597 else
4598 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4599 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00004600 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00004601
Anders Carlsson5c5a7642010-10-31 20:41:46 +00004602 case CK_DerivedToBase:
Richard Smith8a66bf72013-06-03 05:03:02 +00004603 case CK_UncheckedDerivedToBase:
Richard Smith47a1eed2011-10-29 20:57:55 +00004604 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00004605 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00004606 if (!Result.Base && Result.Offset.isZero())
4607 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00004608
Richard Smith180f4792011-11-10 06:34:14 +00004609 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00004610 // the derived class to the base class.
Richard Smith8a66bf72013-06-03 05:03:02 +00004611 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4612 castAs<PointerType>()->getPointeeType(),
4613 Result);
Anders Carlsson5c5a7642010-10-31 20:41:46 +00004614
Richard Smithe24f5fc2011-11-17 22:56:20 +00004615 case CK_BaseToDerived:
4616 if (!Visit(E->getSubExpr()))
4617 return false;
4618 if (!Result.Base && Result.Offset.isZero())
4619 return true;
4620 return HandleBaseToDerivedCast(Info, E, Result);
4621
Richard Smith47a1eed2011-10-29 20:57:55 +00004622 case CK_NullToPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00004623 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00004624 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00004625
John McCall2de56d12010-08-25 11:45:40 +00004626 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00004627 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4628
Richard Smith1aa0be82012-03-03 22:46:17 +00004629 APValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00004630 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00004631 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004632
John McCallefdb83e2010-05-07 21:00:08 +00004633 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004634 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4635 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004636 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00004637 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith83587db2012-02-15 02:18:13 +00004638 Result.CallIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00004639 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00004640 return true;
4641 } else {
4642 // Cast is of an lvalue, no need to change value.
Richard Smith1aa0be82012-03-03 22:46:17 +00004643 Result.setFrom(Info.Ctx, Value);
John McCallefdb83e2010-05-07 21:00:08 +00004644 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004645 }
4646 }
John McCall2de56d12010-08-25 11:45:40 +00004647 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00004648 if (SubExpr->isGLValue()) {
4649 if (!EvaluateLValue(SubExpr, Result, Info))
4650 return false;
4651 } else {
Richard Smith83587db2012-02-15 02:18:13 +00004652 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith03ce5f82013-07-24 07:11:57 +00004653 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smith83587db2012-02-15 02:18:13 +00004654 Info, Result, SubExpr))
Richard Smithe24f5fc2011-11-17 22:56:20 +00004655 return false;
4656 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00004657 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00004658 if (const ConstantArrayType *CAT
4659 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4660 Result.addArray(Info, E, CAT);
4661 else
4662 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00004663 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00004664
John McCall2de56d12010-08-25 11:45:40 +00004665 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00004666 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00004667 }
4668
Richard Smithc49bd112011-10-28 17:51:58 +00004669 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004670}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004671
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004672bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004673 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00004674 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00004675
Richard Smith5154dce2013-07-11 02:27:57 +00004676 switch (E->isBuiltinCall()) {
4677 case Builtin::BI__builtin_addressof:
4678 return EvaluateLValue(E->getArg(0), Result, Info);
4679
4680 default:
4681 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4682 }
Eli Friedman4efaa272008-11-12 09:44:48 +00004683}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004684
4685//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00004686// Member Pointer Evaluation
4687//===----------------------------------------------------------------------===//
4688
4689namespace {
4690class MemberPointerExprEvaluator
4691 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
4692 MemberPtr &Result;
4693
4694 bool Success(const ValueDecl *D) {
4695 Result = MemberPtr(D);
4696 return true;
4697 }
4698public:
4699
4700 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
4701 : ExprEvaluatorBaseTy(Info), Result(Result) {}
4702
Richard Smith1aa0be82012-03-03 22:46:17 +00004703 bool Success(const APValue &V, const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004704 Result.setFrom(V);
4705 return true;
4706 }
Richard Smith51201882011-12-30 21:15:51 +00004707 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004708 return Success((const ValueDecl*)0);
4709 }
4710
4711 bool VisitCastExpr(const CastExpr *E);
4712 bool VisitUnaryAddrOf(const UnaryOperator *E);
4713};
4714} // end anonymous namespace
4715
4716static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
4717 EvalInfo &Info) {
4718 assert(E->isRValue() && E->getType()->isMemberPointerType());
4719 return MemberPointerExprEvaluator(Info, Result).Visit(E);
4720}
4721
4722bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
4723 switch (E->getCastKind()) {
4724 default:
4725 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4726
4727 case CK_NullToMemberPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00004728 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00004729 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00004730
4731 case CK_BaseToDerivedMemberPointer: {
4732 if (!Visit(E->getSubExpr()))
4733 return false;
4734 if (E->path_empty())
4735 return true;
4736 // Base-to-derived member pointer casts store the path in derived-to-base
4737 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
4738 // the wrong end of the derived->base arc, so stagger the path by one class.
4739 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
4740 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
4741 PathI != PathE; ++PathI) {
4742 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4743 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
4744 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00004745 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00004746 }
4747 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
4748 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004749 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00004750 return true;
4751 }
4752
4753 case CK_DerivedToBaseMemberPointer:
4754 if (!Visit(E->getSubExpr()))
4755 return false;
4756 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4757 PathE = E->path_end(); PathI != PathE; ++PathI) {
4758 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4759 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4760 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00004761 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00004762 }
4763 return true;
4764 }
4765}
4766
4767bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4768 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
4769 // member can be formed.
4770 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
4771}
4772
4773//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00004774// Record Evaluation
4775//===----------------------------------------------------------------------===//
4776
4777namespace {
4778 class RecordExprEvaluator
4779 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
4780 const LValue &This;
4781 APValue &Result;
4782 public:
4783
4784 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
4785 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
4786
Richard Smith1aa0be82012-03-03 22:46:17 +00004787 bool Success(const APValue &V, const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00004788 Result = V;
4789 return true;
Richard Smith180f4792011-11-10 06:34:14 +00004790 }
Richard Smith51201882011-12-30 21:15:51 +00004791 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00004792
Richard Smith59efe262011-11-11 04:05:33 +00004793 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00004794 bool VisitInitListExpr(const InitListExpr *E);
4795 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith7c3e6152013-06-12 22:31:48 +00004796 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00004797 };
4798}
4799
Richard Smith51201882011-12-30 21:15:51 +00004800/// Perform zero-initialization on an object of non-union class type.
4801/// C++11 [dcl.init]p5:
4802/// To zero-initialize an object or reference of type T means:
4803/// [...]
4804/// -- if T is a (possibly cv-qualified) non-union class type,
4805/// each non-static data member and each base-class subobject is
4806/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00004807static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
4808 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00004809 const LValue &This, APValue &Result) {
4810 assert(!RD->isUnion() && "Expected non-union class type");
4811 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
4812 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
4813 std::distance(RD->field_begin(), RD->field_end()));
4814
John McCall8d59dee2012-05-01 00:38:49 +00004815 if (RD->isInvalidDecl()) return false;
Richard Smith51201882011-12-30 21:15:51 +00004816 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4817
4818 if (CD) {
4819 unsigned Index = 0;
4820 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00004821 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00004822 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4823 LValue Subobject = This;
John McCall8d59dee2012-05-01 00:38:49 +00004824 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4825 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00004826 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00004827 Result.getStructBase(Index)))
4828 return false;
4829 }
4830 }
4831
Richard Smithb4e85ed2012-01-06 16:39:00 +00004832 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
4833 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00004834 // -- if T is a reference type, no initialization is performed.
David Blaikie262bc182012-04-30 02:36:29 +00004835 if (I->getType()->isReferenceType())
Richard Smith51201882011-12-30 21:15:51 +00004836 continue;
4837
4838 LValue Subobject = This;
David Blaikie581deb32012-06-06 20:45:41 +00004839 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCall8d59dee2012-05-01 00:38:49 +00004840 return false;
Richard Smith51201882011-12-30 21:15:51 +00004841
David Blaikie262bc182012-04-30 02:36:29 +00004842 ImplicitValueInitExpr VIE(I->getType());
Richard Smith83587db2012-02-15 02:18:13 +00004843 if (!EvaluateInPlace(
David Blaikie262bc182012-04-30 02:36:29 +00004844 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00004845 return false;
4846 }
4847
4848 return true;
4849}
4850
4851bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
4852 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall1de9d7d2012-04-26 18:10:01 +00004853 if (RD->isInvalidDecl()) return false;
Richard Smith51201882011-12-30 21:15:51 +00004854 if (RD->isUnion()) {
4855 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4856 // object's first non-static named data member is zero-initialized
4857 RecordDecl::field_iterator I = RD->field_begin();
4858 if (I == RD->field_end()) {
4859 Result = APValue((const FieldDecl*)0);
4860 return true;
4861 }
4862
4863 LValue Subobject = This;
David Blaikie581deb32012-06-06 20:45:41 +00004864 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCall8d59dee2012-05-01 00:38:49 +00004865 return false;
David Blaikie581deb32012-06-06 20:45:41 +00004866 Result = APValue(*I);
David Blaikie262bc182012-04-30 02:36:29 +00004867 ImplicitValueInitExpr VIE(I->getType());
Richard Smith83587db2012-02-15 02:18:13 +00004868 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00004869 }
4870
Richard Smithce582fe2012-02-17 00:44:16 +00004871 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00004872 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smithce582fe2012-02-17 00:44:16 +00004873 return false;
4874 }
4875
Richard Smithb4e85ed2012-01-06 16:39:00 +00004876 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00004877}
4878
Richard Smith59efe262011-11-11 04:05:33 +00004879bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
4880 switch (E->getCastKind()) {
4881 default:
4882 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4883
4884 case CK_ConstructorConversion:
4885 return Visit(E->getSubExpr());
4886
4887 case CK_DerivedToBase:
4888 case CK_UncheckedDerivedToBase: {
Richard Smith1aa0be82012-03-03 22:46:17 +00004889 APValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00004890 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00004891 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004892 if (!DerivedObject.isStruct())
4893 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00004894
4895 // Derived-to-base rvalue conversion: just slice off the derived part.
4896 APValue *Value = &DerivedObject;
4897 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
4898 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4899 PathE = E->path_end(); PathI != PathE; ++PathI) {
4900 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
4901 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4902 Value = &Value->getStructBase(getBaseIndex(RD, Base));
4903 RD = Base;
4904 }
4905 Result = *Value;
4906 return true;
4907 }
4908 }
4909}
4910
Richard Smith180f4792011-11-10 06:34:14 +00004911bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
4912 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall1de9d7d2012-04-26 18:10:01 +00004913 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00004914 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4915
4916 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00004917 const FieldDecl *Field = E->getInitializedFieldInUnion();
4918 Result = APValue(Field);
4919 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00004920 return true;
Richard Smithec789162012-01-12 18:54:33 +00004921
4922 // If the initializer list for a union does not contain any elements, the
4923 // first element of the union is value-initialized.
Richard Smithc3bf52c2013-04-20 22:23:05 +00004924 // FIXME: The element should be initialized from an initializer list.
4925 // Is this difference ever observable for initializer lists which
4926 // we don't build?
Richard Smithec789162012-01-12 18:54:33 +00004927 ImplicitValueInitExpr VIE(Field->getType());
4928 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
4929
Richard Smith180f4792011-11-10 06:34:14 +00004930 LValue Subobject = This;
John McCall8d59dee2012-05-01 00:38:49 +00004931 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
4932 return false;
Richard Smithc3bf52c2013-04-20 22:23:05 +00004933
4934 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4935 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4936 isa<CXXDefaultInitExpr>(InitExpr));
4937
Richard Smith83587db2012-02-15 02:18:13 +00004938 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00004939 }
4940
4941 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
4942 "initializer list for class with base classes");
4943 Result = APValue(APValue::UninitStruct(), 0,
4944 std::distance(RD->field_begin(), RD->field_end()));
4945 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00004946 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00004947 for (RecordDecl::field_iterator Field = RD->field_begin(),
4948 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
4949 // Anonymous bit-fields are not considered members of the class for
4950 // purposes of aggregate initialization.
4951 if (Field->isUnnamedBitfield())
4952 continue;
4953
4954 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00004955
Richard Smith745f5142012-01-27 01:14:48 +00004956 bool HaveInit = ElementNo < E->getNumInits();
4957
4958 // FIXME: Diagnostics here should point to the end of the initializer
4959 // list, not the start.
John McCall8d59dee2012-05-01 00:38:49 +00004960 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie581deb32012-06-06 20:45:41 +00004961 Subobject, *Field, &Layout))
John McCall8d59dee2012-05-01 00:38:49 +00004962 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004963
4964 // Perform an implicit value-initialization for members beyond the end of
4965 // the initializer list.
4966 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smithc3bf52c2013-04-20 22:23:05 +00004967 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith745f5142012-01-27 01:14:48 +00004968
Richard Smithc3bf52c2013-04-20 22:23:05 +00004969 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4970 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4971 isa<CXXDefaultInitExpr>(Init));
4972
Richard Smith3835a4e2013-08-06 07:09:20 +00004973 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
4974 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
4975 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
4976 FieldVal, *Field))) {
Richard Smith745f5142012-01-27 01:14:48 +00004977 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00004978 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004979 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00004980 }
4981 }
4982
Richard Smith745f5142012-01-27 01:14:48 +00004983 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00004984}
4985
4986bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
4987 const CXXConstructorDecl *FD = E->getConstructor();
John McCall1de9d7d2012-04-26 18:10:01 +00004988 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
4989
Richard Smith51201882011-12-30 21:15:51 +00004990 bool ZeroInit = E->requiresZeroInitialization();
4991 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00004992 // If we've already performed zero-initialization, we're already done.
4993 if (!Result.isUninit())
4994 return true;
4995
Richard Smith51201882011-12-30 21:15:51 +00004996 if (ZeroInit)
4997 return ZeroInitialization(E);
4998
Richard Smith61802452011-12-22 02:22:31 +00004999 const CXXRecordDecl *RD = FD->getParent();
5000 if (RD->isUnion())
5001 Result = APValue((FieldDecl*)0);
5002 else
5003 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5004 std::distance(RD->field_begin(), RD->field_end()));
5005 return true;
5006 }
5007
Richard Smith180f4792011-11-10 06:34:14 +00005008 const FunctionDecl *Definition = 0;
5009 FD->getBody(Definition);
5010
Richard Smithc1c5f272011-12-13 06:39:58 +00005011 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5012 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005013
Richard Smith610a60c2012-01-10 04:32:03 +00005014 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00005015 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00005016 if (const MaterializeTemporaryExpr *ME
5017 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5018 return Visit(ME->GetTemporaryExpr());
5019
Richard Smith51201882011-12-30 21:15:51 +00005020 if (ZeroInit && !ZeroInitialization(E))
5021 return false;
5022
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005023 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00005024 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00005025 cast<CXXConstructorDecl>(Definition), Info,
5026 Result);
Richard Smith180f4792011-11-10 06:34:14 +00005027}
5028
Richard Smith7c3e6152013-06-12 22:31:48 +00005029bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5030 const CXXStdInitializerListExpr *E) {
5031 const ConstantArrayType *ArrayType =
5032 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5033
5034 LValue Array;
5035 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5036 return false;
5037
5038 // Get a pointer to the first element of the array.
5039 Array.addArray(Info, E, ArrayType);
5040
5041 // FIXME: Perform the checks on the field types in SemaInit.
5042 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5043 RecordDecl::field_iterator Field = Record->field_begin();
5044 if (Field == Record->field_end())
5045 return Error(E);
5046
5047 // Start pointer.
5048 if (!Field->getType()->isPointerType() ||
5049 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5050 ArrayType->getElementType()))
5051 return Error(E);
5052
5053 // FIXME: What if the initializer_list type has base classes, etc?
5054 Result = APValue(APValue::UninitStruct(), 0, 2);
5055 Array.moveInto(Result.getStructField(0));
5056
5057 if (++Field == Record->field_end())
5058 return Error(E);
5059
5060 if (Field->getType()->isPointerType() &&
5061 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5062 ArrayType->getElementType())) {
5063 // End pointer.
5064 if (!HandleLValueArrayAdjustment(Info, E, Array,
5065 ArrayType->getElementType(),
5066 ArrayType->getSize().getZExtValue()))
5067 return false;
5068 Array.moveInto(Result.getStructField(1));
5069 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5070 // Length.
5071 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5072 else
5073 return Error(E);
5074
5075 if (++Field != Record->field_end())
5076 return Error(E);
5077
5078 return true;
5079}
5080
Richard Smith180f4792011-11-10 06:34:14 +00005081static bool EvaluateRecord(const Expr *E, const LValue &This,
5082 APValue &Result, EvalInfo &Info) {
5083 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00005084 "can't evaluate expression as a record rvalue");
5085 return RecordExprEvaluator(Info, This, Result).Visit(E);
5086}
5087
5088//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00005089// Temporary Evaluation
5090//
5091// Temporaries are represented in the AST as rvalues, but generally behave like
5092// lvalues. The full-object of which the temporary is a subobject is implicitly
5093// materialized so that a reference can bind to it.
5094//===----------------------------------------------------------------------===//
5095namespace {
5096class TemporaryExprEvaluator
5097 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5098public:
5099 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5100 LValueExprEvaluatorBaseTy(Info, Result) {}
5101
5102 /// Visit an expression which constructs the value of this temporary.
5103 bool VisitConstructExpr(const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00005104 Result.set(E, Info.CurrentCall->Index);
Richard Smith03ce5f82013-07-24 07:11:57 +00005105 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5106 Info, Result, E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00005107 }
5108
5109 bool VisitCastExpr(const CastExpr *E) {
5110 switch (E->getCastKind()) {
5111 default:
5112 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5113
5114 case CK_ConstructorConversion:
5115 return VisitConstructExpr(E->getSubExpr());
5116 }
5117 }
5118 bool VisitInitListExpr(const InitListExpr *E) {
5119 return VisitConstructExpr(E);
5120 }
5121 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5122 return VisitConstructExpr(E);
5123 }
5124 bool VisitCallExpr(const CallExpr *E) {
5125 return VisitConstructExpr(E);
5126 }
5127};
5128} // end anonymous namespace
5129
5130/// Evaluate an expression of record type as a temporary.
5131static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00005132 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00005133 return TemporaryExprEvaluator(Info, Result).Visit(E);
5134}
5135
5136//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00005137// Vector Evaluation
5138//===----------------------------------------------------------------------===//
5139
5140namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005141 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00005142 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
5143 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00005144 public:
Mike Stump1eb44332009-09-09 15:08:12 +00005145
Richard Smith07fc6572011-10-22 21:10:00 +00005146 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5147 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00005148
Richard Smith07fc6572011-10-22 21:10:00 +00005149 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
5150 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5151 // FIXME: remove this APValue copy.
5152 Result = APValue(V.data(), V.size());
5153 return true;
5154 }
Richard Smith1aa0be82012-03-03 22:46:17 +00005155 bool Success(const APValue &V, const Expr *E) {
Richard Smith69c2c502011-11-04 05:33:44 +00005156 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00005157 Result = V;
5158 return true;
5159 }
Richard Smith51201882011-12-30 21:15:51 +00005160 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00005161
Richard Smith07fc6572011-10-22 21:10:00 +00005162 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00005163 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00005164 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00005165 bool VisitInitListExpr(const InitListExpr *E);
5166 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00005167 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00005168 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00005169 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00005170 };
5171} // end anonymous namespace
5172
5173static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005174 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00005175 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00005176}
5177
Richard Smith07fc6572011-10-22 21:10:00 +00005178bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5179 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00005180 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00005181
Richard Smithd62ca372011-12-06 22:44:34 +00005182 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00005183 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00005184
Eli Friedman46a52322011-03-25 00:43:55 +00005185 switch (E->getCastKind()) {
5186 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00005187 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00005188 if (SETy->isIntegerType()) {
5189 APSInt IntResult;
5190 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00005191 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00005192 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00005193 } else if (SETy->isRealFloatingType()) {
5194 APFloat F(0.0);
5195 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00005196 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00005197 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00005198 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00005199 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005200 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00005201
5202 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00005203 SmallVector<APValue, 4> Elts(NElts, Val);
5204 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00005205 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00005206 case CK_BitCast: {
5207 // Evaluate the operand into an APInt we can extract from.
5208 llvm::APInt SValInt;
5209 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5210 return false;
5211 // Extract the elements
5212 QualType EltTy = VTy->getElementType();
5213 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5214 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5215 SmallVector<APValue, 4> Elts;
5216 if (EltTy->isRealFloatingType()) {
5217 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedmane6a24e82011-12-22 03:51:45 +00005218 unsigned FloatEltSize = EltSize;
5219 if (&Sem == &APFloat::x87DoubleExtended)
5220 FloatEltSize = 80;
5221 for (unsigned i = 0; i < NElts; i++) {
5222 llvm::APInt Elt;
5223 if (BigEndian)
5224 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5225 else
5226 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover9ec55f22013-01-22 09:46:51 +00005227 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedmane6a24e82011-12-22 03:51:45 +00005228 }
5229 } else if (EltTy->isIntegerType()) {
5230 for (unsigned i = 0; i < NElts; i++) {
5231 llvm::APInt Elt;
5232 if (BigEndian)
5233 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5234 else
5235 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5236 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5237 }
5238 } else {
5239 return Error(E);
5240 }
5241 return Success(Elts, E);
5242 }
Eli Friedman46a52322011-03-25 00:43:55 +00005243 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005244 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005245 }
Nate Begeman59b5da62009-01-18 03:20:47 +00005246}
5247
Richard Smith07fc6572011-10-22 21:10:00 +00005248bool
Nate Begeman59b5da62009-01-18 03:20:47 +00005249VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00005250 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00005251 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00005252 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00005253
Nate Begeman59b5da62009-01-18 03:20:47 +00005254 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00005255 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00005256
Eli Friedman3edd5a92012-01-03 23:24:20 +00005257 // The number of initializers can be less than the number of
5258 // vector elements. For OpenCL, this can be due to nested vector
5259 // initialization. For GCC compatibility, missing trailing elements
5260 // should be initialized with zeroes.
5261 unsigned CountInits = 0, CountElts = 0;
5262 while (CountElts < NumElements) {
5263 // Handle nested vector initialization.
5264 if (CountInits < NumInits
Eli Friedman69b65152013-09-17 04:07:02 +00005265 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedman3edd5a92012-01-03 23:24:20 +00005266 APValue v;
5267 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5268 return Error(E);
5269 unsigned vlen = v.getVectorLength();
5270 for (unsigned j = 0; j < vlen; j++)
5271 Elements.push_back(v.getVectorElt(j));
5272 CountElts += vlen;
5273 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00005274 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00005275 if (CountInits < NumInits) {
5276 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00005277 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00005278 } else // trailing integer zero.
5279 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5280 Elements.push_back(APValue(sInt));
5281 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00005282 } else {
5283 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00005284 if (CountInits < NumInits) {
5285 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00005286 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00005287 } else // trailing float zero.
5288 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5289 Elements.push_back(APValue(f));
5290 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00005291 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00005292 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00005293 }
Richard Smith07fc6572011-10-22 21:10:00 +00005294 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00005295}
5296
Richard Smith07fc6572011-10-22 21:10:00 +00005297bool
Richard Smith51201882011-12-30 21:15:51 +00005298VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00005299 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00005300 QualType EltTy = VT->getElementType();
5301 APValue ZeroElement;
5302 if (EltTy->isIntegerType())
5303 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5304 else
5305 ZeroElement =
5306 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5307
Chris Lattner5f9e2722011-07-23 10:55:15 +00005308 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00005309 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00005310}
5311
Richard Smith07fc6572011-10-22 21:10:00 +00005312bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00005313 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00005314 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00005315}
5316
Nate Begeman59b5da62009-01-18 03:20:47 +00005317//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00005318// Array Evaluation
5319//===----------------------------------------------------------------------===//
5320
5321namespace {
5322 class ArrayExprEvaluator
5323 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00005324 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00005325 APValue &Result;
5326 public:
5327
Richard Smith180f4792011-11-10 06:34:14 +00005328 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5329 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00005330
5331 bool Success(const APValue &V, const Expr *E) {
Richard Smithf3908f22012-02-17 03:35:37 +00005332 assert((V.isArray() || V.isLValue()) &&
5333 "expected array or string literal");
Richard Smithcc5d4f62011-11-07 09:22:26 +00005334 Result = V;
5335 return true;
5336 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00005337
Richard Smith51201882011-12-30 21:15:51 +00005338 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005339 const ConstantArrayType *CAT =
5340 Info.Ctx.getAsConstantArrayType(E->getType());
5341 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005342 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00005343
5344 Result = APValue(APValue::UninitArray(), 0,
5345 CAT->getSize().getZExtValue());
5346 if (!Result.hasArrayFiller()) return true;
5347
Richard Smith51201882011-12-30 21:15:51 +00005348 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00005349 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00005350 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00005351 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00005352 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith180f4792011-11-10 06:34:14 +00005353 }
5354
Richard Smithcc5d4f62011-11-07 09:22:26 +00005355 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00005356 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith99ad3592013-04-22 14:44:29 +00005357 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5358 const LValue &Subobject,
5359 APValue *Value, QualType Type);
Richard Smithcc5d4f62011-11-07 09:22:26 +00005360 };
5361} // end anonymous namespace
5362
Richard Smith180f4792011-11-10 06:34:14 +00005363static bool EvaluateArray(const Expr *E, const LValue &This,
5364 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00005365 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00005366 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00005367}
5368
5369bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5370 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5371 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005372 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00005373
Richard Smith974c5f92011-12-22 01:07:19 +00005374 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5375 // an appropriately-typed string literal enclosed in braces.
Richard Smithfe587202012-04-15 02:50:59 +00005376 if (E->isStringLiteralInit()) {
Richard Smith974c5f92011-12-22 01:07:19 +00005377 LValue LV;
5378 if (!EvaluateLValue(E->getInit(0), LV, Info))
5379 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00005380 APValue Val;
Richard Smithf3908f22012-02-17 03:35:37 +00005381 LV.moveInto(Val);
5382 return Success(Val, E);
Richard Smith974c5f92011-12-22 01:07:19 +00005383 }
5384
Richard Smith745f5142012-01-27 01:14:48 +00005385 bool Success = true;
5386
Richard Smithde31aa72012-07-07 22:48:24 +00005387 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5388 "zero-initialized array shouldn't have any initialized elts");
5389 APValue Filler;
5390 if (Result.isArray() && Result.hasArrayFiller())
5391 Filler = Result.getArrayFiller();
5392
Richard Smith99ad3592013-04-22 14:44:29 +00005393 unsigned NumEltsToInit = E->getNumInits();
5394 unsigned NumElts = CAT->getSize().getZExtValue();
5395 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
5396
5397 // If the initializer might depend on the array index, run it for each
5398 // array element. For now, just whitelist non-class value-initialization.
5399 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5400 NumEltsToInit = NumElts;
5401
5402 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smithde31aa72012-07-07 22:48:24 +00005403
5404 // If the array was previously zero-initialized, preserve the
5405 // zero-initialized values.
5406 if (!Filler.isUninit()) {
5407 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5408 Result.getArrayInitializedElt(I) = Filler;
5409 if (Result.hasArrayFiller())
5410 Result.getArrayFiller() = Filler;
5411 }
5412
Richard Smith180f4792011-11-10 06:34:14 +00005413 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00005414 Subobject.addArray(Info, E, CAT);
Richard Smith99ad3592013-04-22 14:44:29 +00005415 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5416 const Expr *Init =
5417 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smith83587db2012-02-15 02:18:13 +00005418 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith99ad3592013-04-22 14:44:29 +00005419 Info, Subobject, Init) ||
5420 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith745f5142012-01-27 01:14:48 +00005421 CAT->getElementType(), 1)) {
5422 if (!Info.keepEvaluatingAfterFailure())
5423 return false;
5424 Success = false;
5425 }
Richard Smith180f4792011-11-10 06:34:14 +00005426 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00005427
Richard Smith99ad3592013-04-22 14:44:29 +00005428 if (!Result.hasArrayFiller())
5429 return Success;
5430
5431 // If we get here, we have a trivial filler, which we can just evaluate
5432 // once and splat over the rest of the array elements.
5433 assert(FillerExpr && "no array filler for incomplete init list");
5434 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5435 FillerExpr) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00005436}
5437
Richard Smithe24f5fc2011-11-17 22:56:20 +00005438bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith99ad3592013-04-22 14:44:29 +00005439 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5440}
Richard Smithde31aa72012-07-07 22:48:24 +00005441
Richard Smith99ad3592013-04-22 14:44:29 +00005442bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5443 const LValue &Subobject,
5444 APValue *Value,
5445 QualType Type) {
5446 bool HadZeroInit = !Value->isUninit();
5447
5448 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5449 unsigned N = CAT->getSize().getZExtValue();
5450
5451 // Preserve the array filler if we had prior zero-initialization.
5452 APValue Filler =
5453 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5454 : APValue();
5455
5456 *Value = APValue(APValue::UninitArray(), N, N);
5457
5458 if (HadZeroInit)
5459 for (unsigned I = 0; I != N; ++I)
5460 Value->getArrayInitializedElt(I) = Filler;
5461
5462 // Initialize the elements.
5463 LValue ArrayElt = Subobject;
5464 ArrayElt.addArray(Info, E, CAT);
5465 for (unsigned I = 0; I != N; ++I)
5466 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5467 CAT->getElementType()) ||
5468 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5469 CAT->getElementType(), 1))
5470 return false;
5471
5472 return true;
Richard Smithde31aa72012-07-07 22:48:24 +00005473 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00005474
Richard Smith99ad3592013-04-22 14:44:29 +00005475 if (!Type->isRecordType())
Richard Smitha4334df2012-07-10 22:12:55 +00005476 return Error(E);
5477
Richard Smithe24f5fc2011-11-17 22:56:20 +00005478 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00005479
Richard Smith51201882011-12-30 21:15:51 +00005480 bool ZeroInit = E->requiresZeroInitialization();
5481 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00005482 if (HadZeroInit)
5483 return true;
5484
Richard Smith51201882011-12-30 21:15:51 +00005485 if (ZeroInit) {
Richard Smith99ad3592013-04-22 14:44:29 +00005486 ImplicitValueInitExpr VIE(Type);
Richard Smithde31aa72012-07-07 22:48:24 +00005487 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00005488 }
5489
Richard Smith61802452011-12-22 02:22:31 +00005490 const CXXRecordDecl *RD = FD->getParent();
5491 if (RD->isUnion())
Richard Smithde31aa72012-07-07 22:48:24 +00005492 *Value = APValue((FieldDecl*)0);
Richard Smith61802452011-12-22 02:22:31 +00005493 else
Richard Smithde31aa72012-07-07 22:48:24 +00005494 *Value =
Richard Smith61802452011-12-22 02:22:31 +00005495 APValue(APValue::UninitStruct(), RD->getNumBases(),
5496 std::distance(RD->field_begin(), RD->field_end()));
5497 return true;
5498 }
5499
Richard Smithe24f5fc2011-11-17 22:56:20 +00005500 const FunctionDecl *Definition = 0;
5501 FD->getBody(Definition);
5502
Richard Smithc1c5f272011-12-13 06:39:58 +00005503 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5504 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00005505
Richard Smithec789162012-01-12 18:54:33 +00005506 if (ZeroInit && !HadZeroInit) {
Richard Smith99ad3592013-04-22 14:44:29 +00005507 ImplicitValueInitExpr VIE(Type);
Richard Smithde31aa72012-07-07 22:48:24 +00005508 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00005509 return false;
5510 }
5511
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005512 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00005513 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00005514 cast<CXXConstructorDecl>(Definition),
Richard Smithde31aa72012-07-07 22:48:24 +00005515 Info, *Value);
Richard Smithe24f5fc2011-11-17 22:56:20 +00005516}
5517
Richard Smithcc5d4f62011-11-07 09:22:26 +00005518//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005519// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00005520//
5521// As a GNU extension, we support casting pointers to sufficiently-wide integer
5522// types and back in constant folding. Integer values are thus represented
5523// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005524//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005525
5526namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005527class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005528 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith1aa0be82012-03-03 22:46:17 +00005529 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00005530public:
Richard Smith1aa0be82012-03-03 22:46:17 +00005531 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005532 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005533
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00005534 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00005535 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00005536 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00005537 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00005538 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00005539 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00005540 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00005541 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00005542 return true;
5543 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00005544 bool Success(const llvm::APSInt &SI, const Expr *E) {
5545 return Success(SI, E, Result);
5546 }
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00005547
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00005548 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00005549 assert(E->getType()->isIntegralOrEnumerationType() &&
5550 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005551 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00005552 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00005553 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00005554 Result.getInt().setIsUnsigned(
5555 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00005556 return true;
5557 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00005558 bool Success(const llvm::APInt &I, const Expr *E) {
5559 return Success(I, E, Result);
5560 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00005561
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00005562 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00005563 assert(E->getType()->isIntegralOrEnumerationType() &&
5564 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00005565 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00005566 return true;
5567 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00005568 bool Success(uint64_t Value, const Expr *E) {
5569 return Success(Value, E, Result);
5570 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00005571
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005572 bool Success(CharUnits Size, const Expr *E) {
5573 return Success(Size.getQuantity(), E);
5574 }
5575
Richard Smith1aa0be82012-03-03 22:46:17 +00005576 bool Success(const APValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00005577 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00005578 Result = V;
5579 return true;
5580 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005581 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00005582 }
Mike Stump1eb44332009-09-09 15:08:12 +00005583
Richard Smith51201882011-12-30 21:15:51 +00005584 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00005585
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005586 //===--------------------------------------------------------------------===//
5587 // Visitor Methods
5588 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00005589
Chris Lattner4c4867e2008-07-12 00:38:25 +00005590 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00005591 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00005592 }
5593 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00005594 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00005595 }
Eli Friedman04309752009-11-24 05:28:59 +00005596
5597 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5598 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005599 if (CheckReferencedDecl(E, E->getDecl()))
5600 return true;
5601
5602 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00005603 }
5604 bool VisitMemberExpr(const MemberExpr *E) {
5605 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00005606 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00005607 return true;
5608 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005609
5610 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00005611 }
5612
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005613 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00005614 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005615 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00005616 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00005617
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005618 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005619 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00005620
Anders Carlsson3068d112008-11-16 19:01:22 +00005621 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00005622 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00005623 }
Mike Stump1eb44332009-09-09 15:08:12 +00005624
Ted Kremenekebcb57a2012-03-06 20:05:56 +00005625 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5626 return Success(E->getValue(), E);
5627 }
5628
Richard Smithf10d9172011-10-11 21:43:33 +00005629 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00005630 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00005631 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00005632 }
5633
Sebastian Redl64b45f72009-01-05 20:52:13 +00005634 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00005635 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00005636 }
5637
Francois Pichet6ad6f282010-12-07 00:08:36 +00005638 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
5639 return Success(E->getValue(), E);
5640 }
5641
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00005642 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5643 return Success(E->getValue(), E);
5644 }
5645
John Wiegley21ff2e52011-04-28 00:16:57 +00005646 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5647 return Success(E->getValue(), E);
5648 }
5649
John Wiegley55262202011-04-25 06:54:41 +00005650 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5651 return Success(E->getValue(), E);
5652 }
5653
Eli Friedman722c7172009-02-28 03:59:05 +00005654 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00005655 bool VisitUnaryImag(const UnaryOperator *E);
5656
Sebastian Redl295995c2010-09-10 20:55:47 +00005657 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00005658 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00005659
Chris Lattnerfcee0012008-07-11 21:24:13 +00005660private:
Ken Dyck8b752f12010-01-27 17:10:57 +00005661 CharUnits GetAlignOfExpr(const Expr *E);
5662 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005663 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005664 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00005665 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005666};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005667} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00005668
Richard Smithc49bd112011-10-28 17:51:58 +00005669/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
5670/// produce either the integer value or a pointer.
5671///
5672/// GCC has a heinous extension which folds casts between pointer types and
5673/// pointer-sized integral types. We support this by allowing the evaluation of
5674/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
5675/// Some simple arithmetic on such values is supported (they are treated much
5676/// like char*).
Richard Smith1aa0be82012-03-03 22:46:17 +00005677static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00005678 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005679 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005680 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00005681}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005682
Richard Smithf48fdb02011-12-09 22:58:01 +00005683static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith1aa0be82012-03-03 22:46:17 +00005684 APValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00005685 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00005686 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005687 if (!Val.isInt()) {
5688 // FIXME: It would be better to produce the diagnostic for casting
5689 // a pointer to an integer.
Richard Smith5cfc7d82012-03-15 04:53:45 +00005690 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00005691 return false;
5692 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005693 Result = Val.getInt();
5694 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00005695}
Anders Carlsson650c92f2008-07-08 15:34:11 +00005696
Richard Smithf48fdb02011-12-09 22:58:01 +00005697/// Check whether the given declaration can be directly converted to an integral
5698/// rvalue. If not, no diagnostic is produced; there are other things we can
5699/// try.
Eli Friedman04309752009-11-24 05:28:59 +00005700bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00005701 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00005702 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00005703 // Check for signedness/width mismatches between E type and ECD value.
5704 bool SameSign = (ECD->getInitVal().isSigned()
5705 == E->getType()->isSignedIntegerOrEnumerationType());
5706 bool SameWidth = (ECD->getInitVal().getBitWidth()
5707 == Info.Ctx.getIntWidth(E->getType()));
5708 if (SameSign && SameWidth)
5709 return Success(ECD->getInitVal(), E);
5710 else {
5711 // Get rid of mismatch (otherwise Success assertions will fail)
5712 // by computing a new value matching the type of E.
5713 llvm::APSInt Val = ECD->getInitVal();
5714 if (!SameSign)
5715 Val.setIsSigned(!ECD->getInitVal().isSigned());
5716 if (!SameWidth)
5717 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
5718 return Success(Val, E);
5719 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00005720 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005721 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00005722}
5723
Chris Lattnera4d55d82008-10-06 06:40:35 +00005724/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
5725/// as GCC.
5726static int EvaluateBuiltinClassifyType(const CallExpr *E) {
5727 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005728 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00005729 enum gcc_type_class {
5730 no_type_class = -1,
5731 void_type_class, integer_type_class, char_type_class,
5732 enumeral_type_class, boolean_type_class,
5733 pointer_type_class, reference_type_class, offset_type_class,
5734 real_type_class, complex_type_class,
5735 function_type_class, method_type_class,
5736 record_type_class, union_type_class,
5737 array_type_class, string_type_class,
5738 lang_type_class
5739 };
Mike Stump1eb44332009-09-09 15:08:12 +00005740
5741 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00005742 // ideal, however it is what gcc does.
5743 if (E->getNumArgs() == 0)
5744 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00005745
Chris Lattnera4d55d82008-10-06 06:40:35 +00005746 QualType ArgTy = E->getArg(0)->getType();
5747 if (ArgTy->isVoidType())
5748 return void_type_class;
5749 else if (ArgTy->isEnumeralType())
5750 return enumeral_type_class;
5751 else if (ArgTy->isBooleanType())
5752 return boolean_type_class;
5753 else if (ArgTy->isCharType())
5754 return string_type_class; // gcc doesn't appear to use char_type_class
5755 else if (ArgTy->isIntegerType())
5756 return integer_type_class;
5757 else if (ArgTy->isPointerType())
5758 return pointer_type_class;
5759 else if (ArgTy->isReferenceType())
5760 return reference_type_class;
5761 else if (ArgTy->isRealType())
5762 return real_type_class;
5763 else if (ArgTy->isComplexType())
5764 return complex_type_class;
5765 else if (ArgTy->isFunctionType())
5766 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00005767 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00005768 return record_type_class;
5769 else if (ArgTy->isUnionType())
5770 return union_type_class;
5771 else if (ArgTy->isArrayType())
5772 return array_type_class;
5773 else if (ArgTy->isUnionType())
5774 return union_type_class;
5775 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00005776 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00005777}
5778
Richard Smith80d4b552011-12-28 19:48:30 +00005779/// EvaluateBuiltinConstantPForLValue - Determine the result of
5780/// __builtin_constant_p when applied to the given lvalue.
5781///
5782/// An lvalue is only "constant" if it is a pointer or reference to the first
5783/// character of a string literal.
5784template<typename LValue>
5785static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregor8e55ed12012-03-11 02:23:56 +00005786 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith80d4b552011-12-28 19:48:30 +00005787 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
5788}
5789
5790/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
5791/// GCC as we can manage.
5792static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
5793 QualType ArgType = Arg->getType();
5794
5795 // __builtin_constant_p always has one operand. The rules which gcc follows
5796 // are not precisely documented, but are as follows:
5797 //
5798 // - If the operand is of integral, floating, complex or enumeration type,
5799 // and can be folded to a known value of that type, it returns 1.
5800 // - If the operand and can be folded to a pointer to the first character
5801 // of a string literal (or such a pointer cast to an integral type), it
5802 // returns 1.
5803 //
5804 // Otherwise, it returns 0.
5805 //
5806 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
5807 // its support for this does not currently work.
5808 if (ArgType->isIntegralOrEnumerationType()) {
5809 Expr::EvalResult Result;
5810 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
5811 return false;
5812
5813 APValue &V = Result.Val;
5814 if (V.getKind() == APValue::Int)
5815 return true;
5816
5817 return EvaluateBuiltinConstantPForLValue(V);
5818 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
5819 return Arg->isEvaluatable(Ctx);
5820 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
5821 LValue LV;
5822 Expr::EvalStatus Status;
5823 EvalInfo Info(Ctx, Status);
5824 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
5825 : EvaluatePointer(Arg, LV, Info)) &&
5826 !Status.HasSideEffects)
5827 return EvaluateBuiltinConstantPForLValue(LV);
5828 }
5829
5830 // Anything else isn't considered to be sufficiently constant.
5831 return false;
5832}
5833
John McCall42c8f872010-05-10 23:27:23 +00005834/// Retrieves the "underlying object type" of the given expression,
5835/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005836QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
5837 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
5838 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00005839 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005840 } else if (const Expr *E = B.get<const Expr*>()) {
5841 if (isa<CompoundLiteralExpr>(E))
5842 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00005843 }
5844
5845 return QualType();
5846}
5847
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005848bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00005849 LValue Base;
Richard Smithc6794852012-05-23 04:13:20 +00005850
5851 {
5852 // The operand of __builtin_object_size is never evaluated for side-effects.
5853 // If there are any, but we can determine the pointed-to object anyway, then
5854 // ignore the side-effects.
5855 SpeculativeEvaluationRAII SpeculativeEval(Info);
5856 if (!EvaluatePointer(E->getArg(0), Base, Info))
5857 return false;
5858 }
John McCall42c8f872010-05-10 23:27:23 +00005859
5860 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005861 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00005862
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005863 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00005864 if (T.isNull() ||
5865 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00005866 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00005867 T->isVariablyModifiedType() ||
5868 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00005869 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00005870
5871 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
5872 CharUnits Offset = Base.getLValueOffset();
5873
5874 if (!Offset.isNegative() && Offset <= Size)
5875 Size -= Offset;
5876 else
5877 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005878 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00005879}
5880
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005881bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith2c39d712012-04-13 00:45:38 +00005882 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00005883 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005884 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00005885
5886 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00005887 if (TryEvaluateBuiltinObjectSize(E))
5888 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00005889
Richard Smith8ae4ec22012-08-07 04:16:51 +00005890 // If evaluating the argument has side-effects, we can't determine the size
5891 // of the object, and so we lower it to unknown now. CodeGen relies on us to
5892 // handle all cases where the expression has side-effects.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00005893 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005894 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00005895 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00005896 return Success(0, E);
5897 }
Mike Stumpc4c90452009-10-27 22:09:17 +00005898
Richard Smithc6794852012-05-23 04:13:20 +00005899 // Expression had no side effects, but we couldn't statically determine the
5900 // size of the referenced object.
Richard Smithf48fdb02011-12-09 22:58:01 +00005901 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00005902 }
5903
Benjamin Kramerd1900572012-10-06 14:42:22 +00005904 case Builtin::BI__builtin_bswap16:
Richard Smith70d38f32012-09-28 20:20:52 +00005905 case Builtin::BI__builtin_bswap32:
5906 case Builtin::BI__builtin_bswap64: {
5907 APSInt Val;
5908 if (!EvaluateInteger(E->getArg(0), Val, Info))
5909 return false;
5910
5911 return Success(Val.byteSwap(), E);
5912 }
5913
Richard Smithacaf72a2013-06-13 06:26:32 +00005914 case Builtin::BI__builtin_classify_type:
5915 return Success(EvaluateBuiltinClassifyType(E), E);
5916
5917 // FIXME: BI__builtin_clrsb
5918 // FIXME: BI__builtin_clrsbl
5919 // FIXME: BI__builtin_clrsbll
5920
Richard Smith4dbf4082013-06-13 05:04:16 +00005921 case Builtin::BI__builtin_clz:
5922 case Builtin::BI__builtin_clzl:
5923 case Builtin::BI__builtin_clzll: {
5924 APSInt Val;
5925 if (!EvaluateInteger(E->getArg(0), Val, Info))
5926 return false;
5927 if (!Val)
5928 return Error(E);
5929
5930 return Success(Val.countLeadingZeros(), E);
5931 }
5932
Richard Smithacaf72a2013-06-13 06:26:32 +00005933 case Builtin::BI__builtin_constant_p:
5934 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
5935
Richard Smith4dbf4082013-06-13 05:04:16 +00005936 case Builtin::BI__builtin_ctz:
5937 case Builtin::BI__builtin_ctzl:
5938 case Builtin::BI__builtin_ctzll: {
5939 APSInt Val;
5940 if (!EvaluateInteger(E->getArg(0), Val, Info))
5941 return false;
5942 if (!Val)
5943 return Error(E);
5944
5945 return Success(Val.countTrailingZeros(), E);
5946 }
5947
Richard Smithacaf72a2013-06-13 06:26:32 +00005948 case Builtin::BI__builtin_eh_return_data_regno: {
5949 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
5950 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
5951 return Success(Operand, E);
5952 }
5953
5954 case Builtin::BI__builtin_expect:
5955 return Visit(E->getArg(0));
5956
5957 case Builtin::BI__builtin_ffs:
5958 case Builtin::BI__builtin_ffsl:
5959 case Builtin::BI__builtin_ffsll: {
5960 APSInt Val;
5961 if (!EvaluateInteger(E->getArg(0), Val, Info))
5962 return false;
5963
5964 unsigned N = Val.countTrailingZeros();
5965 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
5966 }
5967
5968 case Builtin::BI__builtin_fpclassify: {
5969 APFloat Val(0.0);
5970 if (!EvaluateFloat(E->getArg(5), Val, Info))
5971 return false;
5972 unsigned Arg;
5973 switch (Val.getCategory()) {
5974 case APFloat::fcNaN: Arg = 0; break;
5975 case APFloat::fcInfinity: Arg = 1; break;
5976 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
5977 case APFloat::fcZero: Arg = 4; break;
5978 }
5979 return Visit(E->getArg(Arg));
5980 }
5981
5982 case Builtin::BI__builtin_isinf_sign: {
5983 APFloat Val(0.0);
Richard Smith5350ded2013-06-13 06:31:13 +00005984 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smithacaf72a2013-06-13 06:26:32 +00005985 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
5986 }
5987
5988 case Builtin::BI__builtin_parity:
5989 case Builtin::BI__builtin_parityl:
5990 case Builtin::BI__builtin_parityll: {
5991 APSInt Val;
5992 if (!EvaluateInteger(E->getArg(0), Val, Info))
5993 return false;
5994
5995 return Success(Val.countPopulation() % 2, E);
5996 }
5997
Richard Smith4dbf4082013-06-13 05:04:16 +00005998 case Builtin::BI__builtin_popcount:
5999 case Builtin::BI__builtin_popcountl:
6000 case Builtin::BI__builtin_popcountll: {
6001 APSInt Val;
6002 if (!EvaluateInteger(E->getArg(0), Val, Info))
6003 return false;
6004
6005 return Success(Val.countPopulation(), E);
6006 }
6007
Douglas Gregor5726d402010-09-10 06:27:15 +00006008 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00006009 // A call to strlen is not a constant expression.
Richard Smith80ad52f2013-01-02 11:42:31 +00006010 if (Info.getLangOpts().CPlusPlus11)
Richard Smith5cfc7d82012-03-15 04:53:45 +00006011 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith40b993a2012-01-18 03:06:12 +00006012 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6013 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00006014 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith40b993a2012-01-18 03:06:12 +00006015 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00006016 case Builtin::BI__builtin_strlen:
6017 // As an extension, we support strlen() and __builtin_strlen() as constant
6018 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00006019 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00006020 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
6021 // The string literal may have embedded null characters. Find the first
6022 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006023 StringRef Str = S->getString();
6024 StringRef::size_type Pos = Str.find(0);
6025 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00006026 Str = Str.substr(0, Pos);
6027
6028 return Success(Str.size(), E);
6029 }
6030
Richard Smithf48fdb02011-12-09 22:58:01 +00006031 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00006032
Richard Smith2c39d712012-04-13 00:45:38 +00006033 case Builtin::BI__atomic_always_lock_free:
Richard Smithfafbf062012-04-11 17:55:32 +00006034 case Builtin::BI__atomic_is_lock_free:
6035 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedman454b57a2011-10-17 21:44:23 +00006036 APSInt SizeVal;
6037 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6038 return false;
6039
6040 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6041 // of two less than the maximum inline atomic width, we know it is
6042 // lock-free. If the size isn't a power of two, or greater than the
6043 // maximum alignment where we promote atomics, we know it is not lock-free
6044 // (at least not in the sense of atomic_is_lock_free). Otherwise,
6045 // the answer can only be determined at runtime; for example, 16-byte
6046 // atomics have lock-free implementations on some, but not all,
6047 // x86-64 processors.
6048
6049 // Check power-of-two.
6050 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith2c39d712012-04-13 00:45:38 +00006051 if (Size.isPowerOfTwo()) {
6052 // Check against inlining width.
6053 unsigned InlineWidthBits =
6054 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6055 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6056 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6057 Size == CharUnits::One() ||
6058 E->getArg(1)->isNullPointerConstant(Info.Ctx,
6059 Expr::NPC_NeverValueDependent))
6060 // OK, we will inline appropriately-aligned operations of this size,
6061 // and _Atomic(T) is appropriately-aligned.
6062 return Success(1, E);
Eli Friedman454b57a2011-10-17 21:44:23 +00006063
Richard Smith2c39d712012-04-13 00:45:38 +00006064 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6065 castAs<PointerType>()->getPointeeType();
6066 if (!PointeeType->isIncompleteType() &&
6067 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6068 // OK, we will inline operations on this object.
6069 return Success(1, E);
6070 }
6071 }
6072 }
Eli Friedman454b57a2011-10-17 21:44:23 +00006073
Richard Smith2c39d712012-04-13 00:45:38 +00006074 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6075 Success(0, E) : Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00006076 }
Chris Lattner019f4e82008-10-06 05:28:25 +00006077 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00006078}
Anders Carlsson650c92f2008-07-08 15:34:11 +00006079
Richard Smith625b8072011-10-31 01:37:14 +00006080static bool HasSameBase(const LValue &A, const LValue &B) {
6081 if (!A.getLValueBase())
6082 return !B.getLValueBase();
6083 if (!B.getLValueBase())
6084 return false;
6085
Richard Smith1bf9a9e2011-11-12 22:28:03 +00006086 if (A.getLValueBase().getOpaqueValue() !=
6087 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00006088 const Decl *ADecl = GetLValueBaseDecl(A);
6089 if (!ADecl)
6090 return false;
6091 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00006092 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00006093 return false;
6094 }
6095
6096 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith83587db2012-02-15 02:18:13 +00006097 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith625b8072011-10-31 01:37:14 +00006098}
6099
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006100namespace {
Richard Smithc49bd112011-10-28 17:51:58 +00006101
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006102/// \brief Data recursive integer evaluator of certain binary operators.
6103///
6104/// We use a data recursive algorithm for binary operators so that we are able
6105/// to handle extreme cases of chained binary operators without causing stack
6106/// overflow.
6107class DataRecursiveIntBinOpEvaluator {
6108 struct EvalResult {
6109 APValue Val;
6110 bool Failed;
6111
6112 EvalResult() : Failed(false) { }
6113
6114 void swap(EvalResult &RHS) {
6115 Val.swap(RHS.Val);
6116 Failed = RHS.Failed;
6117 RHS.Failed = false;
6118 }
6119 };
6120
6121 struct Job {
6122 const Expr *E;
6123 EvalResult LHSResult; // meaningful only for binary operator expression.
6124 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
6125
6126 Job() : StoredInfo(0) { }
6127 void startSpeculativeEval(EvalInfo &Info) {
6128 OldEvalStatus = Info.EvalStatus;
6129 Info.EvalStatus.Diag = 0;
6130 StoredInfo = &Info;
6131 }
6132 ~Job() {
6133 if (StoredInfo) {
6134 StoredInfo->EvalStatus = OldEvalStatus;
6135 }
6136 }
6137 private:
6138 EvalInfo *StoredInfo; // non-null if status changed.
6139 Expr::EvalStatus OldEvalStatus;
6140 };
6141
6142 SmallVector<Job, 16> Queue;
6143
6144 IntExprEvaluator &IntEval;
6145 EvalInfo &Info;
6146 APValue &FinalResult;
6147
6148public:
6149 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
6150 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
6151
6152 /// \brief True if \param E is a binary operator that we are going to handle
6153 /// data recursively.
6154 /// We handle binary operators that are comma, logical, or that have operands
6155 /// with integral or enumeration type.
6156 static bool shouldEnqueue(const BinaryOperator *E) {
6157 return E->getOpcode() == BO_Comma ||
6158 E->isLogicalOp() ||
6159 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6160 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedmana6afa762008-11-13 06:09:17 +00006161 }
6162
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006163 bool Traverse(const BinaryOperator *E) {
6164 enqueue(E);
6165 EvalResult PrevResult;
Richard Trieub7783052012-03-21 23:30:30 +00006166 while (!Queue.empty())
6167 process(PrevResult);
6168
6169 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00006170
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006171 FinalResult.swap(PrevResult.Val);
6172 return true;
6173 }
6174
6175private:
6176 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6177 return IntEval.Success(Value, E, Result);
6178 }
6179 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6180 return IntEval.Success(Value, E, Result);
6181 }
6182 bool Error(const Expr *E) {
6183 return IntEval.Error(E);
6184 }
6185 bool Error(const Expr *E, diag::kind D) {
6186 return IntEval.Error(E, D);
6187 }
6188
6189 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6190 return Info.CCEDiag(E, D);
6191 }
6192
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00006193 // \brief Returns true if visiting the RHS is necessary, false otherwise.
6194 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006195 bool &SuppressRHSDiags);
6196
6197 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6198 const BinaryOperator *E, APValue &Result);
6199
6200 void EvaluateExpr(const Expr *E, EvalResult &Result) {
6201 Result.Failed = !Evaluate(Result.Val, Info, E);
6202 if (Result.Failed)
6203 Result.Val = APValue();
6204 }
6205
Richard Trieub7783052012-03-21 23:30:30 +00006206 void process(EvalResult &Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006207
6208 void enqueue(const Expr *E) {
6209 E = E->IgnoreParens();
6210 Queue.resize(Queue.size()+1);
6211 Queue.back().E = E;
6212 Queue.back().Kind = Job::AnyExprKind;
6213 }
6214};
6215
6216}
6217
6218bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00006219 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006220 bool &SuppressRHSDiags) {
6221 if (E->getOpcode() == BO_Comma) {
6222 // Ignore LHS but note if we could not evaluate it.
6223 if (LHSResult.Failed)
6224 Info.EvalStatus.HasSideEffects = true;
6225 return true;
6226 }
6227
6228 if (E->isLogicalOp()) {
6229 bool lhsResult;
6230 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00006231 // We were able to evaluate the LHS, see if we can get away with not
6232 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006233 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00006234 Success(lhsResult, E, LHSResult.Val);
6235 return false; // Ignore RHS
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00006236 }
6237 } else {
6238 // Since we weren't able to evaluate the left hand side, it
6239 // must have had side effects.
6240 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006241
6242 // We can't evaluate the LHS; however, sometimes the result
6243 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6244 // Don't ignore RHS and suppress diagnostics from this arm.
6245 SuppressRHSDiags = true;
6246 }
6247
6248 return true;
6249 }
6250
6251 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6252 E->getRHS()->getType()->isIntegralOrEnumerationType());
6253
6254 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00006255 return false; // Ignore RHS;
6256
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006257 return true;
6258}
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00006259
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006260bool DataRecursiveIntBinOpEvaluator::
6261 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6262 const BinaryOperator *E, APValue &Result) {
6263 if (E->getOpcode() == BO_Comma) {
6264 if (RHSResult.Failed)
6265 return false;
6266 Result = RHSResult.Val;
6267 return true;
6268 }
6269
6270 if (E->isLogicalOp()) {
6271 bool lhsResult, rhsResult;
6272 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
6273 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
6274
6275 if (LHSIsOK) {
6276 if (RHSIsOK) {
6277 if (E->getOpcode() == BO_LOr)
6278 return Success(lhsResult || rhsResult, E, Result);
6279 else
6280 return Success(lhsResult && rhsResult, E, Result);
6281 }
6282 } else {
6283 if (RHSIsOK) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00006284 // We can't evaluate the LHS; however, sometimes the result
6285 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6286 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006287 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00006288 }
6289 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006290
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00006291 return false;
6292 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006293
6294 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6295 E->getRHS()->getType()->isIntegralOrEnumerationType());
6296
6297 if (LHSResult.Failed || RHSResult.Failed)
6298 return false;
6299
6300 const APValue &LHSVal = LHSResult.Val;
6301 const APValue &RHSVal = RHSResult.Val;
6302
6303 // Handle cases like (unsigned long)&a + 4.
6304 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
6305 Result = LHSVal;
6306 CharUnits AdditionalOffset = CharUnits::fromQuantity(
6307 RHSVal.getInt().getZExtValue());
6308 if (E->getOpcode() == BO_Add)
6309 Result.getLValueOffset() += AdditionalOffset;
6310 else
6311 Result.getLValueOffset() -= AdditionalOffset;
6312 return true;
6313 }
6314
6315 // Handle cases like 4 + (unsigned long)&a
6316 if (E->getOpcode() == BO_Add &&
6317 RHSVal.isLValue() && LHSVal.isInt()) {
6318 Result = RHSVal;
6319 Result.getLValueOffset() += CharUnits::fromQuantity(
6320 LHSVal.getInt().getZExtValue());
6321 return true;
6322 }
6323
6324 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
6325 // Handle (intptr_t)&&A - (intptr_t)&&B.
6326 if (!LHSVal.getLValueOffset().isZero() ||
6327 !RHSVal.getLValueOffset().isZero())
6328 return false;
6329 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
6330 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
6331 if (!LHSExpr || !RHSExpr)
6332 return false;
6333 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6334 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6335 if (!LHSAddrExpr || !RHSAddrExpr)
6336 return false;
6337 // Make sure both labels come from the same function.
6338 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6339 RHSAddrExpr->getLabel()->getDeclContext())
6340 return false;
6341 Result = APValue(LHSAddrExpr, RHSAddrExpr);
6342 return true;
6343 }
Richard Smithd20afcb2013-05-07 04:50:00 +00006344
6345 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006346 if (!LHSVal.isInt() || !RHSVal.isInt())
6347 return Error(E);
Richard Smithd20afcb2013-05-07 04:50:00 +00006348
6349 // Set up the width and signedness manually, in case it can't be deduced
6350 // from the operation we're performing.
6351 // FIXME: Don't do this in the cases where we can deduce it.
6352 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
6353 E->getType()->isUnsignedIntegerOrEnumerationType());
6354 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
6355 RHSVal.getInt(), Value))
6356 return false;
6357 return Success(Value, E, Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006358}
6359
Richard Trieub7783052012-03-21 23:30:30 +00006360void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006361 Job &job = Queue.back();
6362
6363 switch (job.Kind) {
6364 case Job::AnyExprKind: {
6365 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
6366 if (shouldEnqueue(Bop)) {
6367 job.Kind = Job::BinOpKind;
6368 enqueue(Bop->getLHS());
Richard Trieub7783052012-03-21 23:30:30 +00006369 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006370 }
6371 }
6372
6373 EvaluateExpr(job.E, Result);
6374 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00006375 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006376 }
6377
6378 case Job::BinOpKind: {
6379 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006380 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00006381 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006382 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00006383 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006384 }
6385 if (SuppressRHSDiags)
6386 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00006387 job.LHSResult.swap(Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006388 job.Kind = Job::BinOpVisitedLHSKind;
6389 enqueue(Bop->getRHS());
Richard Trieub7783052012-03-21 23:30:30 +00006390 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006391 }
6392
6393 case Job::BinOpVisitedLHSKind: {
6394 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6395 EvalResult RHS;
6396 RHS.swap(Result);
Richard Trieub7783052012-03-21 23:30:30 +00006397 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006398 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00006399 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006400 }
6401 }
6402
6403 llvm_unreachable("Invalid Job::Kind!");
6404}
6405
6406bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6407 if (E->isAssignmentOp())
6408 return Error(E);
6409
6410 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
6411 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00006412
Anders Carlsson286f85e2008-11-16 07:17:21 +00006413 QualType LHSTy = E->getLHS()->getType();
6414 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00006415
6416 if (LHSTy->isAnyComplexType()) {
6417 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00006418 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00006419
Richard Smith745f5142012-01-27 01:14:48 +00006420 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
6421 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00006422 return false;
6423
Richard Smith745f5142012-01-27 01:14:48 +00006424 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00006425 return false;
6426
6427 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006428 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00006429 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00006430 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00006431 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
6432
John McCall2de56d12010-08-25 11:45:40 +00006433 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00006434 return Success((CR_r == APFloat::cmpEqual &&
6435 CR_i == APFloat::cmpEqual), E);
6436 else {
John McCall2de56d12010-08-25 11:45:40 +00006437 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00006438 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00006439 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00006440 CR_r == APFloat::cmpLessThan ||
6441 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00006442 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00006443 CR_i == APFloat::cmpLessThan ||
6444 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00006445 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00006446 } else {
John McCall2de56d12010-08-25 11:45:40 +00006447 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00006448 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
6449 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
6450 else {
John McCall2de56d12010-08-25 11:45:40 +00006451 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00006452 "Invalid compex comparison.");
6453 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
6454 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
6455 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00006456 }
6457 }
Mike Stump1eb44332009-09-09 15:08:12 +00006458
Anders Carlsson286f85e2008-11-16 07:17:21 +00006459 if (LHSTy->isRealFloatingType() &&
6460 RHSTy->isRealFloatingType()) {
6461 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00006462
Richard Smith745f5142012-01-27 01:14:48 +00006463 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
6464 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00006465 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006466
Richard Smith745f5142012-01-27 01:14:48 +00006467 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00006468 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006469
Anders Carlsson286f85e2008-11-16 07:17:21 +00006470 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00006471
Anders Carlsson286f85e2008-11-16 07:17:21 +00006472 switch (E->getOpcode()) {
6473 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00006474 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00006475 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00006476 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00006477 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00006478 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00006479 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00006480 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00006481 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00006482 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00006483 E);
John McCall2de56d12010-08-25 11:45:40 +00006484 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00006485 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00006486 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00006487 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00006488 || CR == APFloat::cmpLessThan
6489 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00006490 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00006491 }
Mike Stump1eb44332009-09-09 15:08:12 +00006492
Eli Friedmanad02d7d2009-04-28 19:17:36 +00006493 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00006494 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00006495 LValue LHSValue, RHSValue;
6496
6497 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6498 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00006499 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00006500
Richard Smith745f5142012-01-27 01:14:48 +00006501 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00006502 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00006503
Richard Smith625b8072011-10-31 01:37:14 +00006504 // Reject differing bases from the normal codepath; we special-case
6505 // comparisons to null.
6506 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00006507 if (E->getOpcode() == BO_Sub) {
6508 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00006509 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6510 return false;
6511 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramer7b2f93c2012-10-03 14:15:39 +00006512 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedman65639282012-01-04 23:13:47 +00006513 if (!LHSExpr || !RHSExpr)
6514 return false;
6515 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6516 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6517 if (!LHSAddrExpr || !RHSAddrExpr)
6518 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00006519 // Make sure both labels come from the same function.
6520 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6521 RHSAddrExpr->getLabel()->getDeclContext())
6522 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00006523 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedman65639282012-01-04 23:13:47 +00006524 return true;
6525 }
Richard Smith9e36b532011-10-31 05:11:32 +00006526 // Inequalities and subtractions between unrelated pointers have
6527 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00006528 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00006529 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00006530 // A constant address may compare equal to the address of a symbol.
6531 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00006532 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00006533 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6534 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00006535 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00006536 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00006537 // distinct addresses. In clang, the result of such a comparison is
6538 // unspecified, so it is not a constant expression. However, we do know
6539 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00006540 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6541 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00006542 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00006543 // We can't tell whether weak symbols will end up pointing to the same
6544 // object.
6545 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00006546 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00006547 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00006548 // (Note that clang defaults to -fmerge-all-constants, which can
6549 // lead to inconsistent results for comparisons involving the address
6550 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00006551 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00006552 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00006553
Richard Smith15efc4d2012-02-01 08:10:20 +00006554 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
6555 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
6556
Richard Smithf15fda02012-02-02 01:16:57 +00006557 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
6558 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
6559
John McCall2de56d12010-08-25 11:45:40 +00006560 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00006561 // C++11 [expr.add]p6:
6562 // Unless both pointers point to elements of the same array object, or
6563 // one past the last element of the array object, the behavior is
6564 // undefined.
6565 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6566 !AreElementsOfSameArray(getType(LHSValue.Base),
6567 LHSDesignator, RHSDesignator))
6568 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
6569
Chris Lattner4992bdd2010-04-20 17:13:14 +00006570 QualType Type = E->getLHS()->getType();
6571 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00006572
Richard Smith180f4792011-11-10 06:34:14 +00006573 CharUnits ElementSize;
Richard Smith74e1ad92012-02-16 02:46:34 +00006574 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smith180f4792011-11-10 06:34:14 +00006575 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00006576
Richard Smith812d6bc2013-09-10 21:34:14 +00006577 // As an extension, a type may have zero size (empty struct or union in
6578 // C, array of zero length). Pointer subtraction in such cases has
6579 // undefined behavior, so is not constant.
6580 if (ElementSize.isZero()) {
6581 Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
6582 << ElementType;
6583 return false;
6584 }
6585
Richard Smith15efc4d2012-02-01 08:10:20 +00006586 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
6587 // and produce incorrect results when it overflows. Such behavior
6588 // appears to be non-conforming, but is common, so perhaps we should
6589 // assume the standard intended for such cases to be undefined behavior
6590 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00006591
Richard Smith15efc4d2012-02-01 08:10:20 +00006592 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
6593 // overflow in the final conversion to ptrdiff_t.
6594 APSInt LHS(
6595 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
6596 APSInt RHS(
6597 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
6598 APSInt ElemSize(
6599 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
6600 APSInt TrueResult = (LHS - RHS) / ElemSize;
6601 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
6602
6603 if (Result.extend(65) != TrueResult)
6604 HandleOverflow(Info, E, TrueResult, E->getType());
6605 return Success(Result, E);
6606 }
Richard Smith82f28582012-01-31 06:41:30 +00006607
6608 // C++11 [expr.rel]p3:
6609 // Pointers to void (after pointer conversions) can be compared, with a
6610 // result defined as follows: If both pointers represent the same
6611 // address or are both the null pointer value, the result is true if the
6612 // operator is <= or >= and false otherwise; otherwise the result is
6613 // unspecified.
6614 // We interpret this as applying to pointers to *cv* void.
6615 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00006616 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00006617 CCEDiag(E, diag::note_constexpr_void_comparison);
6618
Richard Smithf15fda02012-02-02 01:16:57 +00006619 // C++11 [expr.rel]p2:
6620 // - If two pointers point to non-static data members of the same object,
6621 // or to subobjects or array elements fo such members, recursively, the
6622 // pointer to the later declared member compares greater provided the
6623 // two members have the same access control and provided their class is
6624 // not a union.
6625 // [...]
6626 // - Otherwise pointer comparisons are unspecified.
6627 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6628 E->isRelationalOp()) {
6629 bool WasArrayIndex;
6630 unsigned Mismatch =
6631 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
6632 RHSDesignator, WasArrayIndex);
6633 // At the point where the designators diverge, the comparison has a
6634 // specified value if:
6635 // - we are comparing array indices
6636 // - we are comparing fields of a union, or fields with the same access
6637 // Otherwise, the result is unspecified and thus the comparison is not a
6638 // constant expression.
6639 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
6640 Mismatch < RHSDesignator.Entries.size()) {
6641 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
6642 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
6643 if (!LF && !RF)
6644 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
6645 else if (!LF)
6646 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6647 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
6648 << RF->getParent() << RF;
6649 else if (!RF)
6650 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6651 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
6652 << LF->getParent() << LF;
6653 else if (!LF->getParent()->isUnion() &&
6654 LF->getAccess() != RF->getAccess())
6655 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
6656 << LF << LF->getAccess() << RF << RF->getAccess()
6657 << LF->getParent();
6658 }
6659 }
6660
Eli Friedmana3169882012-04-16 04:30:08 +00006661 // The comparison here must be unsigned, and performed with the same
6662 // width as the pointer.
Eli Friedmana3169882012-04-16 04:30:08 +00006663 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
6664 uint64_t CompareLHS = LHSOffset.getQuantity();
6665 uint64_t CompareRHS = RHSOffset.getQuantity();
6666 assert(PtrSize <= 64 && "Unexpected pointer width");
6667 uint64_t Mask = ~0ULL >> (64 - PtrSize);
6668 CompareLHS &= Mask;
6669 CompareRHS &= Mask;
6670
Eli Friedman28503762012-04-16 19:23:57 +00006671 // If there is a base and this is a relational operator, we can only
6672 // compare pointers within the object in question; otherwise, the result
6673 // depends on where the object is located in memory.
6674 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
6675 QualType BaseTy = getType(LHSValue.Base);
6676 if (BaseTy->isIncompleteType())
6677 return Error(E);
6678 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
6679 uint64_t OffsetLimit = Size.getQuantity();
6680 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
6681 return Error(E);
6682 }
6683
Richard Smith625b8072011-10-31 01:37:14 +00006684 switch (E->getOpcode()) {
6685 default: llvm_unreachable("missing comparison operator");
Eli Friedmana3169882012-04-16 04:30:08 +00006686 case BO_LT: return Success(CompareLHS < CompareRHS, E);
6687 case BO_GT: return Success(CompareLHS > CompareRHS, E);
6688 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
6689 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
6690 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
6691 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00006692 }
Anders Carlsson3068d112008-11-16 19:01:22 +00006693 }
6694 }
Richard Smithb02e4622012-02-01 01:42:44 +00006695
6696 if (LHSTy->isMemberPointerType()) {
6697 assert(E->isEqualityOp() && "unexpected member pointer operation");
6698 assert(RHSTy->isMemberPointerType() && "invalid comparison");
6699
6700 MemberPtr LHSValue, RHSValue;
6701
6702 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
6703 if (!LHSOK && Info.keepEvaluatingAfterFailure())
6704 return false;
6705
6706 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6707 return false;
6708
6709 // C++11 [expr.eq]p2:
6710 // If both operands are null, they compare equal. Otherwise if only one is
6711 // null, they compare unequal.
6712 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
6713 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
6714 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6715 }
6716
6717 // Otherwise if either is a pointer to a virtual member function, the
6718 // result is unspecified.
6719 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
6720 if (MD->isVirtual())
6721 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6722 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
6723 if (MD->isVirtual())
6724 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6725
6726 // Otherwise they compare equal if and only if they would refer to the
6727 // same member of the same most derived object or the same subobject if
6728 // they were dereferenced with a hypothetical object of the associated
6729 // class type.
6730 bool Equal = LHSValue == RHSValue;
6731 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6732 }
6733
Richard Smith26f2cac2012-02-14 22:35:28 +00006734 if (LHSTy->isNullPtrType()) {
6735 assert(E->isComparisonOp() && "unexpected nullptr operation");
6736 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
6737 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
6738 // are compared, the result is true of the operator is <=, >= or ==, and
6739 // false otherwise.
6740 BinaryOperator::Opcode Opcode = E->getOpcode();
6741 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
6742 }
6743
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00006744 assert((!LHSTy->isIntegralOrEnumerationType() ||
6745 !RHSTy->isIntegralOrEnumerationType()) &&
6746 "DataRecursiveIntBinOpEvaluator should have handled integral types");
6747 // We can't continue from here for non-integral types.
6748 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00006749}
6750
Ken Dyck8b752f12010-01-27 17:10:57 +00006751CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00006752 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
6753 // result shall be the alignment of the referenced type."
6754 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6755 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00006756
6757 // __alignof is defined to return the preferred alignment.
6758 return Info.Ctx.toCharUnitsFromBits(
6759 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00006760}
6761
Ken Dyck8b752f12010-01-27 17:10:57 +00006762CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00006763 E = E->IgnoreParens();
6764
John McCall10f6f062013-05-06 07:40:34 +00006765 // The kinds of expressions that we have special-case logic here for
6766 // should be kept up to date with the special checks for those
6767 // expressions in Sema.
6768
Chris Lattneraf707ab2009-01-24 21:53:27 +00006769 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00006770 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00006771 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00006772 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6773 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00006774
Chris Lattneraf707ab2009-01-24 21:53:27 +00006775 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00006776 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6777 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00006778
Chris Lattnere9feb472009-01-24 21:09:06 +00006779 return GetAlignOfType(E->getType());
6780}
6781
6782
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006783/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
6784/// a result as the expression's type.
6785bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
6786 const UnaryExprOrTypeTraitExpr *E) {
6787 switch(E->getKind()) {
6788 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00006789 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00006790 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00006791 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00006792 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00006793 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00006794
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006795 case UETT_VecStep: {
6796 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00006797
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006798 if (Ty->isVectorType()) {
Ted Kremenek890f0f12012-08-23 20:46:57 +00006799 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00006800
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006801 // The vec_step built-in functions that take a 3-component
6802 // vector return 4. (OpenCL 1.1 spec 6.11.12)
6803 if (n == 3)
6804 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00006805
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006806 return Success(n, E);
6807 } else
6808 return Success(1, E);
6809 }
6810
6811 case UETT_SizeOf: {
6812 QualType SrcTy = E->getTypeOfArgument();
6813 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
6814 // the result is the size of the referenced type."
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006815 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
6816 SrcTy = Ref->getPointeeType();
6817
Richard Smith180f4792011-11-10 06:34:14 +00006818 CharUnits Sizeof;
Richard Smith74e1ad92012-02-16 02:46:34 +00006819 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006820 return false;
Richard Smith180f4792011-11-10 06:34:14 +00006821 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006822 }
6823 }
6824
6825 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00006826}
6827
Peter Collingbourne8cad3042011-05-13 03:29:01 +00006828bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006829 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00006830 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006831 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00006832 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00006833 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006834 for (unsigned i = 0; i != n; ++i) {
6835 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
6836 switch (ON.getKind()) {
6837 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00006838 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006839 APSInt IdxResult;
6840 if (!EvaluateInteger(Idx, IdxResult, Info))
6841 return false;
6842 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
6843 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00006844 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006845 CurrentType = AT->getElementType();
6846 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
6847 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smitha49a7fe2013-05-07 23:34:45 +00006848 break;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006849 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006850
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006851 case OffsetOfExpr::OffsetOfNode::Field: {
6852 FieldDecl *MemberDecl = ON.getField();
6853 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00006854 if (!RT)
6855 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006856 RecordDecl *RD = RT->getDecl();
John McCall8d59dee2012-05-01 00:38:49 +00006857 if (RD->isInvalidDecl()) return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006858 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00006859 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00006860 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00006861 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006862 CurrentType = MemberDecl->getType().getNonReferenceType();
6863 break;
6864 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006865
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006866 case OffsetOfExpr::OffsetOfNode::Identifier:
6867 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00006868
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00006869 case OffsetOfExpr::OffsetOfNode::Base: {
6870 CXXBaseSpecifier *BaseSpec = ON.getBase();
6871 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00006872 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00006873
6874 // Find the layout of the class whose base we are looking into.
6875 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00006876 if (!RT)
6877 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00006878 RecordDecl *RD = RT->getDecl();
John McCall8d59dee2012-05-01 00:38:49 +00006879 if (RD->isInvalidDecl()) return false;
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00006880 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
6881
6882 // Find the base class itself.
6883 CurrentType = BaseSpec->getType();
6884 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
6885 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00006886 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00006887
6888 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00006889 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00006890 break;
6891 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006892 }
6893 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00006894 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006895}
6896
Chris Lattnerb542afe2008-07-11 19:10:17 +00006897bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00006898 switch (E->getOpcode()) {
6899 default:
6900 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
6901 // See C99 6.6p3.
6902 return Error(E);
6903 case UO_Extension:
6904 // FIXME: Should extension allow i-c-e extension expressions in its scope?
6905 // If so, we could clear the diagnostic ID.
6906 return Visit(E->getSubExpr());
6907 case UO_Plus:
6908 // The result is just the value.
6909 return Visit(E->getSubExpr());
6910 case UO_Minus: {
6911 if (!Visit(E->getSubExpr()))
6912 return false;
6913 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00006914 const APSInt &Value = Result.getInt();
6915 if (Value.isSigned() && Value.isMinSignedValue())
6916 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
6917 E->getType());
6918 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00006919 }
6920 case UO_Not: {
6921 if (!Visit(E->getSubExpr()))
6922 return false;
6923 if (!Result.isInt()) return Error(E);
6924 return Success(~Result.getInt(), E);
6925 }
6926 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00006927 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00006928 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00006929 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00006930 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00006931 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00006932 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00006933}
Mike Stump1eb44332009-09-09 15:08:12 +00006934
Chris Lattner732b2232008-07-12 01:15:53 +00006935/// HandleCast - This is used to evaluate implicit or explicit casts where the
6936/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00006937bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
6938 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00006939 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00006940 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00006941
Eli Friedman46a52322011-03-25 00:43:55 +00006942 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00006943 case CK_BaseToDerived:
6944 case CK_DerivedToBase:
6945 case CK_UncheckedDerivedToBase:
6946 case CK_Dynamic:
6947 case CK_ToUnion:
6948 case CK_ArrayToPointerDecay:
6949 case CK_FunctionToPointerDecay:
6950 case CK_NullToPointer:
6951 case CK_NullToMemberPointer:
6952 case CK_BaseToDerivedMemberPointer:
6953 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00006954 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00006955 case CK_ConstructorConversion:
6956 case CK_IntegralToPointer:
6957 case CK_ToVoid:
6958 case CK_VectorSplat:
6959 case CK_IntegralToFloating:
6960 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00006961 case CK_CPointerToObjCPointerCast:
6962 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00006963 case CK_AnyPointerToBlockPointerCast:
6964 case CK_ObjCObjectLValueCast:
6965 case CK_FloatingRealToComplex:
6966 case CK_FloatingComplexToReal:
6967 case CK_FloatingComplexCast:
6968 case CK_FloatingComplexToIntegralComplex:
6969 case CK_IntegralRealToComplex:
6970 case CK_IntegralComplexCast:
6971 case CK_IntegralComplexToFloatingComplex:
Eli Friedmana6c66ce2012-08-31 00:14:07 +00006972 case CK_BuiltinFnToFnPtr:
Guy Benyeie6b9d802013-01-20 12:31:11 +00006973 case CK_ZeroToOCLEvent:
Richard Smith5705f212013-05-23 00:30:41 +00006974 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00006975 llvm_unreachable("invalid cast kind for integral value");
6976
Eli Friedmane50c2972011-03-25 19:07:11 +00006977 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00006978 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00006979 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00006980 case CK_ARCProduceObject:
6981 case CK_ARCConsumeObject:
6982 case CK_ARCReclaimReturnedObject:
6983 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00006984 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00006985 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00006986
Richard Smith7d580a42012-01-17 21:17:26 +00006987 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00006988 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006989 case CK_AtomicToNonAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00006990 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00006991 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00006992
6993 case CK_MemberPointerToBoolean:
6994 case CK_PointerToBoolean:
6995 case CK_IntegralToBoolean:
6996 case CK_FloatingToBoolean:
6997 case CK_FloatingComplexToBoolean:
6998 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00006999 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00007000 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00007001 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00007002 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00007003 }
7004
Eli Friedman46a52322011-03-25 00:43:55 +00007005 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00007006 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00007007 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00007008
Eli Friedmanbe265702009-02-20 01:15:07 +00007009 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00007010 // Allow casts of address-of-label differences if they are no-ops
7011 // or narrowing. (The narrowing case isn't actually guaranteed to
7012 // be constant-evaluatable except in some narrow cases which are hard
7013 // to detect here. We let it through on the assumption the user knows
7014 // what they are doing.)
7015 if (Result.isAddrLabelDiff())
7016 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00007017 // Only allow casts of lvalues if they are lossless.
7018 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
7019 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00007020
Richard Smithf72fccf2012-01-30 22:27:01 +00007021 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
7022 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00007023 }
Mike Stump1eb44332009-09-09 15:08:12 +00007024
Eli Friedman46a52322011-03-25 00:43:55 +00007025 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00007026 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7027
John McCallefdb83e2010-05-07 21:00:08 +00007028 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00007029 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00007030 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00007031
Daniel Dunbardd211642009-02-19 22:24:01 +00007032 if (LV.getLValueBase()) {
7033 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00007034 // FIXME: Allow a larger integer size than the pointer size, and allow
7035 // narrowing back down to pointer width in subsequent integral casts.
7036 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00007037 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00007038 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00007039
Richard Smithb755a9d2011-11-16 07:18:12 +00007040 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00007041 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00007042 return true;
7043 }
7044
Ken Dycka7305832010-01-15 12:37:54 +00007045 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
7046 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00007047 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00007048 }
Eli Friedman4efaa272008-11-12 09:44:48 +00007049
Eli Friedman46a52322011-03-25 00:43:55 +00007050 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00007051 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00007052 if (!EvaluateComplex(SubExpr, C, Info))
7053 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00007054 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00007055 }
Eli Friedman2217c872009-02-22 11:46:18 +00007056
Eli Friedman46a52322011-03-25 00:43:55 +00007057 case CK_FloatingToIntegral: {
7058 APFloat F(0.0);
7059 if (!EvaluateFloat(SubExpr, F, Info))
7060 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00007061
Richard Smithc1c5f272011-12-13 06:39:58 +00007062 APSInt Value;
7063 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7064 return false;
7065 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00007066 }
7067 }
Mike Stump1eb44332009-09-09 15:08:12 +00007068
Eli Friedman46a52322011-03-25 00:43:55 +00007069 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00007070}
Anders Carlsson2bad1682008-07-08 14:30:00 +00007071
Eli Friedman722c7172009-02-28 03:59:05 +00007072bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7073 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00007074 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00007075 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7076 return false;
7077 if (!LV.isComplexInt())
7078 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00007079 return Success(LV.getComplexIntReal(), E);
7080 }
7081
7082 return Visit(E->getSubExpr());
7083}
7084
Eli Friedman664a1042009-02-27 04:45:43 +00007085bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00007086 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00007087 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00007088 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7089 return false;
7090 if (!LV.isComplexInt())
7091 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00007092 return Success(LV.getComplexIntImag(), E);
7093 }
7094
Richard Smith8327fad2011-10-24 18:44:57 +00007095 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00007096 return Success(0, E);
7097}
7098
Douglas Gregoree8aff02011-01-04 17:33:58 +00007099bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
7100 return Success(E->getPackLength(), E);
7101}
7102
Sebastian Redl295995c2010-09-10 20:55:47 +00007103bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
7104 return Success(E->getValue(), E);
7105}
7106
Chris Lattnerf5eeb052008-07-11 18:11:29 +00007107//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00007108// Float Evaluation
7109//===----------------------------------------------------------------------===//
7110
7111namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00007112class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00007113 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00007114 APFloat &Result;
7115public:
7116 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00007117 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00007118
Richard Smith1aa0be82012-03-03 22:46:17 +00007119 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00007120 Result = V.getFloat();
7121 return true;
7122 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00007123
Richard Smith51201882011-12-30 21:15:51 +00007124 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00007125 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
7126 return true;
7127 }
7128
Chris Lattner019f4e82008-10-06 05:28:25 +00007129 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00007130
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00007131 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00007132 bool VisitBinaryOperator(const BinaryOperator *E);
7133 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00007134 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00007135
John McCallabd3a852010-05-07 22:08:54 +00007136 bool VisitUnaryReal(const UnaryOperator *E);
7137 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00007138
Richard Smith51201882011-12-30 21:15:51 +00007139 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00007140};
7141} // end anonymous namespace
7142
7143static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00007144 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00007145 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00007146}
7147
Jay Foad4ba2a172011-01-12 09:06:06 +00007148static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00007149 QualType ResultTy,
7150 const Expr *Arg,
7151 bool SNaN,
7152 llvm::APFloat &Result) {
7153 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
7154 if (!S) return false;
7155
7156 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
7157
7158 llvm::APInt fill;
7159
7160 // Treat empty strings as if they were zero.
7161 if (S->getString().empty())
7162 fill = llvm::APInt(32, 0);
7163 else if (S->getString().getAsInteger(0, fill))
7164 return false;
7165
7166 if (SNaN)
7167 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7168 else
7169 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7170 return true;
7171}
7172
Chris Lattner019f4e82008-10-06 05:28:25 +00007173bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00007174 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00007175 default:
7176 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7177
Chris Lattner019f4e82008-10-06 05:28:25 +00007178 case Builtin::BI__builtin_huge_val:
7179 case Builtin::BI__builtin_huge_valf:
7180 case Builtin::BI__builtin_huge_vall:
7181 case Builtin::BI__builtin_inf:
7182 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00007183 case Builtin::BI__builtin_infl: {
7184 const llvm::fltSemantics &Sem =
7185 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00007186 Result = llvm::APFloat::getInf(Sem);
7187 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00007188 }
Mike Stump1eb44332009-09-09 15:08:12 +00007189
John McCalldb7b72a2010-02-28 13:00:19 +00007190 case Builtin::BI__builtin_nans:
7191 case Builtin::BI__builtin_nansf:
7192 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00007193 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7194 true, Result))
7195 return Error(E);
7196 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00007197
Chris Lattner9e621712008-10-06 06:31:58 +00007198 case Builtin::BI__builtin_nan:
7199 case Builtin::BI__builtin_nanf:
7200 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00007201 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00007202 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00007203 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7204 false, Result))
7205 return Error(E);
7206 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00007207
7208 case Builtin::BI__builtin_fabs:
7209 case Builtin::BI__builtin_fabsf:
7210 case Builtin::BI__builtin_fabsl:
7211 if (!EvaluateFloat(E->getArg(0), Result, Info))
7212 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00007213
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00007214 if (Result.isNegative())
7215 Result.changeSign();
7216 return true;
7217
Richard Smithacaf72a2013-06-13 06:26:32 +00007218 // FIXME: Builtin::BI__builtin_powi
7219 // FIXME: Builtin::BI__builtin_powif
7220 // FIXME: Builtin::BI__builtin_powil
7221
Mike Stump1eb44332009-09-09 15:08:12 +00007222 case Builtin::BI__builtin_copysign:
7223 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00007224 case Builtin::BI__builtin_copysignl: {
7225 APFloat RHS(0.);
7226 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
7227 !EvaluateFloat(E->getArg(1), RHS, Info))
7228 return false;
7229 Result.copySign(RHS);
7230 return true;
7231 }
Chris Lattner019f4e82008-10-06 05:28:25 +00007232 }
7233}
7234
John McCallabd3a852010-05-07 22:08:54 +00007235bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00007236 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7237 ComplexValue CV;
7238 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7239 return false;
7240 Result = CV.FloatReal;
7241 return true;
7242 }
7243
7244 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00007245}
7246
7247bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00007248 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7249 ComplexValue CV;
7250 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7251 return false;
7252 Result = CV.FloatImag;
7253 return true;
7254 }
7255
Richard Smith8327fad2011-10-24 18:44:57 +00007256 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00007257 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
7258 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00007259 return true;
7260}
7261
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00007262bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00007263 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00007264 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00007265 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00007266 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00007267 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00007268 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
7269 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00007270 Result.changeSign();
7271 return true;
7272 }
7273}
Chris Lattner019f4e82008-10-06 05:28:25 +00007274
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00007275bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00007276 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7277 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00007278
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00007279 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00007280 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
7281 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00007282 return false;
Richard Smitha49a7fe2013-05-07 23:34:45 +00007283 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
7284 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00007285}
7286
7287bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
7288 Result = E->getValue();
7289 return true;
7290}
7291
Peter Collingbourne8cad3042011-05-13 03:29:01 +00007292bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
7293 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00007294
Eli Friedman2a523ee2011-03-25 00:54:52 +00007295 switch (E->getCastKind()) {
7296 default:
Richard Smithc49bd112011-10-28 17:51:58 +00007297 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00007298
7299 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00007300 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00007301 return EvaluateInteger(SubExpr, IntResult, Info) &&
7302 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
7303 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00007304 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00007305
7306 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00007307 if (!Visit(SubExpr))
7308 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00007309 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
7310 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00007311 }
John McCallf3ea8cf2010-11-14 08:17:51 +00007312
Eli Friedman2a523ee2011-03-25 00:54:52 +00007313 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00007314 ComplexValue V;
7315 if (!EvaluateComplex(SubExpr, V, Info))
7316 return false;
7317 Result = V.getComplexFloatReal();
7318 return true;
7319 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00007320 }
Eli Friedman4efaa272008-11-12 09:44:48 +00007321}
7322
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00007323//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00007324// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00007325//===----------------------------------------------------------------------===//
7326
7327namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00007328class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00007329 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00007330 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00007331
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00007332public:
John McCallf4cf1a12010-05-07 17:22:02 +00007333 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00007334 : ExprEvaluatorBaseTy(info), Result(Result) {}
7335
Richard Smith1aa0be82012-03-03 22:46:17 +00007336 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00007337 Result.setFrom(V);
7338 return true;
7339 }
Mike Stump1eb44332009-09-09 15:08:12 +00007340
Eli Friedman7ead5c72012-01-10 04:58:17 +00007341 bool ZeroInitialization(const Expr *E);
7342
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00007343 //===--------------------------------------------------------------------===//
7344 // Visitor Methods
7345 //===--------------------------------------------------------------------===//
7346
Peter Collingbourne8cad3042011-05-13 03:29:01 +00007347 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00007348 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00007349 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00007350 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00007351 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00007352};
7353} // end anonymous namespace
7354
John McCallf4cf1a12010-05-07 17:22:02 +00007355static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
7356 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00007357 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00007358 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00007359}
7360
Eli Friedman7ead5c72012-01-10 04:58:17 +00007361bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek890f0f12012-08-23 20:46:57 +00007362 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00007363 if (ElemTy->isRealFloatingType()) {
7364 Result.makeComplexFloat();
7365 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
7366 Result.FloatReal = Zero;
7367 Result.FloatImag = Zero;
7368 } else {
7369 Result.makeComplexInt();
7370 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
7371 Result.IntReal = Zero;
7372 Result.IntImag = Zero;
7373 }
7374 return true;
7375}
7376
Peter Collingbourne8cad3042011-05-13 03:29:01 +00007377bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
7378 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00007379
7380 if (SubExpr->getType()->isRealFloatingType()) {
7381 Result.makeComplexFloat();
7382 APFloat &Imag = Result.FloatImag;
7383 if (!EvaluateFloat(SubExpr, Imag, Info))
7384 return false;
7385
7386 Result.FloatReal = APFloat(Imag.getSemantics());
7387 return true;
7388 } else {
7389 assert(SubExpr->getType()->isIntegerType() &&
7390 "Unexpected imaginary literal.");
7391
7392 Result.makeComplexInt();
7393 APSInt &Imag = Result.IntImag;
7394 if (!EvaluateInteger(SubExpr, Imag, Info))
7395 return false;
7396
7397 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
7398 return true;
7399 }
7400}
7401
Peter Collingbourne8cad3042011-05-13 03:29:01 +00007402bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00007403
John McCall8786da72010-12-14 17:51:41 +00007404 switch (E->getCastKind()) {
7405 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00007406 case CK_BaseToDerived:
7407 case CK_DerivedToBase:
7408 case CK_UncheckedDerivedToBase:
7409 case CK_Dynamic:
7410 case CK_ToUnion:
7411 case CK_ArrayToPointerDecay:
7412 case CK_FunctionToPointerDecay:
7413 case CK_NullToPointer:
7414 case CK_NullToMemberPointer:
7415 case CK_BaseToDerivedMemberPointer:
7416 case CK_DerivedToBaseMemberPointer:
7417 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00007418 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00007419 case CK_ConstructorConversion:
7420 case CK_IntegralToPointer:
7421 case CK_PointerToIntegral:
7422 case CK_PointerToBoolean:
7423 case CK_ToVoid:
7424 case CK_VectorSplat:
7425 case CK_IntegralCast:
7426 case CK_IntegralToBoolean:
7427 case CK_IntegralToFloating:
7428 case CK_FloatingToIntegral:
7429 case CK_FloatingToBoolean:
7430 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00007431 case CK_CPointerToObjCPointerCast:
7432 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00007433 case CK_AnyPointerToBlockPointerCast:
7434 case CK_ObjCObjectLValueCast:
7435 case CK_FloatingComplexToReal:
7436 case CK_FloatingComplexToBoolean:
7437 case CK_IntegralComplexToReal:
7438 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00007439 case CK_ARCProduceObject:
7440 case CK_ARCConsumeObject:
7441 case CK_ARCReclaimReturnedObject:
7442 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00007443 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedmana6c66ce2012-08-31 00:14:07 +00007444 case CK_BuiltinFnToFnPtr:
Guy Benyeie6b9d802013-01-20 12:31:11 +00007445 case CK_ZeroToOCLEvent:
Richard Smith5705f212013-05-23 00:30:41 +00007446 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00007447 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00007448
John McCall8786da72010-12-14 17:51:41 +00007449 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00007450 case CK_AtomicToNonAtomic:
John McCall8786da72010-12-14 17:51:41 +00007451 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00007452 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00007453
7454 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00007455 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00007456 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00007457 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00007458
7459 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00007460 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00007461 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00007462 return false;
7463
John McCall8786da72010-12-14 17:51:41 +00007464 Result.makeComplexFloat();
7465 Result.FloatImag = APFloat(Real.getSemantics());
7466 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00007467 }
7468
John McCall8786da72010-12-14 17:51:41 +00007469 case CK_FloatingComplexCast: {
7470 if (!Visit(E->getSubExpr()))
7471 return false;
7472
7473 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7474 QualType From
7475 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7476
Richard Smithc1c5f272011-12-13 06:39:58 +00007477 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
7478 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00007479 }
7480
7481 case CK_FloatingComplexToIntegralComplex: {
7482 if (!Visit(E->getSubExpr()))
7483 return false;
7484
7485 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7486 QualType From
7487 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7488 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00007489 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
7490 To, Result.IntReal) &&
7491 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
7492 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00007493 }
7494
7495 case CK_IntegralRealToComplex: {
7496 APSInt &Real = Result.IntReal;
7497 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
7498 return false;
7499
7500 Result.makeComplexInt();
7501 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
7502 return true;
7503 }
7504
7505 case CK_IntegralComplexCast: {
7506 if (!Visit(E->getSubExpr()))
7507 return false;
7508
7509 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7510 QualType From
7511 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7512
Richard Smithf72fccf2012-01-30 22:27:01 +00007513 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7514 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00007515 return true;
7516 }
7517
7518 case CK_IntegralComplexToFloatingComplex: {
7519 if (!Visit(E->getSubExpr()))
7520 return false;
7521
Ted Kremenek890f0f12012-08-23 20:46:57 +00007522 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00007523 QualType From
Ted Kremenek890f0f12012-08-23 20:46:57 +00007524 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00007525 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00007526 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7527 To, Result.FloatReal) &&
7528 HandleIntToFloatCast(Info, E, From, Result.IntImag,
7529 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00007530 }
7531 }
7532
7533 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00007534}
7535
John McCallf4cf1a12010-05-07 17:22:02 +00007536bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00007537 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00007538 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7539
Richard Smith745f5142012-01-27 01:14:48 +00007540 bool LHSOK = Visit(E->getLHS());
7541 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00007542 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00007543
John McCallf4cf1a12010-05-07 17:22:02 +00007544 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00007545 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00007546 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00007547
Daniel Dunbar3f279872009-01-29 01:32:56 +00007548 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
7549 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00007550 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00007551 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00007552 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00007553 if (Result.isComplexFloat()) {
7554 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
7555 APFloat::rmNearestTiesToEven);
7556 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
7557 APFloat::rmNearestTiesToEven);
7558 } else {
7559 Result.getComplexIntReal() += RHS.getComplexIntReal();
7560 Result.getComplexIntImag() += RHS.getComplexIntImag();
7561 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00007562 break;
John McCall2de56d12010-08-25 11:45:40 +00007563 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00007564 if (Result.isComplexFloat()) {
7565 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
7566 APFloat::rmNearestTiesToEven);
7567 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
7568 APFloat::rmNearestTiesToEven);
7569 } else {
7570 Result.getComplexIntReal() -= RHS.getComplexIntReal();
7571 Result.getComplexIntImag() -= RHS.getComplexIntImag();
7572 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00007573 break;
John McCall2de56d12010-08-25 11:45:40 +00007574 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00007575 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00007576 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00007577 APFloat &LHS_r = LHS.getComplexFloatReal();
7578 APFloat &LHS_i = LHS.getComplexFloatImag();
7579 APFloat &RHS_r = RHS.getComplexFloatReal();
7580 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00007581
Daniel Dunbar3f279872009-01-29 01:32:56 +00007582 APFloat Tmp = LHS_r;
7583 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7584 Result.getComplexFloatReal() = Tmp;
7585 Tmp = LHS_i;
7586 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7587 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
7588
7589 Tmp = LHS_r;
7590 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7591 Result.getComplexFloatImag() = Tmp;
7592 Tmp = LHS_i;
7593 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7594 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
7595 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00007596 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00007597 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00007598 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
7599 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00007600 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00007601 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
7602 LHS.getComplexIntImag() * RHS.getComplexIntReal());
7603 }
7604 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00007605 case BO_Div:
7606 if (Result.isComplexFloat()) {
7607 ComplexValue LHS = Result;
7608 APFloat &LHS_r = LHS.getComplexFloatReal();
7609 APFloat &LHS_i = LHS.getComplexFloatImag();
7610 APFloat &RHS_r = RHS.getComplexFloatReal();
7611 APFloat &RHS_i = RHS.getComplexFloatImag();
7612 APFloat &Res_r = Result.getComplexFloatReal();
7613 APFloat &Res_i = Result.getComplexFloatImag();
7614
7615 APFloat Den = RHS_r;
7616 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7617 APFloat Tmp = RHS_i;
7618 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7619 Den.add(Tmp, APFloat::rmNearestTiesToEven);
7620
7621 Res_r = LHS_r;
7622 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7623 Tmp = LHS_i;
7624 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7625 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
7626 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
7627
7628 Res_i = LHS_i;
7629 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7630 Tmp = LHS_r;
7631 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7632 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
7633 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
7634 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00007635 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
7636 return Error(E, diag::note_expr_divide_by_zero);
7637
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00007638 ComplexValue LHS = Result;
7639 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
7640 RHS.getComplexIntImag() * RHS.getComplexIntImag();
7641 Result.getComplexIntReal() =
7642 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
7643 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
7644 Result.getComplexIntImag() =
7645 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
7646 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
7647 }
7648 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00007649 }
7650
John McCallf4cf1a12010-05-07 17:22:02 +00007651 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00007652}
7653
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00007654bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7655 // Get the operand value into 'Result'.
7656 if (!Visit(E->getSubExpr()))
7657 return false;
7658
7659 switch (E->getOpcode()) {
7660 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00007661 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00007662 case UO_Extension:
7663 return true;
7664 case UO_Plus:
7665 // The result is always just the subexpr.
7666 return true;
7667 case UO_Minus:
7668 if (Result.isComplexFloat()) {
7669 Result.getComplexFloatReal().changeSign();
7670 Result.getComplexFloatImag().changeSign();
7671 }
7672 else {
7673 Result.getComplexIntReal() = -Result.getComplexIntReal();
7674 Result.getComplexIntImag() = -Result.getComplexIntImag();
7675 }
7676 return true;
7677 case UO_Not:
7678 if (Result.isComplexFloat())
7679 Result.getComplexFloatImag().changeSign();
7680 else
7681 Result.getComplexIntImag() = -Result.getComplexIntImag();
7682 return true;
7683 }
7684}
7685
Eli Friedman7ead5c72012-01-10 04:58:17 +00007686bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7687 if (E->getNumInits() == 2) {
7688 if (E->getType()->isComplexType()) {
7689 Result.makeComplexFloat();
7690 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
7691 return false;
7692 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
7693 return false;
7694 } else {
7695 Result.makeComplexInt();
7696 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
7697 return false;
7698 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
7699 return false;
7700 }
7701 return true;
7702 }
7703 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
7704}
7705
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00007706//===----------------------------------------------------------------------===//
Richard Smith5705f212013-05-23 00:30:41 +00007707// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
7708// implicit conversion.
7709//===----------------------------------------------------------------------===//
7710
7711namespace {
7712class AtomicExprEvaluator :
7713 public ExprEvaluatorBase<AtomicExprEvaluator, bool> {
7714 APValue &Result;
7715public:
7716 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
7717 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7718
7719 bool Success(const APValue &V, const Expr *E) {
7720 Result = V;
7721 return true;
7722 }
7723
7724 bool ZeroInitialization(const Expr *E) {
7725 ImplicitValueInitExpr VIE(
7726 E->getType()->castAs<AtomicType>()->getValueType());
7727 return Evaluate(Result, Info, &VIE);
7728 }
7729
7730 bool VisitCastExpr(const CastExpr *E) {
7731 switch (E->getCastKind()) {
7732 default:
7733 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7734 case CK_NonAtomicToAtomic:
7735 return Evaluate(Result, Info, E->getSubExpr());
7736 }
7737 }
7738};
7739} // end anonymous namespace
7740
7741static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
7742 assert(E->isRValue() && E->getType()->isAtomicType());
7743 return AtomicExprEvaluator(Info, Result).Visit(E);
7744}
7745
7746//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00007747// Void expression evaluation, primarily for a cast to void on the LHS of a
7748// comma operator
7749//===----------------------------------------------------------------------===//
7750
7751namespace {
7752class VoidExprEvaluator
7753 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
7754public:
7755 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
7756
Richard Smith1aa0be82012-03-03 22:46:17 +00007757 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00007758
7759 bool VisitCastExpr(const CastExpr *E) {
7760 switch (E->getCastKind()) {
7761 default:
7762 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7763 case CK_ToVoid:
7764 VisitIgnoredValue(E->getSubExpr());
7765 return true;
7766 }
7767 }
7768};
7769} // end anonymous namespace
7770
7771static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
7772 assert(E->isRValue() && E->getType()->isVoidType());
7773 return VoidExprEvaluator(Info).Visit(E);
7774}
7775
7776//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00007777// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00007778//===----------------------------------------------------------------------===//
7779
Richard Smith1aa0be82012-03-03 22:46:17 +00007780static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00007781 // In C, function designators are not lvalues, but we evaluate them as if they
7782 // are.
Richard Smith5705f212013-05-23 00:30:41 +00007783 QualType T = E->getType();
7784 if (E->isGLValue() || T->isFunctionType()) {
Richard Smithc49bd112011-10-28 17:51:58 +00007785 LValue LV;
7786 if (!EvaluateLValue(E, LV, Info))
7787 return false;
7788 LV.moveInto(Result);
Richard Smith5705f212013-05-23 00:30:41 +00007789 } else if (T->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00007790 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00007791 return false;
Richard Smith5705f212013-05-23 00:30:41 +00007792 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00007793 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00007794 return false;
Richard Smith5705f212013-05-23 00:30:41 +00007795 } else if (T->hasPointerRepresentation()) {
John McCallefdb83e2010-05-07 21:00:08 +00007796 LValue LV;
7797 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00007798 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00007799 LV.moveInto(Result);
Richard Smith5705f212013-05-23 00:30:41 +00007800 } else if (T->isRealFloatingType()) {
John McCallefdb83e2010-05-07 21:00:08 +00007801 llvm::APFloat F(0.0);
7802 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00007803 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00007804 Result = APValue(F);
Richard Smith5705f212013-05-23 00:30:41 +00007805 } else if (T->isAnyComplexType()) {
John McCallefdb83e2010-05-07 21:00:08 +00007806 ComplexValue C;
7807 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00007808 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00007809 C.moveInto(Result);
Richard Smith5705f212013-05-23 00:30:41 +00007810 } else if (T->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00007811 MemberPtr P;
7812 if (!EvaluateMemberPointer(E, P, Info))
7813 return false;
7814 P.moveInto(Result);
7815 return true;
Richard Smith5705f212013-05-23 00:30:41 +00007816 } else if (T->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00007817 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00007818 LV.set(E, Info.CurrentCall->Index);
Richard Smith03ce5f82013-07-24 07:11:57 +00007819 APValue &Value = Info.CurrentCall->createTemporary(E, false);
7820 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00007821 return false;
Richard Smith03ce5f82013-07-24 07:11:57 +00007822 Result = Value;
Richard Smith5705f212013-05-23 00:30:41 +00007823 } else if (T->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00007824 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00007825 LV.set(E, Info.CurrentCall->Index);
Richard Smith03ce5f82013-07-24 07:11:57 +00007826 APValue &Value = Info.CurrentCall->createTemporary(E, false);
7827 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smith180f4792011-11-10 06:34:14 +00007828 return false;
Richard Smith03ce5f82013-07-24 07:11:57 +00007829 Result = Value;
Richard Smith5705f212013-05-23 00:30:41 +00007830 } else if (T->isVoidType()) {
Richard Smith80ad52f2013-01-02 11:42:31 +00007831 if (!Info.getLangOpts().CPlusPlus11)
Richard Smith5cfc7d82012-03-15 04:53:45 +00007832 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smithc1c5f272011-12-13 06:39:58 +00007833 << E->getType();
Richard Smithaa9c3502011-12-07 00:43:50 +00007834 if (!EvaluateVoid(E, Info))
7835 return false;
Richard Smith5705f212013-05-23 00:30:41 +00007836 } else if (T->isAtomicType()) {
7837 if (!EvaluateAtomic(E, Result, Info))
7838 return false;
Richard Smith80ad52f2013-01-02 11:42:31 +00007839 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00007840 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smithc1c5f272011-12-13 06:39:58 +00007841 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00007842 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00007843 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00007844 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00007845 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00007846
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00007847 return true;
7848}
7849
Richard Smith83587db2012-02-15 02:18:13 +00007850/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
7851/// cases, the in-place evaluation is essential, since later initializers for
7852/// an object can indirectly refer to subobjects which were initialized earlier.
7853static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith6391ea22013-05-09 07:14:00 +00007854 const Expr *E, bool AllowNonLiteralTypes) {
7855 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smith51201882011-12-30 21:15:51 +00007856 return false;
7857
7858 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00007859 // Evaluate arrays and record types in-place, so that later initializers can
7860 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00007861 if (E->getType()->isArrayType())
7862 return EvaluateArray(E, This, Result, Info);
7863 else if (E->getType()->isRecordType())
7864 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00007865 }
7866
7867 // For any other type, in-place evaluation is unimportant.
Richard Smith1aa0be82012-03-03 22:46:17 +00007868 return Evaluate(Result, Info, E);
Richard Smith69c2c502011-11-04 05:33:44 +00007869}
7870
Richard Smithf48fdb02011-12-09 22:58:01 +00007871/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
7872/// lvalue-to-rvalue cast if it is an lvalue.
7873static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00007874 if (!CheckLiteralType(Info, E))
7875 return false;
7876
Richard Smith1aa0be82012-03-03 22:46:17 +00007877 if (!::Evaluate(Result, Info, E))
Richard Smithf48fdb02011-12-09 22:58:01 +00007878 return false;
7879
7880 if (E->isGLValue()) {
7881 LValue LV;
Richard Smith1aa0be82012-03-03 22:46:17 +00007882 LV.setFrom(Info.Ctx, Result);
Richard Smith5528ac92013-05-05 23:31:59 +00007883 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00007884 return false;
7885 }
7886
Richard Smith1aa0be82012-03-03 22:46:17 +00007887 // Check this core constant expression is a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +00007888 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf48fdb02011-12-09 22:58:01 +00007889}
Richard Smithc49bd112011-10-28 17:51:58 +00007890
Fariborz Jahanianad48a502013-01-24 22:11:45 +00007891static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
7892 const ASTContext &Ctx, bool &IsConst) {
7893 // Fast-path evaluations of integer literals, since we sometimes see files
7894 // containing vast quantities of these.
7895 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
7896 Result.Val = APValue(APSInt(L->getValue(),
7897 L->getType()->isUnsignedIntegerType()));
7898 IsConst = true;
7899 return true;
7900 }
7901
7902 // FIXME: Evaluating values of large array and record types can cause
7903 // performance problems. Only do so in C++11 for now.
7904 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
7905 Exp->getType()->isRecordType()) &&
7906 !Ctx.getLangOpts().CPlusPlus11) {
7907 IsConst = false;
7908 return true;
7909 }
7910 return false;
7911}
7912
7913
Richard Smith51f47082011-10-29 00:50:52 +00007914/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00007915/// any crazy technique (that has nothing to do with language standards) that
7916/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00007917/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
7918/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00007919bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahanianad48a502013-01-24 22:11:45 +00007920 bool IsConst;
7921 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
7922 return IsConst;
7923
Richard Smithf48fdb02011-12-09 22:58:01 +00007924 EvalInfo Info(Ctx, Result);
7925 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00007926}
7927
Jay Foad4ba2a172011-01-12 09:06:06 +00007928bool Expr::EvaluateAsBooleanCondition(bool &Result,
7929 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00007930 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00007931 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith1aa0be82012-03-03 22:46:17 +00007932 HandleConversionToBool(Scratch.Val, Result);
John McCallcd7a4452010-01-05 23:42:56 +00007933}
7934
Richard Smith80d4b552011-12-28 19:48:30 +00007935bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
7936 SideEffectsKind AllowSideEffects) const {
7937 if (!getType()->isIntegralOrEnumerationType())
7938 return false;
7939
Richard Smithc49bd112011-10-28 17:51:58 +00007940 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00007941 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
7942 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00007943 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00007944
Richard Smithc49bd112011-10-28 17:51:58 +00007945 Result = ExprResult.Val.getInt();
7946 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00007947}
7948
Jay Foad4ba2a172011-01-12 09:06:06 +00007949bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00007950 EvalInfo Info(Ctx, Result);
7951
John McCallefdb83e2010-05-07 21:00:08 +00007952 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00007953 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
7954 !CheckLValueConstantExpression(Info, getExprLoc(),
7955 Ctx.getLValueReferenceType(getType()), LV))
7956 return false;
7957
Richard Smith1aa0be82012-03-03 22:46:17 +00007958 LV.moveInto(Result.Val);
Richard Smith83587db2012-02-15 02:18:13 +00007959 return true;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00007960}
7961
Richard Smith099e7f62011-12-19 06:19:21 +00007962bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
7963 const VarDecl *VD,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00007964 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00007965 // FIXME: Evaluating initializers for large array and record types can cause
7966 // performance problems. Only do so in C++11 for now.
7967 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith80ad52f2013-01-02 11:42:31 +00007968 !Ctx.getLangOpts().CPlusPlus11)
Richard Smith2d6a5672012-01-14 04:30:29 +00007969 return false;
7970
Richard Smith099e7f62011-12-19 06:19:21 +00007971 Expr::EvalStatus EStatus;
7972 EStatus.Diag = &Notes;
7973
7974 EvalInfo InitInfo(Ctx, EStatus);
7975 InitInfo.setEvaluatingDecl(VD, Value);
7976
7977 LValue LVal;
7978 LVal.set(VD);
7979
Richard Smith51201882011-12-30 21:15:51 +00007980 // C++11 [basic.start.init]p2:
7981 // Variables with static storage duration or thread storage duration shall be
7982 // zero-initialized before any other initialization takes place.
7983 // This behavior is not present in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00007984 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smith51201882011-12-30 21:15:51 +00007985 !VD->getType()->isReferenceType()) {
7986 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith6391ea22013-05-09 07:14:00 +00007987 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smith83587db2012-02-15 02:18:13 +00007988 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00007989 return false;
7990 }
7991
Richard Smith6391ea22013-05-09 07:14:00 +00007992 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
7993 /*AllowNonLiteralTypes=*/true) ||
Richard Smith83587db2012-02-15 02:18:13 +00007994 EStatus.HasSideEffects)
7995 return false;
7996
7997 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
7998 Value);
Richard Smith099e7f62011-12-19 06:19:21 +00007999}
8000
Richard Smith51f47082011-10-29 00:50:52 +00008001/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
8002/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00008003bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00008004 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00008005 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00008006}
Anders Carlsson51fe9962008-11-22 21:04:56 +00008007
Fariborz Jahaniana18e70b2013-01-09 23:04:56 +00008008APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008009 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00008010 EvalResult EvalResult;
Fariborz Jahaniana18e70b2013-01-09 23:04:56 +00008011 EvalResult.Diag = Diag;
Richard Smith51f47082011-10-29 00:50:52 +00008012 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00008013 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00008014 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00008015 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00008016
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00008017 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00008018}
John McCalld905f5a2010-05-07 05:32:02 +00008019
Fariborz Jahanianad48a502013-01-24 22:11:45 +00008020void Expr::EvaluateForOverflow(const ASTContext &Ctx,
8021 SmallVectorImpl<PartialDiagnosticAt> *Diags) const {
8022 bool IsConst;
8023 EvalResult EvalResult;
8024 EvalResult.Diag = Diags;
8025 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
8026 EvalInfo Info(Ctx, EvalResult, true);
8027 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
8028 }
8029}
8030
Richard Smith211c8dd2013-06-05 00:46:14 +00008031bool Expr::EvalResult::isGlobalLValue() const {
8032 assert(Val.isLValue());
8033 return IsGlobalLValue(Val.getLValueBase());
8034}
Abramo Bagnarae17a6432010-05-14 17:07:14 +00008035
8036
John McCalld905f5a2010-05-07 05:32:02 +00008037/// isIntegerConstantExpr - this recursive routine will test if an expression is
8038/// an integer constant expression.
8039
8040/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
8041/// comma, etc
John McCalld905f5a2010-05-07 05:32:02 +00008042
8043// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smithceb59d92012-12-28 13:25:52 +00008044// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
8045// and a (possibly null) SourceLocation indicating the location of the problem.
8046//
John McCalld905f5a2010-05-07 05:32:02 +00008047// Note that to reduce code duplication, this helper does no evaluation
8048// itself; the caller checks whether the expression is evaluatable, and
8049// in the rare cases where CheckICE actually cares about the evaluated
8050// value, it calls into Evalute.
John McCalld905f5a2010-05-07 05:32:02 +00008051
Dan Gohman3c46e8d2010-07-26 21:25:24 +00008052namespace {
8053
Richard Smithceb59d92012-12-28 13:25:52 +00008054enum ICEKind {
8055 /// This expression is an ICE.
8056 IK_ICE,
8057 /// This expression is not an ICE, but if it isn't evaluated, it's
8058 /// a legal subexpression for an ICE. This return value is used to handle
8059 /// the comma operator in C99 mode, and non-constant subexpressions.
8060 IK_ICEIfUnevaluated,
8061 /// This expression is not an ICE, and is not a legal subexpression for one.
8062 IK_NotICE
8063};
8064
John McCalld905f5a2010-05-07 05:32:02 +00008065struct ICEDiag {
Richard Smithceb59d92012-12-28 13:25:52 +00008066 ICEKind Kind;
John McCalld905f5a2010-05-07 05:32:02 +00008067 SourceLocation Loc;
8068
Richard Smithceb59d92012-12-28 13:25:52 +00008069 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCalld905f5a2010-05-07 05:32:02 +00008070};
8071
Dan Gohman3c46e8d2010-07-26 21:25:24 +00008072}
8073
Richard Smithceb59d92012-12-28 13:25:52 +00008074static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
8075
8076static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCalld905f5a2010-05-07 05:32:02 +00008077
Craig Topper32b5a1e2013-08-22 07:09:37 +00008078static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCalld905f5a2010-05-07 05:32:02 +00008079 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00008080 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smithceb59d92012-12-28 13:25:52 +00008081 !EVResult.Val.isInt())
8082 return ICEDiag(IK_NotICE, E->getLocStart());
8083
John McCalld905f5a2010-05-07 05:32:02 +00008084 return NoDiag();
8085}
8086
Craig Topper32b5a1e2013-08-22 07:09:37 +00008087static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCalld905f5a2010-05-07 05:32:02 +00008088 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smithceb59d92012-12-28 13:25:52 +00008089 if (!E->getType()->isIntegralOrEnumerationType())
8090 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00008091
8092 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00008093#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00008094#define STMT(Node, Base) case Expr::Node##Class:
8095#define EXPR(Node, Base)
8096#include "clang/AST/StmtNodes.inc"
8097 case Expr::PredefinedExprClass:
8098 case Expr::FloatingLiteralClass:
8099 case Expr::ImaginaryLiteralClass:
8100 case Expr::StringLiteralClass:
8101 case Expr::ArraySubscriptExprClass:
8102 case Expr::MemberExprClass:
8103 case Expr::CompoundAssignOperatorClass:
8104 case Expr::CompoundLiteralExprClass:
8105 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00008106 case Expr::DesignatedInitExprClass:
8107 case Expr::ImplicitValueInitExprClass:
8108 case Expr::ParenListExprClass:
8109 case Expr::VAArgExprClass:
8110 case Expr::AddrLabelExprClass:
8111 case Expr::StmtExprClass:
8112 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00008113 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00008114 case Expr::CXXDynamicCastExprClass:
8115 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00008116 case Expr::CXXUuidofExprClass:
John McCall76da55d2013-04-16 07:28:30 +00008117 case Expr::MSPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00008118 case Expr::CXXNullPtrLiteralExprClass:
Richard Smith9fcce652012-03-07 08:35:16 +00008119 case Expr::UserDefinedLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00008120 case Expr::CXXThisExprClass:
8121 case Expr::CXXThrowExprClass:
8122 case Expr::CXXNewExprClass:
8123 case Expr::CXXDeleteExprClass:
8124 case Expr::CXXPseudoDestructorExprClass:
8125 case Expr::UnresolvedLookupExprClass:
8126 case Expr::DependentScopeDeclRefExprClass:
8127 case Expr::CXXConstructExprClass:
Richard Smith7c3e6152013-06-12 22:31:48 +00008128 case Expr::CXXStdInitializerListExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00008129 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00008130 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00008131 case Expr::CXXTemporaryObjectExprClass:
8132 case Expr::CXXUnresolvedConstructExprClass:
8133 case Expr::CXXDependentScopeMemberExprClass:
8134 case Expr::UnresolvedMemberExprClass:
8135 case Expr::ObjCStringLiteralClass:
Patrick Beardeb382ec2012-04-19 00:25:12 +00008136 case Expr::ObjCBoxedExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00008137 case Expr::ObjCArrayLiteralClass:
8138 case Expr::ObjCDictionaryLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00008139 case Expr::ObjCEncodeExprClass:
8140 case Expr::ObjCMessageExprClass:
8141 case Expr::ObjCSelectorExprClass:
8142 case Expr::ObjCProtocolExprClass:
8143 case Expr::ObjCIvarRefExprClass:
8144 case Expr::ObjCPropertyRefExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00008145 case Expr::ObjCSubscriptRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00008146 case Expr::ObjCIsaExprClass:
8147 case Expr::ShuffleVectorExprClass:
Hal Finkel414a1bd2013-09-18 03:29:45 +00008148 case Expr::ConvertVectorExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00008149 case Expr::BlockExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00008150 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00008151 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00008152 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00008153 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smith9a4db032012-09-12 00:56:43 +00008154 case Expr::FunctionParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00008155 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00008156 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00008157 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00008158 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00008159 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00008160 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00008161 case Expr::LambdaExprClass:
Richard Smithceb59d92012-12-28 13:25:52 +00008162 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redlcea8d962011-09-24 17:48:14 +00008163
Douglas Gregoree8aff02011-01-04 17:33:58 +00008164 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00008165 case Expr::GNUNullExprClass:
8166 // GCC considers the GNU __null value to be an integral constant expression.
8167 return NoDiag();
8168
John McCall91a57552011-07-15 05:09:51 +00008169 case Expr::SubstNonTypeTemplateParmExprClass:
8170 return
8171 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
8172
John McCalld905f5a2010-05-07 05:32:02 +00008173 case Expr::ParenExprClass:
8174 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00008175 case Expr::GenericSelectionExprClass:
8176 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00008177 case Expr::IntegerLiteralClass:
8178 case Expr::CharacterLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00008179 case Expr::ObjCBoolLiteralExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00008180 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00008181 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00008182 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00008183 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00008184 case Expr::TypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00008185 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00008186 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00008187 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00008188 return NoDiag();
8189 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00008190 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00008191 // C99 6.6/3 allows function calls within unevaluated subexpressions of
8192 // constant expressions, but they can never be ICEs because an ICE cannot
8193 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00008194 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00008195 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00008196 return CheckEvalInICE(E, Ctx);
Richard Smithceb59d92012-12-28 13:25:52 +00008197 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00008198 }
Richard Smith359c89d2012-02-24 22:12:32 +00008199 case Expr::DeclRefExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00008200 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
8201 return NoDiag();
Richard Smith359c89d2012-02-24 22:12:32 +00008202 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikie4e4d0842012-03-11 07:00:24 +00008203 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith359c89d2012-02-24 22:12:32 +00008204 D && IsConstNonVolatile(D->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00008205 // Parameter variables are never constants. Without this check,
8206 // getAnyInitializer() can find a default argument, which leads
8207 // to chaos.
8208 if (isa<ParmVarDecl>(D))
Richard Smithceb59d92012-12-28 13:25:52 +00008209 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00008210
8211 // C++ 7.1.5.1p2
8212 // A variable of non-volatile const-qualified integral or enumeration
8213 // type initialized by an ICE can be used in ICEs.
8214 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00008215 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smithceb59d92012-12-28 13:25:52 +00008216 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithdb1822c2011-11-08 01:31:09 +00008217
Richard Smith099e7f62011-12-19 06:19:21 +00008218 const VarDecl *VD;
8219 // Look for a declaration of this variable that has an initializer, and
8220 // check whether it is an ICE.
8221 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
8222 return NoDiag();
8223 else
Richard Smithceb59d92012-12-28 13:25:52 +00008224 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00008225 }
8226 }
Richard Smithceb59d92012-12-28 13:25:52 +00008227 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith359c89d2012-02-24 22:12:32 +00008228 }
John McCalld905f5a2010-05-07 05:32:02 +00008229 case Expr::UnaryOperatorClass: {
8230 const UnaryOperator *Exp = cast<UnaryOperator>(E);
8231 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00008232 case UO_PostInc:
8233 case UO_PostDec:
8234 case UO_PreInc:
8235 case UO_PreDec:
8236 case UO_AddrOf:
8237 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00008238 // C99 6.6/3 allows increment and decrement within unevaluated
8239 // subexpressions of constant expressions, but they can never be ICEs
8240 // because an ICE cannot contain an lvalue operand.
Richard Smithceb59d92012-12-28 13:25:52 +00008241 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00008242 case UO_Extension:
8243 case UO_LNot:
8244 case UO_Plus:
8245 case UO_Minus:
8246 case UO_Not:
8247 case UO_Real:
8248 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00008249 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00008250 }
Richard Smithceb59d92012-12-28 13:25:52 +00008251
John McCalld905f5a2010-05-07 05:32:02 +00008252 // OffsetOf falls through here.
8253 }
8254 case Expr::OffsetOfExprClass: {
Richard Smithceb59d92012-12-28 13:25:52 +00008255 // Note that per C99, offsetof must be an ICE. And AFAIK, using
8256 // EvaluateAsRValue matches the proposed gcc behavior for cases like
8257 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
8258 // compliance: we should warn earlier for offsetof expressions with
8259 // array subscripts that aren't ICEs, and if the array subscripts
8260 // are ICEs, the value of the offsetof must be an integer constant.
8261 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00008262 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00008263 case Expr::UnaryExprOrTypeTraitExprClass: {
8264 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
8265 if ((Exp->getKind() == UETT_SizeOf) &&
8266 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smithceb59d92012-12-28 13:25:52 +00008267 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00008268 return NoDiag();
8269 }
8270 case Expr::BinaryOperatorClass: {
8271 const BinaryOperator *Exp = cast<BinaryOperator>(E);
8272 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00008273 case BO_PtrMemD:
8274 case BO_PtrMemI:
8275 case BO_Assign:
8276 case BO_MulAssign:
8277 case BO_DivAssign:
8278 case BO_RemAssign:
8279 case BO_AddAssign:
8280 case BO_SubAssign:
8281 case BO_ShlAssign:
8282 case BO_ShrAssign:
8283 case BO_AndAssign:
8284 case BO_XorAssign:
8285 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00008286 // C99 6.6/3 allows assignments within unevaluated subexpressions of
8287 // constant expressions, but they can never be ICEs because an ICE cannot
8288 // contain an lvalue operand.
Richard Smithceb59d92012-12-28 13:25:52 +00008289 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00008290
John McCall2de56d12010-08-25 11:45:40 +00008291 case BO_Mul:
8292 case BO_Div:
8293 case BO_Rem:
8294 case BO_Add:
8295 case BO_Sub:
8296 case BO_Shl:
8297 case BO_Shr:
8298 case BO_LT:
8299 case BO_GT:
8300 case BO_LE:
8301 case BO_GE:
8302 case BO_EQ:
8303 case BO_NE:
8304 case BO_And:
8305 case BO_Xor:
8306 case BO_Or:
8307 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00008308 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8309 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00008310 if (Exp->getOpcode() == BO_Div ||
8311 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00008312 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00008313 // we don't evaluate one.
Richard Smithceb59d92012-12-28 13:25:52 +00008314 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008315 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00008316 if (REval == 0)
Richard Smithceb59d92012-12-28 13:25:52 +00008317 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00008318 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008319 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00008320 if (LEval.isMinSignedValue())
Richard Smithceb59d92012-12-28 13:25:52 +00008321 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00008322 }
8323 }
8324 }
John McCall2de56d12010-08-25 11:45:40 +00008325 if (Exp->getOpcode() == BO_Comma) {
David Blaikie4e4d0842012-03-11 07:00:24 +00008326 if (Ctx.getLangOpts().C99) {
John McCalld905f5a2010-05-07 05:32:02 +00008327 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
8328 // if it isn't evaluated.
Richard Smithceb59d92012-12-28 13:25:52 +00008329 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
8330 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00008331 } else {
8332 // In both C89 and C++, commas in ICEs are illegal.
Richard Smithceb59d92012-12-28 13:25:52 +00008333 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00008334 }
8335 }
Richard Smithceb59d92012-12-28 13:25:52 +00008336 return Worst(LHSResult, RHSResult);
John McCalld905f5a2010-05-07 05:32:02 +00008337 }
John McCall2de56d12010-08-25 11:45:40 +00008338 case BO_LAnd:
8339 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00008340 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8341 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smithceb59d92012-12-28 13:25:52 +00008342 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCalld905f5a2010-05-07 05:32:02 +00008343 // Rare case where the RHS has a comma "side-effect"; we need
8344 // to actually check the condition to see whether the side
8345 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00008346 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008347 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00008348 return RHSResult;
8349 return NoDiag();
8350 }
8351
Richard Smithceb59d92012-12-28 13:25:52 +00008352 return Worst(LHSResult, RHSResult);
John McCalld905f5a2010-05-07 05:32:02 +00008353 }
8354 }
8355 }
8356 case Expr::ImplicitCastExprClass:
8357 case Expr::CStyleCastExprClass:
8358 case Expr::CXXFunctionalCastExprClass:
8359 case Expr::CXXStaticCastExprClass:
8360 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00008361 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00008362 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00008363 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00008364 if (isa<ExplicitCastExpr>(E)) {
8365 if (const FloatingLiteral *FL
8366 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
8367 unsigned DestWidth = Ctx.getIntWidth(E->getType());
8368 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
8369 APSInt IgnoredVal(DestWidth, !DestSigned);
8370 bool Ignored;
8371 // If the value does not fit in the destination type, the behavior is
8372 // undefined, so we are not required to treat it as a constant
8373 // expression.
8374 if (FL->getValue().convertToInteger(IgnoredVal,
8375 llvm::APFloat::rmTowardZero,
8376 &Ignored) & APFloat::opInvalidOp)
Richard Smithceb59d92012-12-28 13:25:52 +00008377 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith2116b142011-12-18 02:33:09 +00008378 return NoDiag();
8379 }
8380 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00008381 switch (cast<CastExpr>(E)->getCastKind()) {
8382 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00008383 case CK_AtomicToNonAtomic:
8384 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00008385 case CK_NoOp:
8386 case CK_IntegralToBoolean:
8387 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00008388 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00008389 default:
Richard Smithceb59d92012-12-28 13:25:52 +00008390 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedmaneea0e812011-09-29 21:49:34 +00008391 }
John McCalld905f5a2010-05-07 05:32:02 +00008392 }
John McCall56ca35d2011-02-17 10:25:35 +00008393 case Expr::BinaryConditionalOperatorClass: {
8394 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
8395 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smithceb59d92012-12-28 13:25:52 +00008396 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCall56ca35d2011-02-17 10:25:35 +00008397 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smithceb59d92012-12-28 13:25:52 +00008398 if (FalseResult.Kind == IK_NotICE) return FalseResult;
8399 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
8400 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith9b403c52012-12-28 12:53:55 +00008401 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00008402 return FalseResult;
8403 }
John McCalld905f5a2010-05-07 05:32:02 +00008404 case Expr::ConditionalOperatorClass: {
8405 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
8406 // If the condition (ignoring parens) is a __builtin_constant_p call,
8407 // then only the true side is actually considered in an integer constant
8408 // expression, and it is fully evaluated. This is an important GNU
8409 // extension. See GCC PR38377 for discussion.
8410 if (const CallExpr *CallCE
8411 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00008412 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
8413 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00008414 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smithceb59d92012-12-28 13:25:52 +00008415 if (CondResult.Kind == IK_NotICE)
John McCalld905f5a2010-05-07 05:32:02 +00008416 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00008417
Richard Smithf48fdb02011-12-09 22:58:01 +00008418 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
8419 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00008420
Richard Smithceb59d92012-12-28 13:25:52 +00008421 if (TrueResult.Kind == IK_NotICE)
John McCalld905f5a2010-05-07 05:32:02 +00008422 return TrueResult;
Richard Smithceb59d92012-12-28 13:25:52 +00008423 if (FalseResult.Kind == IK_NotICE)
John McCalld905f5a2010-05-07 05:32:02 +00008424 return FalseResult;
Richard Smithceb59d92012-12-28 13:25:52 +00008425 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCalld905f5a2010-05-07 05:32:02 +00008426 return CondResult;
Richard Smithceb59d92012-12-28 13:25:52 +00008427 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCalld905f5a2010-05-07 05:32:02 +00008428 return NoDiag();
8429 // Rare case where the diagnostics depend on which side is evaluated
8430 // Note that if we get here, CondResult is 0, and at least one of
8431 // TrueResult and FalseResult is non-zero.
Richard Smithceb59d92012-12-28 13:25:52 +00008432 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCalld905f5a2010-05-07 05:32:02 +00008433 return FalseResult;
John McCalld905f5a2010-05-07 05:32:02 +00008434 return TrueResult;
8435 }
8436 case Expr::CXXDefaultArgExprClass:
8437 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smithc3bf52c2013-04-20 22:23:05 +00008438 case Expr::CXXDefaultInitExprClass:
8439 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00008440 case Expr::ChooseExprClass: {
Eli Friedmana5e66012013-07-20 00:40:58 +00008441 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00008442 }
8443 }
8444
David Blaikie30263482012-01-20 21:50:17 +00008445 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00008446}
8447
Richard Smithf48fdb02011-12-09 22:58:01 +00008448/// Evaluate an expression as a C++11 integral constant expression.
Craig Topper32b5a1e2013-08-22 07:09:37 +00008449static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf48fdb02011-12-09 22:58:01 +00008450 const Expr *E,
8451 llvm::APSInt *Value,
8452 SourceLocation *Loc) {
8453 if (!E->getType()->isIntegralOrEnumerationType()) {
8454 if (Loc) *Loc = E->getExprLoc();
8455 return false;
8456 }
8457
Richard Smith4c3fc9b2012-01-18 05:21:49 +00008458 APValue Result;
8459 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00008460 return false;
8461
Richard Smith4c3fc9b2012-01-18 05:21:49 +00008462 assert(Result.isInt() && "pointer cast to int is not an ICE");
8463 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00008464 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00008465}
8466
Craig Topper32b5a1e2013-08-22 07:09:37 +00008467bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
8468 SourceLocation *Loc) const {
Richard Smith80ad52f2013-01-02 11:42:31 +00008469 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf48fdb02011-12-09 22:58:01 +00008470 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
8471
Richard Smithceb59d92012-12-28 13:25:52 +00008472 ICEDiag D = CheckICE(this, Ctx);
8473 if (D.Kind != IK_ICE) {
8474 if (Loc) *Loc = D.Loc;
John McCalld905f5a2010-05-07 05:32:02 +00008475 return false;
8476 }
Richard Smithf48fdb02011-12-09 22:58:01 +00008477 return true;
8478}
8479
Craig Topper32b5a1e2013-08-22 07:09:37 +00008480bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf48fdb02011-12-09 22:58:01 +00008481 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith80ad52f2013-01-02 11:42:31 +00008482 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf48fdb02011-12-09 22:58:01 +00008483 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
8484
8485 if (!isIntegerConstantExpr(Ctx, Loc))
8486 return false;
8487 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00008488 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00008489 return true;
8490}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00008491
Craig Topper32b5a1e2013-08-22 07:09:37 +00008492bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smithceb59d92012-12-28 13:25:52 +00008493 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith70488e22012-02-14 21:38:30 +00008494}
8495
Craig Topper32b5a1e2013-08-22 07:09:37 +00008496bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith4c3fc9b2012-01-18 05:21:49 +00008497 SourceLocation *Loc) const {
8498 // We support this checking in C++98 mode in order to diagnose compatibility
8499 // issues.
David Blaikie4e4d0842012-03-11 07:00:24 +00008500 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00008501
Richard Smith70488e22012-02-14 21:38:30 +00008502 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00008503 Expr::EvalStatus Status;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008504 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith4c3fc9b2012-01-18 05:21:49 +00008505 Status.Diag = &Diags;
8506 EvalInfo Info(Ctx, Status);
8507
8508 APValue Scratch;
8509 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
8510
8511 if (!Diags.empty()) {
8512 IsConstExpr = false;
8513 if (Loc) *Loc = Diags[0].first;
8514 } else if (!IsConstExpr) {
8515 // FIXME: This shouldn't happen.
8516 if (Loc) *Loc = getExprLoc();
8517 }
8518
8519 return IsConstExpr;
8520}
Richard Smith745f5142012-01-27 01:14:48 +00008521
8522bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008523 SmallVectorImpl<
Richard Smith745f5142012-01-27 01:14:48 +00008524 PartialDiagnosticAt> &Diags) {
8525 // FIXME: It would be useful to check constexpr function templates, but at the
8526 // moment the constant expression evaluator cannot cope with the non-rigorous
8527 // ASTs which we build for dependent expressions.
8528 if (FD->isDependentContext())
8529 return true;
8530
8531 Expr::EvalStatus Status;
8532 Status.Diag = &Diags;
8533
8534 EvalInfo Info(FD->getASTContext(), Status);
8535 Info.CheckingPotentialConstantExpression = true;
8536
8537 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8538 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
8539
Richard Smith6391ea22013-05-09 07:14:00 +00008540 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith745f5142012-01-27 01:14:48 +00008541 // is a temporary being used as the 'this' pointer.
8542 LValue This;
8543 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smith83587db2012-02-15 02:18:13 +00008544 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith745f5142012-01-27 01:14:48 +00008545
Richard Smith745f5142012-01-27 01:14:48 +00008546 ArrayRef<const Expr*> Args;
8547
8548 SourceLocation Loc = FD->getLocation();
8549
Richard Smith1aa0be82012-03-03 22:46:17 +00008550 APValue Scratch;
Richard Smith6391ea22013-05-09 07:14:00 +00008551 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
8552 // Evaluate the call as a constant initializer, to allow the construction
8553 // of objects of non-literal types.
8554 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith745f5142012-01-27 01:14:48 +00008555 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith6391ea22013-05-09 07:14:00 +00008556 } else
Richard Smith745f5142012-01-27 01:14:48 +00008557 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
8558 Args, FD->getBody(), Info, Scratch);
8559
8560 return Diags.empty();
8561}