blob: 47b0a6690015c7865aae419a1f4e7eb4271bed50 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
Richard Smith253c2a32012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
Richard Smith861b5b52013-05-07 23:34:45 +000026// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27// too, why the expression could not be folded.
Richard Smith253c2a32012-01-27 01:14:48 +000028//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlsson7a241ba2008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000038#include "clang/AST/ASTDiagnostic.h"
Ken Dyck40775002010-01-11 17:06:35 +000039#include "clang/AST/CharUnits.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000040#include "clang/AST/Expr.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000041#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000042#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000043#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000044#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000045#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000046#include "llvm/ADT/SmallString.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000047#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000048#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000049#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000050
Anders Carlsson7a241ba2008-07-03 04:20:39 +000051using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000052using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000053using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000054
Richard Smithb228a862012-02-15 02:18:13 +000055static bool IsGlobalLValue(APValue::LValueBase B);
56
John McCall93d91dc2010-05-07 17:22:02 +000057namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000058 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000059 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000060 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000061
Richard Smithb228a862012-02-15 02:18:13 +000062 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000063 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65 return D->getType();
Richard Smith84401042013-06-03 05:03:02 +000066
67 const Expr *Base = B.get<const Expr*>();
68
69 // For a materialized temporary, the type of the temporary we materialized
70 // may not be the type of the expression.
71 if (const MaterializeTemporaryExpr *MTE =
72 dyn_cast<MaterializeTemporaryExpr>(Base)) {
73 SmallVector<const Expr *, 2> CommaLHSs;
74 SmallVector<SubobjectAdjustment, 2> Adjustments;
75 const Expr *Temp = MTE->GetTemporaryExpr();
76 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
77 Adjustments);
78 // Keep any cv-qualifiers from the reference if we generated a temporary
79 // for it.
80 if (Inner != Temp)
81 return Inner->getType();
82 }
83
84 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +000085 }
86
Richard Smithd62306a2011-11-10 06:34:14 +000087 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000088 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000089 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000090 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000091 APValue::BaseOrMemberType Value;
92 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +000093 return Value;
94 }
95
96 /// Get an LValue path entry, which is known to not be an array index, as a
97 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +000098 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000099 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000100 }
101 /// Get an LValue path entry, which is known to not be an array index, as a
102 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000103 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000104 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000105 }
106 /// Determine whether this LValue path entry for a base class names a virtual
107 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000108 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000109 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000110 }
111
Richard Smitha8105bc2012-01-06 16:39:00 +0000112 /// Find the path length and type of the most-derived subobject in the given
113 /// path, and find the size of the containing array, if any.
114 static
115 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
116 ArrayRef<APValue::LValuePathEntry> Path,
117 uint64_t &ArraySize, QualType &Type) {
118 unsigned MostDerivedLength = 0;
119 Type = Base;
Richard Smith80815602011-11-07 05:07:52 +0000120 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000121 if (Type->isArrayType()) {
122 const ConstantArrayType *CAT =
123 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
124 Type = CAT->getElementType();
125 ArraySize = CAT->getSize().getZExtValue();
126 MostDerivedLength = I + 1;
Richard Smith66c96992012-02-18 22:04:06 +0000127 } else if (Type->isAnyComplexType()) {
128 const ComplexType *CT = Type->castAs<ComplexType>();
129 Type = CT->getElementType();
130 ArraySize = 2;
131 MostDerivedLength = I + 1;
Richard Smitha8105bc2012-01-06 16:39:00 +0000132 } else if (const FieldDecl *FD = getAsField(Path[I])) {
133 Type = FD->getType();
134 ArraySize = 0;
135 MostDerivedLength = I + 1;
136 } else {
Richard Smith80815602011-11-07 05:07:52 +0000137 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000138 ArraySize = 0;
139 }
Richard Smith80815602011-11-07 05:07:52 +0000140 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000141 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000142 }
143
Richard Smitha8105bc2012-01-06 16:39:00 +0000144 // The order of this enum is important for diagnostics.
145 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000146 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000147 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000148 };
149
Richard Smith96e0c102011-11-04 02:25:55 +0000150 /// A path from a glvalue to a subobject of that glvalue.
151 struct SubobjectDesignator {
152 /// True if the subobject was named in a manner not supported by C++11. Such
153 /// lvalues can still be folded, but they are not core constant expressions
154 /// and we cannot perform lvalue-to-rvalue conversions on them.
155 bool Invalid : 1;
156
Richard Smitha8105bc2012-01-06 16:39:00 +0000157 /// Is this a pointer one past the end of an object?
158 bool IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000159
Richard Smitha8105bc2012-01-06 16:39:00 +0000160 /// The length of the path to the most-derived object of which this is a
161 /// subobject.
162 unsigned MostDerivedPathLength : 30;
163
164 /// The size of the array of which the most-derived object is an element, or
165 /// 0 if the most-derived object is not an array element.
166 uint64_t MostDerivedArraySize;
167
168 /// The type of the most derived object referred to by this address.
169 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000170
Richard Smith80815602011-11-07 05:07:52 +0000171 typedef APValue::LValuePathEntry PathEntry;
172
Richard Smith96e0c102011-11-04 02:25:55 +0000173 /// The entries on the path from the glvalue to the designated subobject.
174 SmallVector<PathEntry, 8> Entries;
175
Richard Smitha8105bc2012-01-06 16:39:00 +0000176 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000177
Richard Smitha8105bc2012-01-06 16:39:00 +0000178 explicit SubobjectDesignator(QualType T)
179 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
180 MostDerivedArraySize(0), MostDerivedType(T) {}
181
182 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
183 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
184 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith80815602011-11-07 05:07:52 +0000185 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000186 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000187 ArrayRef<PathEntry> VEntries = V.getLValuePath();
188 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
189 if (V.getLValueBase())
Richard Smitha8105bc2012-01-06 16:39:00 +0000190 MostDerivedPathLength =
191 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
192 V.getLValuePath(), MostDerivedArraySize,
193 MostDerivedType);
Richard Smith80815602011-11-07 05:07:52 +0000194 }
195 }
196
Richard Smith96e0c102011-11-04 02:25:55 +0000197 void setInvalid() {
198 Invalid = true;
199 Entries.clear();
200 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000201
202 /// Determine whether this is a one-past-the-end pointer.
203 bool isOnePastTheEnd() const {
204 if (IsOnePastTheEnd)
205 return true;
206 if (MostDerivedArraySize &&
207 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
208 return true;
209 return false;
210 }
211
212 /// Check that this refers to a valid subobject.
213 bool isValidSubobject() const {
214 if (Invalid)
215 return false;
216 return !isOnePastTheEnd();
217 }
218 /// Check that this refers to a valid subobject, and if not, produce a
219 /// relevant diagnostic and set the designator as invalid.
220 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
221
222 /// Update this designator to refer to the first element within this array.
223 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000224 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000225 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000226 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000227
228 // This is a most-derived object.
229 MostDerivedType = CAT->getElementType();
230 MostDerivedArraySize = CAT->getSize().getZExtValue();
231 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000232 }
233 /// Update this designator to refer to the given base or member of this
234 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000235 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000236 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000237 APValue::BaseOrMemberType Value(D, Virtual);
238 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000239 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000240
241 // If this isn't a base class, it's a new most-derived object.
242 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
243 MostDerivedType = FD->getType();
244 MostDerivedArraySize = 0;
245 MostDerivedPathLength = Entries.size();
246 }
Richard Smith96e0c102011-11-04 02:25:55 +0000247 }
Richard Smith66c96992012-02-18 22:04:06 +0000248 /// Update this designator to refer to the given complex component.
249 void addComplexUnchecked(QualType EltTy, bool Imag) {
250 PathEntry Entry;
251 Entry.ArrayIndex = Imag;
252 Entries.push_back(Entry);
253
254 // This is technically a most-derived object, though in practice this
255 // is unlikely to matter.
256 MostDerivedType = EltTy;
257 MostDerivedArraySize = 2;
258 MostDerivedPathLength = Entries.size();
259 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000260 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith96e0c102011-11-04 02:25:55 +0000261 /// Add N to the address of this subobject.
Richard Smitha8105bc2012-01-06 16:39:00 +0000262 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith96e0c102011-11-04 02:25:55 +0000263 if (Invalid) return;
Richard Smitha8105bc2012-01-06 16:39:00 +0000264 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith80815602011-11-07 05:07:52 +0000265 Entries.back().ArrayIndex += N;
Richard Smitha8105bc2012-01-06 16:39:00 +0000266 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
267 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
268 setInvalid();
269 }
Richard Smith96e0c102011-11-04 02:25:55 +0000270 return;
271 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000272 // [expr.add]p4: For the purposes of these operators, a pointer to a
273 // nonarray object behaves the same as a pointer to the first element of
274 // an array of length one with the type of the object as its element type.
275 if (IsOnePastTheEnd && N == (uint64_t)-1)
276 IsOnePastTheEnd = false;
277 else if (!IsOnePastTheEnd && N == 1)
278 IsOnePastTheEnd = true;
279 else if (N != 0) {
280 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith96e0c102011-11-04 02:25:55 +0000281 setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000282 }
Richard Smith96e0c102011-11-04 02:25:55 +0000283 }
284 };
285
Richard Smith254a73d2011-10-28 22:34:42 +0000286 /// A stack frame in the constexpr call stack.
287 struct CallStackFrame {
288 EvalInfo &Info;
289
290 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000291 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000292
Richard Smithf6f003a2011-12-16 19:06:07 +0000293 /// CallLoc - The location of the call expression for this call.
294 SourceLocation CallLoc;
295
296 /// Callee - The function which was called.
297 const FunctionDecl *Callee;
298
Richard Smithb228a862012-02-15 02:18:13 +0000299 /// Index - The call index of this call.
300 unsigned Index;
301
Richard Smithd62306a2011-11-10 06:34:14 +0000302 /// This - The binding for the this pointer in this call, if any.
303 const LValue *This;
304
Richard Smith254a73d2011-10-28 22:34:42 +0000305 /// ParmBindings - Parameter bindings for this function call, indexed by
306 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000307 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000308
Eli Friedman4830ec82012-06-25 21:21:08 +0000309 // Note that we intentionally use std::map here so that references to
310 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000311 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000312 typedef MapTy::const_iterator temp_iterator;
313 /// Temporaries - Temporary lvalues materialized within this stack frame.
314 MapTy Temporaries;
315
Richard Smithf6f003a2011-12-16 19:06:07 +0000316 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
317 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000318 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000319 ~CallStackFrame();
Richard Smith08d6a2c2013-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 Smith254a73d2011-10-28 22:34:42 +0000326 };
327
Richard Smith852c9db2013-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 Smith92b1ce02011-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 Smithfe800032012-01-31 04:08:20 +0000358
359 OptionalDiagnostic &operator<<(const APSInt &I) {
360 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000361 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000362 I.toString(Buffer);
363 *Diag << StringRef(Buffer.data(), Buffer.size());
364 }
365 return *this;
366 }
367
368 OptionalDiagnostic &operator<<(const APFloat &F) {
369 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000370 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000371 F.toString(Buffer);
372 *Diag << StringRef(Buffer.data(), Buffer.size());
373 }
374 return *this;
375 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000376 };
377
Richard Smith08d6a2c2013-07-24 07:11:57 +0000378 /// A cleanup, and a flag indicating whether it is lifetime-extended.
379 class Cleanup {
380 llvm::PointerIntPair<APValue*, 1, bool> Value;
381
382 public:
383 Cleanup(APValue *Val, bool IsLifetimeExtended)
384 : Value(Val, IsLifetimeExtended) {}
385
386 bool isLifetimeExtended() const { return Value.getInt(); }
387 void endLifetime() {
388 *Value.getPointer() = APValue();
389 }
390 };
391
Richard Smithb228a862012-02-15 02:18:13 +0000392 /// EvalInfo - This is a private struct used by the evaluator to capture
393 /// information about a subexpression as it is folded. It retains information
394 /// about the AST context, but also maintains information about the folded
395 /// expression.
396 ///
397 /// If an expression could be evaluated, it is still possible it is not a C
398 /// "integer constant expression" or constant expression. If not, this struct
399 /// captures information about how and why not.
400 ///
401 /// One bit of information passed *into* the request for constant folding
402 /// indicates whether the subexpression is "evaluated" or not according to C
403 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
404 /// evaluate the expression regardless of what the RHS is, but C only allows
405 /// certain things in certain situations.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000406 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000407 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000408
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000409 /// EvalStatus - Contains information about the evaluation.
410 Expr::EvalStatus &EvalStatus;
411
412 /// CurrentCall - The top of the constexpr call stack.
413 CallStackFrame *CurrentCall;
414
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000415 /// CallStackDepth - The number of calls in the call stack right now.
416 unsigned CallStackDepth;
417
Richard Smithb228a862012-02-15 02:18:13 +0000418 /// NextCallIndex - The next call index to assign.
419 unsigned NextCallIndex;
420
Richard Smitha3d3bd22013-05-08 02:12:03 +0000421 /// StepsLeft - The remaining number of evaluation steps we're permitted
422 /// to perform. This is essentially a limit for the number of statements
423 /// we will evaluate.
424 unsigned StepsLeft;
425
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000426 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000427 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000428 CallStackFrame BottomFrame;
429
Richard Smith08d6a2c2013-07-24 07:11:57 +0000430 /// A stack of values whose lifetimes end at the end of some surrounding
431 /// evaluation frame.
432 llvm::SmallVector<Cleanup, 16> CleanupStack;
433
Richard Smithd62306a2011-11-10 06:34:14 +0000434 /// EvaluatingDecl - This is the declaration whose initializer is being
435 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000436 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000437
438 /// EvaluatingDeclValue - This is the value being constructed for the
439 /// declaration whose initializer is being evaluated, if any.
440 APValue *EvaluatingDeclValue;
441
Richard Smith357362d2011-12-13 06:39:58 +0000442 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
443 /// notes attached to it will also be stored, otherwise they will not be.
444 bool HasActiveDiagnostic;
445
Richard Smith253c2a32012-01-27 01:14:48 +0000446 /// CheckingPotentialConstantExpression - Are we checking whether the
447 /// expression is a potential constant expression? If so, some diagnostics
448 /// are suppressed.
449 bool CheckingPotentialConstantExpression;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000450
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000451 bool IntOverflowCheckMode;
Richard Smith253c2a32012-01-27 01:14:48 +0000452
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000453 EvalInfo(const ASTContext &C, Expr::EvalStatus &S,
Richard Smitha3d3bd22013-05-08 02:12:03 +0000454 bool OverflowCheckMode = false)
Richard Smith92b1ce02011-12-12 09:28:41 +0000455 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smithb228a862012-02-15 02:18:13 +0000456 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000457 StepsLeft(getLangOpts().ConstexprStepLimit),
Richard Smithb228a862012-02-15 02:18:13 +0000458 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith7525ff62013-05-09 07:14:00 +0000459 EvaluatingDecl((const ValueDecl*)0), EvaluatingDeclValue(0),
460 HasActiveDiagnostic(false), CheckingPotentialConstantExpression(false),
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000461 IntOverflowCheckMode(OverflowCheckMode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000462
Richard Smith7525ff62013-05-09 07:14:00 +0000463 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
464 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000465 EvaluatingDeclValue = &Value;
466 }
467
David Blaikiebbafb8a2012-03-11 07:00:24 +0000468 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000469
Richard Smith357362d2011-12-13 06:39:58 +0000470 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000471 // Don't perform any constexpr calls (other than the call we're checking)
472 // when checking a potential constant expression.
473 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
474 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000475 if (NextCallIndex == 0) {
476 // NextCallIndex has wrapped around.
477 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
478 return false;
479 }
Richard Smith357362d2011-12-13 06:39:58 +0000480 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
481 return true;
482 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
483 << getLangOpts().ConstexprCallDepth;
484 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000485 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000486
Richard Smithb228a862012-02-15 02:18:13 +0000487 CallStackFrame *getCallFrame(unsigned CallIndex) {
488 assert(CallIndex && "no call index in getCallFrame");
489 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
490 // be null in this loop.
491 CallStackFrame *Frame = CurrentCall;
492 while (Frame->Index > CallIndex)
493 Frame = Frame->Caller;
494 return (Frame->Index == CallIndex) ? Frame : 0;
495 }
496
Richard Smitha3d3bd22013-05-08 02:12:03 +0000497 bool nextStep(const Stmt *S) {
498 if (!StepsLeft) {
499 Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
500 return false;
501 }
502 --StepsLeft;
503 return true;
504 }
505
Richard Smith357362d2011-12-13 06:39:58 +0000506 private:
507 /// Add a diagnostic to the diagnostics list.
508 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
509 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
510 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
511 return EvalStatus.Diag->back().second;
512 }
513
Richard Smithf6f003a2011-12-16 19:06:07 +0000514 /// Add notes containing a call stack to the current point of evaluation.
515 void addCallStack(unsigned Limit);
516
Richard Smith357362d2011-12-13 06:39:58 +0000517 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000518 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000519 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
520 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000521 unsigned ExtraNotes = 0) {
Richard Smithf57d8cb2011-12-09 22:58:01 +0000522 // If we have a prior diagnostic, it will be noting that the expression
523 // isn't a constant expression. This diagnostic is more important.
524 // FIXME: We might want to show both diagnostics to the user.
Richard Smith92b1ce02011-12-12 09:28:41 +0000525 if (EvalStatus.Diag) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000526 unsigned CallStackNotes = CallStackDepth - 1;
527 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
528 if (Limit)
529 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith253c2a32012-01-27 01:14:48 +0000530 if (CheckingPotentialConstantExpression)
531 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000532
Richard Smith357362d2011-12-13 06:39:58 +0000533 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000534 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000535 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
536 addDiag(Loc, DiagId);
Richard Smith253c2a32012-01-27 01:14:48 +0000537 if (!CheckingPotentialConstantExpression)
538 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000539 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000540 }
Richard Smith357362d2011-12-13 06:39:58 +0000541 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000542 return OptionalDiagnostic();
543 }
544
Richard Smithce1ec5e2012-03-15 04:53:45 +0000545 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
546 = diag::note_invalid_subexpr_in_const_expr,
547 unsigned ExtraNotes = 0) {
548 if (EvalStatus.Diag)
549 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
550 HasActiveDiagnostic = false;
551 return OptionalDiagnostic();
552 }
553
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000554 bool getIntOverflowCheckMode() { return IntOverflowCheckMode; }
555
Richard Smith92b1ce02011-12-12 09:28:41 +0000556 /// Diagnose that the evaluation does not produce a C++11 core constant
557 /// expression.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000558 template<typename LocArg>
559 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000560 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000561 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000562 // Don't override a previous diagnostic.
Eli Friedmanebea9af2012-02-21 22:41:33 +0000563 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
564 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000565 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000566 }
Richard Smith357362d2011-12-13 06:39:58 +0000567 return Diag(Loc, DiagId, ExtraNotes);
568 }
569
570 /// Add a note to a prior diagnostic.
571 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
572 if (!HasActiveDiagnostic)
573 return OptionalDiagnostic();
574 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000575 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000576
577 /// Add a stack of notes to a prior diagnostic.
578 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
579 if (HasActiveDiagnostic) {
580 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
581 Diags.begin(), Diags.end());
582 }
583 }
Richard Smith253c2a32012-01-27 01:14:48 +0000584
585 /// Should we continue evaluation as much as possible after encountering a
586 /// construct which can't be folded?
587 bool keepEvaluatingAfterFailure() {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000588 // Should return true in IntOverflowCheckMode, so that we check for
589 // overflow even if some subexpressions can't be evaluated as constants.
Richard Smitha3d3bd22013-05-08 02:12:03 +0000590 return StepsLeft && (IntOverflowCheckMode ||
591 (CheckingPotentialConstantExpression &&
592 EvalStatus.Diag && EvalStatus.Diag->empty()));
Richard Smith253c2a32012-01-27 01:14:48 +0000593 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000594 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000595
596 /// Object used to treat all foldable expressions as constant expressions.
597 struct FoldConstant {
598 bool Enabled;
599
600 explicit FoldConstant(EvalInfo &Info)
601 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
602 !Info.EvalStatus.HasSideEffects) {
603 }
604 // Treat the value we've computed since this object was created as constant.
605 void Fold(EvalInfo &Info) {
606 if (Enabled && !Info.EvalStatus.Diag->empty() &&
607 !Info.EvalStatus.HasSideEffects)
608 Info.EvalStatus.Diag->clear();
609 }
610 };
Richard Smith17100ba2012-02-16 02:46:34 +0000611
612 /// RAII object used to suppress diagnostics and side-effects from a
613 /// speculative evaluation.
614 class SpeculativeEvaluationRAII {
615 EvalInfo &Info;
616 Expr::EvalStatus Old;
617
618 public:
619 SpeculativeEvaluationRAII(EvalInfo &Info,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000620 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = 0)
Richard Smith17100ba2012-02-16 02:46:34 +0000621 : Info(Info), Old(Info.EvalStatus) {
622 Info.EvalStatus.Diag = NewDiag;
623 }
624 ~SpeculativeEvaluationRAII() {
625 Info.EvalStatus = Old;
626 }
627 };
Richard Smith08d6a2c2013-07-24 07:11:57 +0000628
629 /// RAII object wrapping a full-expression or block scope, and handling
630 /// the ending of the lifetime of temporaries created within it.
631 template<bool IsFullExpression>
632 class ScopeRAII {
633 EvalInfo &Info;
634 unsigned OldStackSize;
635 public:
636 ScopeRAII(EvalInfo &Info)
637 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
638 ~ScopeRAII() {
639 // Body moved to a static method to encourage the compiler to inline away
640 // instances of this class.
641 cleanup(Info, OldStackSize);
642 }
643 private:
644 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
645 unsigned NewEnd = OldStackSize;
646 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
647 I != N; ++I) {
648 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
649 // Full-expression cleanup of a lifetime-extended temporary: nothing
650 // to do, just move this cleanup to the right place in the stack.
651 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
652 ++NewEnd;
653 } else {
654 // End the lifetime of the object.
655 Info.CleanupStack[I].endLifetime();
656 }
657 }
658 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
659 Info.CleanupStack.end());
660 }
661 };
662 typedef ScopeRAII<false> BlockScopeRAII;
663 typedef ScopeRAII<true> FullExpressionRAII;
Richard Smithf6f003a2011-12-16 19:06:07 +0000664}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000665
Richard Smitha8105bc2012-01-06 16:39:00 +0000666bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
667 CheckSubobjectKind CSK) {
668 if (Invalid)
669 return false;
670 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000671 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000672 << CSK;
673 setInvalid();
674 return false;
675 }
676 return true;
677}
678
679void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
680 const Expr *E, uint64_t N) {
681 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000682 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000683 << static_cast<int>(N) << /*array*/ 0
684 << static_cast<unsigned>(MostDerivedArraySize);
685 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000686 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000687 << static_cast<int>(N) << /*non-array*/ 1;
688 setInvalid();
689}
690
Richard Smithf6f003a2011-12-16 19:06:07 +0000691CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
692 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000693 APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000694 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000695 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000696 Info.CurrentCall = this;
697 ++Info.CallStackDepth;
698}
699
700CallStackFrame::~CallStackFrame() {
701 assert(Info.CurrentCall == this && "calls retired out of order");
702 --Info.CallStackDepth;
703 Info.CurrentCall = Caller;
704}
705
Richard Smith08d6a2c2013-07-24 07:11:57 +0000706APValue &CallStackFrame::createTemporary(const void *Key,
707 bool IsLifetimeExtended) {
708 APValue &Result = Temporaries[Key];
709 assert(Result.isUninit() && "temporary created multiple times");
710 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
711 return Result;
712}
713
Richard Smith84401042013-06-03 05:03:02 +0000714static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +0000715
716void EvalInfo::addCallStack(unsigned Limit) {
717 // Determine which calls to skip, if any.
718 unsigned ActiveCalls = CallStackDepth - 1;
719 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
720 if (Limit && Limit < ActiveCalls) {
721 SkipStart = Limit / 2 + Limit % 2;
722 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000723 }
724
Richard Smithf6f003a2011-12-16 19:06:07 +0000725 // Walk the call stack and add the diagnostics.
726 unsigned CallIdx = 0;
727 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
728 Frame = Frame->Caller, ++CallIdx) {
729 // Skip this call?
730 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
731 if (CallIdx == SkipStart) {
732 // Note that we're skipping calls.
733 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
734 << unsigned(ActiveCalls - Limit);
735 }
736 continue;
737 }
738
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000739 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +0000740 llvm::raw_svector_ostream Out(Buffer);
741 describeCall(Frame, Out);
742 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
743 }
744}
745
746namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000747 struct ComplexValue {
748 private:
749 bool IsInt;
750
751 public:
752 APSInt IntReal, IntImag;
753 APFloat FloatReal, FloatImag;
754
755 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
756
757 void makeComplexFloat() { IsInt = false; }
758 bool isComplexFloat() const { return !IsInt; }
759 APFloat &getComplexFloatReal() { return FloatReal; }
760 APFloat &getComplexFloatImag() { return FloatImag; }
761
762 void makeComplexInt() { IsInt = true; }
763 bool isComplexInt() const { return IsInt; }
764 APSInt &getComplexIntReal() { return IntReal; }
765 APSInt &getComplexIntImag() { return IntImag; }
766
Richard Smith2e312c82012-03-03 22:46:17 +0000767 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000768 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +0000769 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000770 else
Richard Smith2e312c82012-03-03 22:46:17 +0000771 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000772 }
Richard Smith2e312c82012-03-03 22:46:17 +0000773 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000774 assert(v.isComplexFloat() || v.isComplexInt());
775 if (v.isComplexFloat()) {
776 makeComplexFloat();
777 FloatReal = v.getComplexFloatReal();
778 FloatImag = v.getComplexFloatImag();
779 } else {
780 makeComplexInt();
781 IntReal = v.getComplexIntReal();
782 IntImag = v.getComplexIntImag();
783 }
784 }
John McCall93d91dc2010-05-07 17:22:02 +0000785 };
John McCall45d55e42010-05-07 21:00:08 +0000786
787 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000788 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000789 CharUnits Offset;
Richard Smithb228a862012-02-15 02:18:13 +0000790 unsigned CallIndex;
Richard Smith96e0c102011-11-04 02:25:55 +0000791 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000792
Richard Smithce40ad62011-11-12 22:28:03 +0000793 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000794 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000795 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +0000796 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +0000797 SubobjectDesignator &getLValueDesignator() { return Designator; }
798 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000799
Richard Smith2e312c82012-03-03 22:46:17 +0000800 void moveInto(APValue &V) const {
801 if (Designator.Invalid)
802 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
803 else
804 V = APValue(Base, Offset, Designator.Entries,
805 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000806 }
Richard Smith2e312c82012-03-03 22:46:17 +0000807 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000808 assert(V.isLValue());
809 Base = V.getLValueBase();
810 Offset = V.getLValueOffset();
Richard Smithb228a862012-02-15 02:18:13 +0000811 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +0000812 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +0000813 }
814
Richard Smithb228a862012-02-15 02:18:13 +0000815 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smithce40ad62011-11-12 22:28:03 +0000816 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000817 Offset = CharUnits::Zero();
Richard Smithb228a862012-02-15 02:18:13 +0000818 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +0000819 Designator = SubobjectDesignator(getType(B));
820 }
821
822 // Check that this LValue is not based on a null pointer. If it is, produce
823 // a diagnostic and mark the designator as invalid.
824 bool checkNullPointer(EvalInfo &Info, const Expr *E,
825 CheckSubobjectKind CSK) {
826 if (Designator.Invalid)
827 return false;
828 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000829 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000830 << CSK;
831 Designator.setInvalid();
832 return false;
833 }
834 return true;
835 }
836
837 // Check this LValue refers to an object. If not, set the designator to be
838 // invalid and emit a diagnostic.
839 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000840 // Outside C++11, do not build a designator referring to a subobject of
841 // any object: we won't use such a designator for anything.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000842 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000843 Designator.setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000844 return checkNullPointer(Info, E, CSK) &&
845 Designator.checkSubobject(Info, E, CSK);
846 }
847
848 void addDecl(EvalInfo &Info, const Expr *E,
849 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000850 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
851 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +0000852 }
853 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000854 if (checkSubobject(Info, E, CSK_ArrayToPointer))
855 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +0000856 }
Richard Smith66c96992012-02-18 22:04:06 +0000857 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000858 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
859 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +0000860 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000861 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000862 if (checkNullPointer(Info, E, CSK_ArrayIndex))
863 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +0000864 }
John McCall45d55e42010-05-07 21:00:08 +0000865 };
Richard Smith027bf112011-11-17 22:56:20 +0000866
867 struct MemberPtr {
868 MemberPtr() {}
869 explicit MemberPtr(const ValueDecl *Decl) :
870 DeclAndIsDerivedMember(Decl, false), Path() {}
871
872 /// The member or (direct or indirect) field referred to by this member
873 /// pointer, or 0 if this is a null member pointer.
874 const ValueDecl *getDecl() const {
875 return DeclAndIsDerivedMember.getPointer();
876 }
877 /// Is this actually a member of some type derived from the relevant class?
878 bool isDerivedMember() const {
879 return DeclAndIsDerivedMember.getInt();
880 }
881 /// Get the class which the declaration actually lives in.
882 const CXXRecordDecl *getContainingRecord() const {
883 return cast<CXXRecordDecl>(
884 DeclAndIsDerivedMember.getPointer()->getDeclContext());
885 }
886
Richard Smith2e312c82012-03-03 22:46:17 +0000887 void moveInto(APValue &V) const {
888 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +0000889 }
Richard Smith2e312c82012-03-03 22:46:17 +0000890 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +0000891 assert(V.isMemberPointer());
892 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
893 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
894 Path.clear();
895 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
896 Path.insert(Path.end(), P.begin(), P.end());
897 }
898
899 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
900 /// whether the member is a member of some class derived from the class type
901 /// of the member pointer.
902 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
903 /// Path - The path of base/derived classes from the member declaration's
904 /// class (exclusive) to the class type of the member pointer (inclusive).
905 SmallVector<const CXXRecordDecl*, 4> Path;
906
907 /// Perform a cast towards the class of the Decl (either up or down the
908 /// hierarchy).
909 bool castBack(const CXXRecordDecl *Class) {
910 assert(!Path.empty());
911 const CXXRecordDecl *Expected;
912 if (Path.size() >= 2)
913 Expected = Path[Path.size() - 2];
914 else
915 Expected = getContainingRecord();
916 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
917 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
918 // if B does not contain the original member and is not a base or
919 // derived class of the class containing the original member, the result
920 // of the cast is undefined.
921 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
922 // (D::*). We consider that to be a language defect.
923 return false;
924 }
925 Path.pop_back();
926 return true;
927 }
928 /// Perform a base-to-derived member pointer cast.
929 bool castToDerived(const CXXRecordDecl *Derived) {
930 if (!getDecl())
931 return true;
932 if (!isDerivedMember()) {
933 Path.push_back(Derived);
934 return true;
935 }
936 if (!castBack(Derived))
937 return false;
938 if (Path.empty())
939 DeclAndIsDerivedMember.setInt(false);
940 return true;
941 }
942 /// Perform a derived-to-base member pointer cast.
943 bool castToBase(const CXXRecordDecl *Base) {
944 if (!getDecl())
945 return true;
946 if (Path.empty())
947 DeclAndIsDerivedMember.setInt(true);
948 if (isDerivedMember()) {
949 Path.push_back(Base);
950 return true;
951 }
952 return castBack(Base);
953 }
954 };
Richard Smith357362d2011-12-13 06:39:58 +0000955
Richard Smith7bb00672012-02-01 01:42:44 +0000956 /// Compare two member pointers, which are assumed to be of the same type.
957 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
958 if (!LHS.getDecl() || !RHS.getDecl())
959 return !LHS.getDecl() && !RHS.getDecl();
960 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
961 return false;
962 return LHS.Path == RHS.Path;
963 }
John McCall93d91dc2010-05-07 17:22:02 +0000964}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000965
Richard Smith2e312c82012-03-03 22:46:17 +0000966static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +0000967static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
968 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +0000969 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +0000970static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
971static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +0000972static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
973 EvalInfo &Info);
974static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000975static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +0000976static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000977 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000978static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000979static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +0000980static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000981
982//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000983// Misc utilities
984//===----------------------------------------------------------------------===//
985
Richard Smith84401042013-06-03 05:03:02 +0000986/// Produce a string describing the given constexpr call.
987static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
988 unsigned ArgIndex = 0;
989 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
990 !isa<CXXConstructorDecl>(Frame->Callee) &&
991 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
992
993 if (!IsMemberCall)
994 Out << *Frame->Callee << '(';
995
996 if (Frame->This && IsMemberCall) {
997 APValue Val;
998 Frame->This->moveInto(Val);
999 Val.printPretty(Out, Frame->Info.Ctx,
1000 Frame->This->Designator.MostDerivedType);
1001 // FIXME: Add parens around Val if needed.
1002 Out << "->" << *Frame->Callee << '(';
1003 IsMemberCall = false;
1004 }
1005
1006 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1007 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1008 if (ArgIndex > (unsigned)IsMemberCall)
1009 Out << ", ";
1010
1011 const ParmVarDecl *Param = *I;
1012 const APValue &Arg = Frame->Arguments[ArgIndex];
1013 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1014
1015 if (ArgIndex == 0 && IsMemberCall)
1016 Out << "->" << *Frame->Callee << '(';
1017 }
1018
1019 Out << ')';
1020}
1021
Richard Smithd9f663b2013-04-22 15:31:51 +00001022/// Evaluate an expression to see if it had side-effects, and discard its
1023/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001024/// \return \c true if the caller should keep evaluating.
1025static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001026 APValue Scratch;
Richard Smith4e18ca52013-05-06 05:56:11 +00001027 if (!Evaluate(Scratch, Info, E)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001028 Info.EvalStatus.HasSideEffects = true;
Richard Smith4e18ca52013-05-06 05:56:11 +00001029 return Info.keepEvaluatingAfterFailure();
1030 }
1031 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001032}
1033
Richard Smith861b5b52013-05-07 23:34:45 +00001034/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1035/// return its existing value.
1036static int64_t getExtValue(const APSInt &Value) {
1037 return Value.isSigned() ? Value.getSExtValue()
1038 : static_cast<int64_t>(Value.getZExtValue());
1039}
1040
Richard Smithd62306a2011-11-10 06:34:14 +00001041/// Should this call expression be treated as a string literal?
1042static bool IsStringLiteralCall(const CallExpr *E) {
1043 unsigned Builtin = E->isBuiltinCall();
1044 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1045 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1046}
1047
Richard Smithce40ad62011-11-12 22:28:03 +00001048static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001049 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1050 // constant expression of pointer type that evaluates to...
1051
1052 // ... a null pointer value, or a prvalue core constant expression of type
1053 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001054 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001055
Richard Smithce40ad62011-11-12 22:28:03 +00001056 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1057 // ... the address of an object with static storage duration,
1058 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1059 return VD->hasGlobalStorage();
1060 // ... the address of a function,
1061 return isa<FunctionDecl>(D);
1062 }
1063
1064 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001065 switch (E->getStmtClass()) {
1066 default:
1067 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001068 case Expr::CompoundLiteralExprClass: {
1069 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1070 return CLE->isFileScope() && CLE->isLValue();
1071 }
Richard Smithe6c01442013-06-05 00:46:14 +00001072 case Expr::MaterializeTemporaryExprClass:
1073 // A materialized temporary might have been lifetime-extended to static
1074 // storage duration.
1075 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001076 // A string literal has static storage duration.
1077 case Expr::StringLiteralClass:
1078 case Expr::PredefinedExprClass:
1079 case Expr::ObjCStringLiteralClass:
1080 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001081 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001082 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001083 return true;
1084 case Expr::CallExprClass:
1085 return IsStringLiteralCall(cast<CallExpr>(E));
1086 // For GCC compatibility, &&label has static storage duration.
1087 case Expr::AddrLabelExprClass:
1088 return true;
1089 // A Block literal expression may be used as the initialization value for
1090 // Block variables at global or local static scope.
1091 case Expr::BlockExprClass:
1092 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001093 case Expr::ImplicitValueInitExprClass:
1094 // FIXME:
1095 // We can never form an lvalue with an implicit value initialization as its
1096 // base through expression evaluation, so these only appear in one case: the
1097 // implicit variable declaration we invent when checking whether a constexpr
1098 // constructor can produce a constant expression. We must assume that such
1099 // an expression might be a global lvalue.
1100 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001101 }
John McCall95007602010-05-10 23:27:23 +00001102}
1103
Richard Smithb228a862012-02-15 02:18:13 +00001104static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1105 assert(Base && "no location for a null lvalue");
1106 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1107 if (VD)
1108 Info.Note(VD->getLocation(), diag::note_declared_at);
1109 else
Ted Kremenek28831752012-08-23 20:46:57 +00001110 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001111 diag::note_constexpr_temporary_here);
1112}
1113
Richard Smith80815602011-11-07 05:07:52 +00001114/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001115/// value for an address or reference constant expression. Return true if we
1116/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001117static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1118 QualType Type, const LValue &LVal) {
1119 bool IsReferenceType = Type->isReferenceType();
1120
Richard Smith357362d2011-12-13 06:39:58 +00001121 APValue::LValueBase Base = LVal.getLValueBase();
1122 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1123
Richard Smith0dea49e2012-02-18 04:58:18 +00001124 // Check that the object is a global. Note that the fake 'this' object we
1125 // manufacture when checking potential constant expressions is conservatively
1126 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001127 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001128 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001129 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001130 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1131 << IsReferenceType << !Designator.Entries.empty()
1132 << !!VD << VD;
1133 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001134 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001135 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001136 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001137 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001138 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001139 }
Richard Smithb228a862012-02-15 02:18:13 +00001140 assert((Info.CheckingPotentialConstantExpression ||
1141 LVal.getLValueCallIndex() == 0) &&
1142 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001143
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001144 // Check if this is a thread-local variable.
1145 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1146 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
Richard Smithfd3834f2013-04-13 02:43:54 +00001147 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001148 return false;
1149 }
1150 }
1151
Richard Smitha8105bc2012-01-06 16:39:00 +00001152 // Allow address constant expressions to be past-the-end pointers. This is
1153 // an extension: the standard requires them to point to an object.
1154 if (!IsReferenceType)
1155 return true;
1156
1157 // A reference constant expression must refer to an object.
1158 if (!Base) {
1159 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001160 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001161 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001162 }
1163
Richard Smith357362d2011-12-13 06:39:58 +00001164 // Does this refer one past the end of some object?
Richard Smitha8105bc2012-01-06 16:39:00 +00001165 if (Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001166 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001167 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001168 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001169 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001170 }
1171
Richard Smith80815602011-11-07 05:07:52 +00001172 return true;
1173}
1174
Richard Smithfddd3842011-12-30 21:15:51 +00001175/// Check that this core constant expression is of literal type, and if not,
1176/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001177static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1178 const LValue *This = 0) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001179 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001180 return true;
1181
Richard Smith7525ff62013-05-09 07:14:00 +00001182 // C++1y: A constant initializer for an object o [...] may also invoke
1183 // constexpr constructors for o and its subobjects even if those objects
1184 // are of non-literal class types.
1185 if (Info.getLangOpts().CPlusPlus1y && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001186 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001187 return true;
1188
Richard Smithfddd3842011-12-30 21:15:51 +00001189 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001190 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001191 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001192 << E->getType();
1193 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001194 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001195 return false;
1196}
1197
Richard Smith0b0a0b62011-10-29 20:57:55 +00001198/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001199/// constant expression. If not, report an appropriate diagnostic. Does not
1200/// check that the expression is of literal type.
1201static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1202 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001203 if (Value.isUninit()) {
Richard Smith51f03172013-06-20 03:00:05 +00001204 Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1205 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001206 return false;
1207 }
1208
Richard Smithb228a862012-02-15 02:18:13 +00001209 // Core issue 1454: For a literal constant expression of array or class type,
1210 // each subobject of its value shall have been initialized by a constant
1211 // expression.
1212 if (Value.isArray()) {
1213 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1214 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1215 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1216 Value.getArrayInitializedElt(I)))
1217 return false;
1218 }
1219 if (!Value.hasArrayFiller())
1220 return true;
1221 return CheckConstantExpression(Info, DiagLoc, EltTy,
1222 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001223 }
Richard Smithb228a862012-02-15 02:18:13 +00001224 if (Value.isUnion() && Value.getUnionField()) {
1225 return CheckConstantExpression(Info, DiagLoc,
1226 Value.getUnionField()->getType(),
1227 Value.getUnionValue());
1228 }
1229 if (Value.isStruct()) {
1230 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1231 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1232 unsigned BaseIndex = 0;
1233 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1234 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1235 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1236 Value.getStructBase(BaseIndex)))
1237 return false;
1238 }
1239 }
1240 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1241 I != E; ++I) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001242 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1243 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001244 return false;
1245 }
1246 }
1247
1248 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001249 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001250 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001251 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1252 }
1253
1254 // Everything else is fine.
1255 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001256}
1257
Richard Smith83c68212011-10-31 05:11:32 +00001258const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001259 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001260}
1261
1262static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001263 if (Value.CallIndex)
1264 return false;
1265 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1266 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001267}
1268
Richard Smithcecf1842011-11-01 21:06:14 +00001269static bool IsWeakLValue(const LValue &Value) {
1270 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001271 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001272}
1273
Richard Smith2e312c82012-03-03 22:46:17 +00001274static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001275 // A null base expression indicates a null pointer. These are always
1276 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001277 if (!Value.getLValueBase()) {
1278 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001279 return true;
1280 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001281
Richard Smith027bf112011-11-17 22:56:20 +00001282 // We have a non-null base. These are generally known to be true, but if it's
1283 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001284 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001285 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001286 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001287}
1288
Richard Smith2e312c82012-03-03 22:46:17 +00001289static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001290 switch (Val.getKind()) {
1291 case APValue::Uninitialized:
1292 return false;
1293 case APValue::Int:
1294 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001295 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001296 case APValue::Float:
1297 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001298 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001299 case APValue::ComplexInt:
1300 Result = Val.getComplexIntReal().getBoolValue() ||
1301 Val.getComplexIntImag().getBoolValue();
1302 return true;
1303 case APValue::ComplexFloat:
1304 Result = !Val.getComplexFloatReal().isZero() ||
1305 !Val.getComplexFloatImag().isZero();
1306 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001307 case APValue::LValue:
1308 return EvalPointerValueAsBool(Val, Result);
1309 case APValue::MemberPointer:
1310 Result = Val.getMemberPointerDecl();
1311 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001312 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001313 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001314 case APValue::Struct:
1315 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001316 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001317 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001318 }
1319
Richard Smith11562c52011-10-28 17:51:58 +00001320 llvm_unreachable("unknown APValue kind");
1321}
1322
1323static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1324 EvalInfo &Info) {
1325 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001326 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001327 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001328 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001329 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001330}
1331
Richard Smith357362d2011-12-13 06:39:58 +00001332template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001333static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001334 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001335 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001336 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001337}
1338
1339static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1340 QualType SrcType, const APFloat &Value,
1341 QualType DestType, APSInt &Result) {
1342 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001343 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001344 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001345
Richard Smith357362d2011-12-13 06:39:58 +00001346 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001347 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001348 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1349 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001350 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001351 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001352}
1353
Richard Smith357362d2011-12-13 06:39:58 +00001354static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1355 QualType SrcType, QualType DestType,
1356 APFloat &Result) {
1357 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001358 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001359 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1360 APFloat::rmNearestTiesToEven, &ignored)
1361 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001362 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001363 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001364}
1365
Richard Smith911e1422012-01-30 22:27:01 +00001366static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1367 QualType DestType, QualType SrcType,
1368 APSInt &Value) {
1369 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001370 APSInt Result = Value;
1371 // Figure out if this is a truncate, extend or noop cast.
1372 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001373 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001374 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001375 return Result;
1376}
1377
Richard Smith357362d2011-12-13 06:39:58 +00001378static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1379 QualType SrcType, const APSInt &Value,
1380 QualType DestType, APFloat &Result) {
1381 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1382 if (Result.convertFromAPInt(Value, Value.isSigned(),
1383 APFloat::rmNearestTiesToEven)
1384 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001385 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001386 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001387}
1388
Eli Friedman803acb32011-12-22 03:51:45 +00001389static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1390 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001391 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001392 if (!Evaluate(SVal, Info, E))
1393 return false;
1394 if (SVal.isInt()) {
1395 Res = SVal.getInt();
1396 return true;
1397 }
1398 if (SVal.isFloat()) {
1399 Res = SVal.getFloat().bitcastToAPInt();
1400 return true;
1401 }
1402 if (SVal.isVector()) {
1403 QualType VecTy = E->getType();
1404 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1405 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1406 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1407 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1408 Res = llvm::APInt::getNullValue(VecSize);
1409 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1410 APValue &Elt = SVal.getVectorElt(i);
1411 llvm::APInt EltAsInt;
1412 if (Elt.isInt()) {
1413 EltAsInt = Elt.getInt();
1414 } else if (Elt.isFloat()) {
1415 EltAsInt = Elt.getFloat().bitcastToAPInt();
1416 } else {
1417 // Don't try to handle vectors of anything other than int or float
1418 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001419 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001420 return false;
1421 }
1422 unsigned BaseEltSize = EltAsInt.getBitWidth();
1423 if (BigEndian)
1424 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1425 else
1426 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1427 }
1428 return true;
1429 }
1430 // Give up if the input isn't an int, float, or vector. For example, we
1431 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001432 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001433 return false;
1434}
1435
Richard Smith43e77732013-05-07 04:50:00 +00001436/// Perform the given integer operation, which is known to need at most BitWidth
1437/// bits, and check for overflow in the original type (if that type was not an
1438/// unsigned type).
1439template<typename Operation>
1440static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1441 const APSInt &LHS, const APSInt &RHS,
1442 unsigned BitWidth, Operation Op) {
1443 if (LHS.isUnsigned())
1444 return Op(LHS, RHS);
1445
1446 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1447 APSInt Result = Value.trunc(LHS.getBitWidth());
1448 if (Result.extend(BitWidth) != Value) {
1449 if (Info.getIntOverflowCheckMode())
1450 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1451 diag::warn_integer_constant_overflow)
1452 << Result.toString(10) << E->getType();
1453 else
1454 HandleOverflow(Info, E, Value, E->getType());
1455 }
1456 return Result;
1457}
1458
1459/// Perform the given binary integer operation.
1460static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1461 BinaryOperatorKind Opcode, APSInt RHS,
1462 APSInt &Result) {
1463 switch (Opcode) {
1464 default:
1465 Info.Diag(E);
1466 return false;
1467 case BO_Mul:
1468 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1469 std::multiplies<APSInt>());
1470 return true;
1471 case BO_Add:
1472 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1473 std::plus<APSInt>());
1474 return true;
1475 case BO_Sub:
1476 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1477 std::minus<APSInt>());
1478 return true;
1479 case BO_And: Result = LHS & RHS; return true;
1480 case BO_Xor: Result = LHS ^ RHS; return true;
1481 case BO_Or: Result = LHS | RHS; return true;
1482 case BO_Div:
1483 case BO_Rem:
1484 if (RHS == 0) {
1485 Info.Diag(E, diag::note_expr_divide_by_zero);
1486 return false;
1487 }
1488 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1489 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1490 LHS.isSigned() && LHS.isMinSignedValue())
1491 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1492 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1493 return true;
1494 case BO_Shl: {
1495 if (Info.getLangOpts().OpenCL)
1496 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1497 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1498 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1499 RHS.isUnsigned());
1500 else if (RHS.isSigned() && RHS.isNegative()) {
1501 // During constant-folding, a negative shift is an opposite shift. Such
1502 // a shift is not a constant expression.
1503 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1504 RHS = -RHS;
1505 goto shift_right;
1506 }
1507 shift_left:
1508 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1509 // the shifted type.
1510 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1511 if (SA != RHS) {
1512 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1513 << RHS << E->getType() << LHS.getBitWidth();
1514 } else if (LHS.isSigned()) {
1515 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1516 // operand, and must not overflow the corresponding unsigned type.
1517 if (LHS.isNegative())
1518 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1519 else if (LHS.countLeadingZeros() < SA)
1520 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1521 }
1522 Result = LHS << SA;
1523 return true;
1524 }
1525 case BO_Shr: {
1526 if (Info.getLangOpts().OpenCL)
1527 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1528 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1529 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1530 RHS.isUnsigned());
1531 else if (RHS.isSigned() && RHS.isNegative()) {
1532 // During constant-folding, a negative shift is an opposite shift. Such a
1533 // shift is not a constant expression.
1534 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1535 RHS = -RHS;
1536 goto shift_left;
1537 }
1538 shift_right:
1539 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1540 // shifted type.
1541 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1542 if (SA != RHS)
1543 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1544 << RHS << E->getType() << LHS.getBitWidth();
1545 Result = LHS >> SA;
1546 return true;
1547 }
1548
1549 case BO_LT: Result = LHS < RHS; return true;
1550 case BO_GT: Result = LHS > RHS; return true;
1551 case BO_LE: Result = LHS <= RHS; return true;
1552 case BO_GE: Result = LHS >= RHS; return true;
1553 case BO_EQ: Result = LHS == RHS; return true;
1554 case BO_NE: Result = LHS != RHS; return true;
1555 }
1556}
1557
Richard Smith861b5b52013-05-07 23:34:45 +00001558/// Perform the given binary floating-point operation, in-place, on LHS.
1559static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1560 APFloat &LHS, BinaryOperatorKind Opcode,
1561 const APFloat &RHS) {
1562 switch (Opcode) {
1563 default:
1564 Info.Diag(E);
1565 return false;
1566 case BO_Mul:
1567 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1568 break;
1569 case BO_Add:
1570 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1571 break;
1572 case BO_Sub:
1573 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1574 break;
1575 case BO_Div:
1576 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1577 break;
1578 }
1579
1580 if (LHS.isInfinity() || LHS.isNaN())
1581 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1582 return true;
1583}
1584
Richard Smitha8105bc2012-01-06 16:39:00 +00001585/// Cast an lvalue referring to a base subobject to a derived class, by
1586/// truncating the lvalue's path to the given length.
1587static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1588 const RecordDecl *TruncatedType,
1589 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001590 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001591
1592 // Check we actually point to a derived class object.
1593 if (TruncatedElements == D.Entries.size())
1594 return true;
1595 assert(TruncatedElements >= D.MostDerivedPathLength &&
1596 "not casting to a derived class");
1597 if (!Result.checkSubobject(Info, E, CSK_Derived))
1598 return false;
1599
1600 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001601 const RecordDecl *RD = TruncatedType;
1602 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001603 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001604 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1605 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001606 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001607 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001608 else
Richard Smithd62306a2011-11-10 06:34:14 +00001609 Result.Offset -= Layout.getBaseClassOffset(Base);
1610 RD = Base;
1611 }
Richard Smith027bf112011-11-17 22:56:20 +00001612 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001613 return true;
1614}
1615
John McCalld7bca762012-05-01 00:38:49 +00001616static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001617 const CXXRecordDecl *Derived,
1618 const CXXRecordDecl *Base,
1619 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001620 if (!RL) {
1621 if (Derived->isInvalidDecl()) return false;
1622 RL = &Info.Ctx.getASTRecordLayout(Derived);
1623 }
1624
Richard Smithd62306a2011-11-10 06:34:14 +00001625 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001626 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001627 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001628}
1629
Richard Smitha8105bc2012-01-06 16:39:00 +00001630static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001631 const CXXRecordDecl *DerivedDecl,
1632 const CXXBaseSpecifier *Base) {
1633 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1634
John McCalld7bca762012-05-01 00:38:49 +00001635 if (!Base->isVirtual())
1636 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001637
Richard Smitha8105bc2012-01-06 16:39:00 +00001638 SubobjectDesignator &D = Obj.Designator;
1639 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001640 return false;
1641
Richard Smitha8105bc2012-01-06 16:39:00 +00001642 // Extract most-derived object and corresponding type.
1643 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1644 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1645 return false;
1646
1647 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001648 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001649 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1650 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001651 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001652 return true;
1653}
1654
Richard Smith84401042013-06-03 05:03:02 +00001655static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1656 QualType Type, LValue &Result) {
1657 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1658 PathE = E->path_end();
1659 PathI != PathE; ++PathI) {
1660 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1661 *PathI))
1662 return false;
1663 Type = (*PathI)->getType();
1664 }
1665 return true;
1666}
1667
Richard Smithd62306a2011-11-10 06:34:14 +00001668/// Update LVal to refer to the given field, which must be a member of the type
1669/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001670static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001671 const FieldDecl *FD,
1672 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001673 if (!RL) {
1674 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001675 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001676 }
Richard Smithd62306a2011-11-10 06:34:14 +00001677
1678 unsigned I = FD->getFieldIndex();
1679 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001680 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001681 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001682}
1683
Richard Smith1b78b3d2012-01-25 22:15:11 +00001684/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001685static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001686 LValue &LVal,
1687 const IndirectFieldDecl *IFD) {
1688 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1689 CE = IFD->chain_end(); C != CE; ++C)
John McCalld7bca762012-05-01 00:38:49 +00001690 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1691 return false;
1692 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001693}
1694
Richard Smithd62306a2011-11-10 06:34:14 +00001695/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001696static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1697 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001698 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1699 // extension.
1700 if (Type->isVoidType() || Type->isFunctionType()) {
1701 Size = CharUnits::One();
1702 return true;
1703 }
1704
1705 if (!Type->isConstantSizeType()) {
1706 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001707 // FIXME: Better diagnostic.
1708 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001709 return false;
1710 }
1711
1712 Size = Info.Ctx.getTypeSizeInChars(Type);
1713 return true;
1714}
1715
1716/// Update a pointer value to model pointer arithmetic.
1717/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001718/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001719/// \param LVal - The pointer value to be updated.
1720/// \param EltTy - The pointee type represented by LVal.
1721/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001722static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1723 LValue &LVal, QualType EltTy,
1724 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001725 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001726 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001727 return false;
1728
1729 // Compute the new offset in the appropriate width.
1730 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001731 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001732 return true;
1733}
1734
Richard Smith66c96992012-02-18 22:04:06 +00001735/// Update an lvalue to refer to a component of a complex number.
1736/// \param Info - Information about the ongoing evaluation.
1737/// \param LVal - The lvalue to be updated.
1738/// \param EltTy - The complex number's component type.
1739/// \param Imag - False for the real component, true for the imaginary.
1740static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1741 LValue &LVal, QualType EltTy,
1742 bool Imag) {
1743 if (Imag) {
1744 CharUnits SizeOfComponent;
1745 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1746 return false;
1747 LVal.Offset += SizeOfComponent;
1748 }
1749 LVal.addComplex(Info, E, EltTy, Imag);
1750 return true;
1751}
1752
Richard Smith27908702011-10-24 17:54:18 +00001753/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001754///
1755/// \param Info Information about the ongoing evaluation.
1756/// \param E An expression to be used when printing diagnostics.
1757/// \param VD The variable whose initializer should be obtained.
1758/// \param Frame The frame in which the variable was created. Must be null
1759/// if this variable is not local to the evaluation.
1760/// \param Result Filled in with a pointer to the value of the variable.
1761static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1762 const VarDecl *VD, CallStackFrame *Frame,
1763 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001764 // If this is a parameter to an active constexpr function call, perform
1765 // argument substitution.
1766 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001767 // Assume arguments of a potential constant expression are unknown
1768 // constant expressions.
1769 if (Info.CheckingPotentialConstantExpression)
1770 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001771 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001772 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001773 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001774 }
Richard Smith3229b742013-05-05 21:17:10 +00001775 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00001776 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001777 }
Richard Smith27908702011-10-24 17:54:18 +00001778
Richard Smithd9f663b2013-04-22 15:31:51 +00001779 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00001780 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00001781 Result = Frame->getTemporary(VD);
1782 assert(Result && "missing value for local variable");
1783 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001784 }
1785
Richard Smithd0b4dd62011-12-19 06:19:21 +00001786 // Dig out the initializer, and use the declaration which it's attached to.
1787 const Expr *Init = VD->getAnyInitializer(VD);
1788 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001789 // If we're checking a potential constant expression, the variable could be
1790 // initialized later.
1791 if (!Info.CheckingPotentialConstantExpression)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001792 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001793 return false;
1794 }
1795
Richard Smithd62306a2011-11-10 06:34:14 +00001796 // If we're currently evaluating the initializer of this declaration, use that
1797 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00001798 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00001799 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00001800 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001801 }
1802
Richard Smithcecf1842011-11-01 21:06:14 +00001803 // Never evaluate the initializer of a weak variable. We can't be sure that
1804 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001805 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001806 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001807 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001808 }
Richard Smithcecf1842011-11-01 21:06:14 +00001809
Richard Smithd0b4dd62011-12-19 06:19:21 +00001810 // Check that we can fold the initializer. In C++, we will have already done
1811 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001812 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001813 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001814 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001815 Notes.size() + 1) << VD;
1816 Info.Note(VD->getLocation(), diag::note_declared_at);
1817 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001818 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001819 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001820 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001821 Notes.size() + 1) << VD;
1822 Info.Note(VD->getLocation(), diag::note_declared_at);
1823 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001824 }
Richard Smith27908702011-10-24 17:54:18 +00001825
Richard Smith3229b742013-05-05 21:17:10 +00001826 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001827 return true;
Richard Smith27908702011-10-24 17:54:18 +00001828}
1829
Richard Smith11562c52011-10-28 17:51:58 +00001830static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001831 Qualifiers Quals = T.getQualifiers();
1832 return Quals.hasConst() && !Quals.hasVolatile();
1833}
1834
Richard Smithe97cbd72011-11-11 04:05:33 +00001835/// Get the base index of the given base class within an APValue representing
1836/// the given derived class.
1837static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1838 const CXXRecordDecl *Base) {
1839 Base = Base->getCanonicalDecl();
1840 unsigned Index = 0;
1841 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1842 E = Derived->bases_end(); I != E; ++I, ++Index) {
1843 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1844 return Index;
1845 }
1846
1847 llvm_unreachable("base class missing from derived class's bases list");
1848}
1849
Richard Smith3da88fa2013-04-26 14:36:30 +00001850/// Extract the value of a character from a string literal.
1851static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1852 uint64_t Index) {
Richard Smith14a94132012-02-17 03:35:37 +00001853 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith3da88fa2013-04-26 14:36:30 +00001854 const StringLiteral *S = cast<StringLiteral>(Lit);
1855 const ConstantArrayType *CAT =
1856 Info.Ctx.getAsConstantArrayType(S->getType());
1857 assert(CAT && "string literal isn't an array");
1858 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00001859 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00001860
1861 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00001862 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00001863 if (Index < S->getLength())
1864 Value = S->getCodeUnit(Index);
1865 return Value;
1866}
1867
Richard Smith3da88fa2013-04-26 14:36:30 +00001868// Expand a string literal into an array of characters.
1869static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
1870 APValue &Result) {
1871 const StringLiteral *S = cast<StringLiteral>(Lit);
1872 const ConstantArrayType *CAT =
1873 Info.Ctx.getAsConstantArrayType(S->getType());
1874 assert(CAT && "string literal isn't an array");
1875 QualType CharType = CAT->getElementType();
1876 assert(CharType->isIntegerType() && "unexpected character type");
1877
1878 unsigned Elts = CAT->getSize().getZExtValue();
1879 Result = APValue(APValue::UninitArray(),
1880 std::min(S->getLength(), Elts), Elts);
1881 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1882 CharType->isUnsignedIntegerType());
1883 if (Result.hasArrayFiller())
1884 Result.getArrayFiller() = APValue(Value);
1885 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
1886 Value = S->getCodeUnit(I);
1887 Result.getArrayInitializedElt(I) = APValue(Value);
1888 }
1889}
1890
1891// Expand an array so that it has more than Index filled elements.
1892static void expandArray(APValue &Array, unsigned Index) {
1893 unsigned Size = Array.getArraySize();
1894 assert(Index < Size);
1895
1896 // Always at least double the number of elements for which we store a value.
1897 unsigned OldElts = Array.getArrayInitializedElts();
1898 unsigned NewElts = std::max(Index+1, OldElts * 2);
1899 NewElts = std::min(Size, std::max(NewElts, 8u));
1900
1901 // Copy the data across.
1902 APValue NewValue(APValue::UninitArray(), NewElts, Size);
1903 for (unsigned I = 0; I != OldElts; ++I)
1904 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
1905 for (unsigned I = OldElts; I != NewElts; ++I)
1906 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
1907 if (NewValue.hasArrayFiller())
1908 NewValue.getArrayFiller() = Array.getArrayFiller();
1909 Array.swap(NewValue);
1910}
1911
Richard Smith861b5b52013-05-07 23:34:45 +00001912/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00001913enum AccessKinds {
1914 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00001915 AK_Assign,
1916 AK_Increment,
1917 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00001918};
1919
Richard Smith3229b742013-05-05 21:17:10 +00001920/// A handle to a complete object (an object that is not a subobject of
1921/// another object).
1922struct CompleteObject {
1923 /// The value of the complete object.
1924 APValue *Value;
1925 /// The type of the complete object.
1926 QualType Type;
1927
1928 CompleteObject() : Value(0) {}
1929 CompleteObject(APValue *Value, QualType Type)
1930 : Value(Value), Type(Type) {
1931 assert(Value && "missing value for complete object");
1932 }
1933
David Blaikie7d170102013-05-15 07:37:26 +00001934 LLVM_EXPLICIT operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00001935};
1936
Richard Smith3da88fa2013-04-26 14:36:30 +00001937/// Find the designated sub-object of an rvalue.
1938template<typename SubobjectHandler>
1939typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00001940findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00001941 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001942 if (Sub.Invalid)
1943 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00001944 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00001945 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001946 if (Info.getLangOpts().CPlusPlus11)
1947 Info.Diag(E, diag::note_constexpr_access_past_end)
1948 << handler.AccessKind;
1949 else
1950 Info.Diag(E);
1951 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001952 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001953
Richard Smith3229b742013-05-05 21:17:10 +00001954 APValue *O = Obj.Value;
1955 QualType ObjType = Obj.Type;
Richard Smithd62306a2011-11-10 06:34:14 +00001956 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00001957 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
1958 if (O->isUninit()) {
1959 if (!Info.CheckingPotentialConstantExpression)
1960 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
1961 return handler.failed();
1962 }
1963
1964 if (I == N)
1965 return handler.found(*O, ObjType);
1966
Richard Smithf3e9e432011-11-07 09:22:26 +00001967 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001968 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001969 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001970 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001971 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001972 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001973 // Note, it should not be possible to form a pointer with a valid
1974 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00001975 if (Info.getLangOpts().CPlusPlus11)
1976 Info.Diag(E, diag::note_constexpr_access_past_end)
1977 << handler.AccessKind;
1978 else
1979 Info.Diag(E);
1980 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001981 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001982
1983 ObjType = CAT->getElementType();
1984
Richard Smith14a94132012-02-17 03:35:37 +00001985 // An array object is represented as either an Array APValue or as an
1986 // LValue which refers to a string literal.
1987 if (O->isLValue()) {
1988 assert(I == N - 1 && "extracting subobject of character?");
1989 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00001990 if (handler.AccessKind != AK_Read)
1991 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
1992 *O);
1993 else
1994 return handler.foundString(*O, ObjType, Index);
1995 }
1996
1997 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00001998 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00001999 else if (handler.AccessKind != AK_Read) {
2000 expandArray(*O, Index);
2001 O = &O->getArrayInitializedElt(Index);
2002 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002003 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002004 } else if (ObjType->isAnyComplexType()) {
2005 // Next subobject is a complex number.
2006 uint64_t Index = Sub.Entries[I].ArrayIndex;
2007 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002008 if (Info.getLangOpts().CPlusPlus11)
2009 Info.Diag(E, diag::note_constexpr_access_past_end)
2010 << handler.AccessKind;
2011 else
2012 Info.Diag(E);
2013 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002014 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002015
2016 bool WasConstQualified = ObjType.isConstQualified();
2017 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2018 if (WasConstQualified)
2019 ObjType.addConst();
2020
Richard Smith66c96992012-02-18 22:04:06 +00002021 assert(I == N - 1 && "extracting subobject of scalar?");
2022 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002023 return handler.found(Index ? O->getComplexIntImag()
2024 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002025 } else {
2026 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002027 return handler.found(Index ? O->getComplexFloatImag()
2028 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002029 }
Richard Smithd62306a2011-11-10 06:34:14 +00002030 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002031 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002032 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002033 << Field;
2034 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002035 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002036 }
2037
Richard Smithd62306a2011-11-10 06:34:14 +00002038 // Next subobject is a class, struct or union field.
2039 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2040 if (RD->isUnion()) {
2041 const FieldDecl *UnionField = O->getUnionField();
2042 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002043 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002044 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2045 << handler.AccessKind << Field << !UnionField << UnionField;
2046 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002047 }
Richard Smithd62306a2011-11-10 06:34:14 +00002048 O = &O->getUnionValue();
2049 } else
2050 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002051
2052 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002053 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002054 if (WasConstQualified && !Field->isMutable())
2055 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002056
2057 if (ObjType.isVolatileQualified()) {
2058 if (Info.getLangOpts().CPlusPlus) {
2059 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00002060 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2061 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002062 Info.Note(Field->getLocation(), diag::note_declared_at);
2063 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002064 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002065 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002066 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002067 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002068 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002069 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002070 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2071 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2072 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002073
2074 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002075 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002076 if (WasConstQualified)
2077 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002078 }
2079 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002080}
2081
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002082namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002083struct ExtractSubobjectHandler {
2084 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002085 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002086
2087 static const AccessKinds AccessKind = AK_Read;
2088
2089 typedef bool result_type;
2090 bool failed() { return false; }
2091 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002092 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002093 return true;
2094 }
2095 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002096 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002097 return true;
2098 }
2099 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002100 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002101 return true;
2102 }
2103 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002104 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002105 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2106 return true;
2107 }
2108};
Richard Smith3229b742013-05-05 21:17:10 +00002109} // end anonymous namespace
2110
Richard Smith3da88fa2013-04-26 14:36:30 +00002111const AccessKinds ExtractSubobjectHandler::AccessKind;
2112
2113/// Extract the designated sub-object of an rvalue.
2114static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002115 const CompleteObject &Obj,
2116 const SubobjectDesignator &Sub,
2117 APValue &Result) {
2118 ExtractSubobjectHandler Handler = { Info, Result };
2119 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002120}
2121
Richard Smith3229b742013-05-05 21:17:10 +00002122namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002123struct ModifySubobjectHandler {
2124 EvalInfo &Info;
2125 APValue &NewVal;
2126 const Expr *E;
2127
2128 typedef bool result_type;
2129 static const AccessKinds AccessKind = AK_Assign;
2130
2131 bool checkConst(QualType QT) {
2132 // Assigning to a const object has undefined behavior.
2133 if (QT.isConstQualified()) {
2134 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2135 return false;
2136 }
2137 return true;
2138 }
2139
2140 bool failed() { return false; }
2141 bool found(APValue &Subobj, QualType SubobjType) {
2142 if (!checkConst(SubobjType))
2143 return false;
2144 // We've been given ownership of NewVal, so just swap it in.
2145 Subobj.swap(NewVal);
2146 return true;
2147 }
2148 bool found(APSInt &Value, QualType SubobjType) {
2149 if (!checkConst(SubobjType))
2150 return false;
2151 if (!NewVal.isInt()) {
2152 // Maybe trying to write a cast pointer value into a complex?
2153 Info.Diag(E);
2154 return false;
2155 }
2156 Value = NewVal.getInt();
2157 return true;
2158 }
2159 bool found(APFloat &Value, QualType SubobjType) {
2160 if (!checkConst(SubobjType))
2161 return false;
2162 Value = NewVal.getFloat();
2163 return true;
2164 }
2165 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2166 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2167 }
2168};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002169} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002170
Richard Smith3229b742013-05-05 21:17:10 +00002171const AccessKinds ModifySubobjectHandler::AccessKind;
2172
Richard Smith3da88fa2013-04-26 14:36:30 +00002173/// Update the designated sub-object of an rvalue to the given value.
2174static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002175 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002176 const SubobjectDesignator &Sub,
2177 APValue &NewVal) {
2178 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002179 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002180}
2181
Richard Smith84f6dcf2012-02-02 01:16:57 +00002182/// Find the position where two subobject designators diverge, or equivalently
2183/// the length of the common initial subsequence.
2184static unsigned FindDesignatorMismatch(QualType ObjType,
2185 const SubobjectDesignator &A,
2186 const SubobjectDesignator &B,
2187 bool &WasArrayIndex) {
2188 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2189 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002190 if (!ObjType.isNull() &&
2191 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002192 // Next subobject is an array element.
2193 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2194 WasArrayIndex = true;
2195 return I;
2196 }
Richard Smith66c96992012-02-18 22:04:06 +00002197 if (ObjType->isAnyComplexType())
2198 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2199 else
2200 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002201 } else {
2202 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2203 WasArrayIndex = false;
2204 return I;
2205 }
2206 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2207 // Next subobject is a field.
2208 ObjType = FD->getType();
2209 else
2210 // Next subobject is a base class.
2211 ObjType = QualType();
2212 }
2213 }
2214 WasArrayIndex = false;
2215 return I;
2216}
2217
2218/// Determine whether the given subobject designators refer to elements of the
2219/// same array object.
2220static bool AreElementsOfSameArray(QualType ObjType,
2221 const SubobjectDesignator &A,
2222 const SubobjectDesignator &B) {
2223 if (A.Entries.size() != B.Entries.size())
2224 return false;
2225
2226 bool IsArray = A.MostDerivedArraySize != 0;
2227 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2228 // A is a subobject of the array element.
2229 return false;
2230
2231 // If A (and B) designates an array element, the last entry will be the array
2232 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2233 // of length 1' case, and the entire path must match.
2234 bool WasArrayIndex;
2235 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2236 return CommonLength >= A.Entries.size() - IsArray;
2237}
2238
Richard Smith3229b742013-05-05 21:17:10 +00002239/// Find the complete object to which an LValue refers.
2240CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
2241 const LValue &LVal, QualType LValType) {
2242 if (!LVal.Base) {
2243 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2244 return CompleteObject();
2245 }
2246
2247 CallStackFrame *Frame = 0;
2248 if (LVal.CallIndex) {
2249 Frame = Info.getCallFrame(LVal.CallIndex);
2250 if (!Frame) {
2251 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2252 << AK << LVal.Base.is<const ValueDecl*>();
2253 NoteLValueLocation(Info, LVal.Base);
2254 return CompleteObject();
2255 }
Richard Smith3229b742013-05-05 21:17:10 +00002256 }
2257
2258 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2259 // is not a constant expression (even if the object is non-volatile). We also
2260 // apply this rule to C++98, in order to conform to the expected 'volatile'
2261 // semantics.
2262 if (LValType.isVolatileQualified()) {
2263 if (Info.getLangOpts().CPlusPlus)
2264 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2265 << AK << LValType;
2266 else
2267 Info.Diag(E);
2268 return CompleteObject();
2269 }
2270
2271 // Compute value storage location and type of base object.
2272 APValue *BaseVal = 0;
Richard Smith84401042013-06-03 05:03:02 +00002273 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002274
2275 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2276 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2277 // In C++11, constexpr, non-volatile variables initialized with constant
2278 // expressions are constant expressions too. Inside constexpr functions,
2279 // parameters are constant expressions even if they're non-const.
2280 // In C++1y, objects local to a constant expression (those with a Frame) are
2281 // both readable and writable inside constant expressions.
2282 // In C, such things can also be folded, although they are not ICEs.
2283 const VarDecl *VD = dyn_cast<VarDecl>(D);
2284 if (VD) {
2285 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2286 VD = VDef;
2287 }
2288 if (!VD || VD->isInvalidDecl()) {
2289 Info.Diag(E);
2290 return CompleteObject();
2291 }
2292
2293 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002294 if (BaseType.isVolatileQualified()) {
2295 if (Info.getLangOpts().CPlusPlus) {
2296 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2297 << AK << 1 << VD;
2298 Info.Note(VD->getLocation(), diag::note_declared_at);
2299 } else {
2300 Info.Diag(E);
2301 }
2302 return CompleteObject();
2303 }
2304
2305 // Unless we're looking at a local variable or argument in a constexpr call,
2306 // the variable we're reading must be const.
2307 if (!Frame) {
Richard Smith7525ff62013-05-09 07:14:00 +00002308 if (Info.getLangOpts().CPlusPlus1y &&
2309 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2310 // OK, we can read and modify an object if we're in the process of
2311 // evaluating its initializer, because its lifetime began in this
2312 // evaluation.
2313 } else if (AK != AK_Read) {
2314 // All the remaining cases only permit reading.
2315 Info.Diag(E, diag::note_constexpr_modify_global);
2316 return CompleteObject();
2317 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002318 // OK, we can read this variable.
2319 } else if (BaseType->isIntegralOrEnumerationType()) {
2320 if (!BaseType.isConstQualified()) {
2321 if (Info.getLangOpts().CPlusPlus) {
2322 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2323 Info.Note(VD->getLocation(), diag::note_declared_at);
2324 } else {
2325 Info.Diag(E);
2326 }
2327 return CompleteObject();
2328 }
2329 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2330 // We support folding of const floating-point types, in order to make
2331 // static const data members of such types (supported as an extension)
2332 // more useful.
2333 if (Info.getLangOpts().CPlusPlus11) {
2334 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2335 Info.Note(VD->getLocation(), diag::note_declared_at);
2336 } else {
2337 Info.CCEDiag(E);
2338 }
2339 } else {
2340 // FIXME: Allow folding of values of any literal type in all languages.
2341 if (Info.getLangOpts().CPlusPlus11) {
2342 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2343 Info.Note(VD->getLocation(), diag::note_declared_at);
2344 } else {
2345 Info.Diag(E);
2346 }
2347 return CompleteObject();
2348 }
2349 }
2350
2351 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2352 return CompleteObject();
2353 } else {
2354 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2355
2356 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002357 if (const MaterializeTemporaryExpr *MTE =
2358 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2359 assert(MTE->getStorageDuration() == SD_Static &&
2360 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002361
Richard Smithe6c01442013-06-05 00:46:14 +00002362 // Per C++1y [expr.const]p2:
2363 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2364 // - a [...] glvalue of integral or enumeration type that refers to
2365 // a non-volatile const object [...]
2366 // [...]
2367 // - a [...] glvalue of literal type that refers to a non-volatile
2368 // object whose lifetime began within the evaluation of e.
2369 //
2370 // C++11 misses the 'began within the evaluation of e' check and
2371 // instead allows all temporaries, including things like:
2372 // int &&r = 1;
2373 // int x = ++r;
2374 // constexpr int k = r;
2375 // Therefore we use the C++1y rules in C++11 too.
2376 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2377 const ValueDecl *ED = MTE->getExtendingDecl();
2378 if (!(BaseType.isConstQualified() &&
2379 BaseType->isIntegralOrEnumerationType()) &&
2380 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2381 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2382 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2383 return CompleteObject();
2384 }
2385
2386 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2387 assert(BaseVal && "got reference to unevaluated temporary");
2388 } else {
2389 Info.Diag(E);
2390 return CompleteObject();
2391 }
2392 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002393 BaseVal = Frame->getTemporary(Base);
2394 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002395 }
Richard Smith3229b742013-05-05 21:17:10 +00002396
2397 // Volatile temporary objects cannot be accessed in constant expressions.
2398 if (BaseType.isVolatileQualified()) {
2399 if (Info.getLangOpts().CPlusPlus) {
2400 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2401 << AK << 0;
2402 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2403 } else {
2404 Info.Diag(E);
2405 }
2406 return CompleteObject();
2407 }
2408 }
2409
Richard Smith7525ff62013-05-09 07:14:00 +00002410 // During the construction of an object, it is not yet 'const'.
2411 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2412 // and this doesn't do quite the right thing for const subobjects of the
2413 // object under construction.
2414 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2415 BaseType = Info.Ctx.getCanonicalType(BaseType);
2416 BaseType.removeLocalConst();
2417 }
2418
Richard Smith3229b742013-05-05 21:17:10 +00002419 // In C++1y, we can't safely access any mutable state when checking a
2420 // potential constant expression.
2421 if (Frame && Info.getLangOpts().CPlusPlus1y &&
2422 Info.CheckingPotentialConstantExpression)
2423 return CompleteObject();
2424
2425 return CompleteObject(BaseVal, BaseType);
2426}
2427
Richard Smith243ef902013-05-05 23:31:59 +00002428/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2429/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2430/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002431///
2432/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002433/// \param Conv - The expression for which we are performing the conversion.
2434/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002435/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2436/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002437/// \param LVal - The glvalue on which we are attempting to perform this action.
2438/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002439static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002440 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002441 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002442 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002443 return false;
2444
Richard Smith3229b742013-05-05 21:17:10 +00002445 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002446 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith3229b742013-05-05 21:17:10 +00002447 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2448 !Type.isVolatileQualified()) {
2449 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2450 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2451 // initializer until now for such expressions. Such an expression can't be
2452 // an ICE in C, so this only matters for fold.
2453 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2454 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002455 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002456 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002457 }
Richard Smith3229b742013-05-05 21:17:10 +00002458 APValue Lit;
2459 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2460 return false;
2461 CompleteObject LitObj(&Lit, Base->getType());
2462 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2463 } else if (isa<StringLiteral>(Base)) {
2464 // We represent a string literal array as an lvalue pointing at the
2465 // corresponding expression, rather than building an array of chars.
2466 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2467 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2468 CompleteObject StrObj(&Str, Base->getType());
2469 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002470 }
Richard Smith11562c52011-10-28 17:51:58 +00002471 }
2472
Richard Smith3229b742013-05-05 21:17:10 +00002473 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2474 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002475}
2476
2477/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002478static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002479 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002480 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002481 return false;
2482
Richard Smith3229b742013-05-05 21:17:10 +00002483 if (!Info.getLangOpts().CPlusPlus1y) {
2484 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002485 return false;
2486 }
2487
Richard Smith3229b742013-05-05 21:17:10 +00002488 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2489 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002490}
2491
Richard Smith243ef902013-05-05 23:31:59 +00002492static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2493 return T->isSignedIntegerType() &&
2494 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2495}
2496
2497namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002498struct CompoundAssignSubobjectHandler {
2499 EvalInfo &Info;
2500 const Expr *E;
2501 QualType PromotedLHSType;
2502 BinaryOperatorKind Opcode;
2503 const APValue &RHS;
2504
2505 static const AccessKinds AccessKind = AK_Assign;
2506
2507 typedef bool result_type;
2508
2509 bool checkConst(QualType QT) {
2510 // Assigning to a const object has undefined behavior.
2511 if (QT.isConstQualified()) {
2512 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2513 return false;
2514 }
2515 return true;
2516 }
2517
2518 bool failed() { return false; }
2519 bool found(APValue &Subobj, QualType SubobjType) {
2520 switch (Subobj.getKind()) {
2521 case APValue::Int:
2522 return found(Subobj.getInt(), SubobjType);
2523 case APValue::Float:
2524 return found(Subobj.getFloat(), SubobjType);
2525 case APValue::ComplexInt:
2526 case APValue::ComplexFloat:
2527 // FIXME: Implement complex compound assignment.
2528 Info.Diag(E);
2529 return false;
2530 case APValue::LValue:
2531 return foundPointer(Subobj, SubobjType);
2532 default:
2533 // FIXME: can this happen?
2534 Info.Diag(E);
2535 return false;
2536 }
2537 }
2538 bool found(APSInt &Value, QualType SubobjType) {
2539 if (!checkConst(SubobjType))
2540 return false;
2541
2542 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2543 // We don't support compound assignment on integer-cast-to-pointer
2544 // values.
2545 Info.Diag(E);
2546 return false;
2547 }
2548
2549 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2550 SubobjType, Value);
2551 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2552 return false;
2553 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2554 return true;
2555 }
2556 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002557 return checkConst(SubobjType) &&
2558 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2559 Value) &&
2560 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2561 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00002562 }
2563 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2564 if (!checkConst(SubobjType))
2565 return false;
2566
2567 QualType PointeeType;
2568 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2569 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00002570
2571 if (PointeeType.isNull() || !RHS.isInt() ||
2572 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00002573 Info.Diag(E);
2574 return false;
2575 }
2576
Richard Smith861b5b52013-05-07 23:34:45 +00002577 int64_t Offset = getExtValue(RHS.getInt());
2578 if (Opcode == BO_Sub)
2579 Offset = -Offset;
2580
2581 LValue LVal;
2582 LVal.setFrom(Info.Ctx, Subobj);
2583 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2584 return false;
2585 LVal.moveInto(Subobj);
2586 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002587 }
2588 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2589 llvm_unreachable("shouldn't encounter string elements here");
2590 }
2591};
2592} // end anonymous namespace
2593
2594const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2595
2596/// Perform a compound assignment of LVal <op>= RVal.
2597static bool handleCompoundAssignment(
2598 EvalInfo &Info, const Expr *E,
2599 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2600 BinaryOperatorKind Opcode, const APValue &RVal) {
2601 if (LVal.Designator.Invalid)
2602 return false;
2603
2604 if (!Info.getLangOpts().CPlusPlus1y) {
2605 Info.Diag(E);
2606 return false;
2607 }
2608
2609 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2610 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2611 RVal };
2612 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2613}
2614
2615namespace {
Richard Smith243ef902013-05-05 23:31:59 +00002616struct IncDecSubobjectHandler {
2617 EvalInfo &Info;
2618 const Expr *E;
2619 AccessKinds AccessKind;
2620 APValue *Old;
2621
2622 typedef bool result_type;
2623
2624 bool checkConst(QualType QT) {
2625 // Assigning to a const object has undefined behavior.
2626 if (QT.isConstQualified()) {
2627 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2628 return false;
2629 }
2630 return true;
2631 }
2632
2633 bool failed() { return false; }
2634 bool found(APValue &Subobj, QualType SubobjType) {
2635 // Stash the old value. Also clear Old, so we don't clobber it later
2636 // if we're post-incrementing a complex.
2637 if (Old) {
2638 *Old = Subobj;
2639 Old = 0;
2640 }
2641
2642 switch (Subobj.getKind()) {
2643 case APValue::Int:
2644 return found(Subobj.getInt(), SubobjType);
2645 case APValue::Float:
2646 return found(Subobj.getFloat(), SubobjType);
2647 case APValue::ComplexInt:
2648 return found(Subobj.getComplexIntReal(),
2649 SubobjType->castAs<ComplexType>()->getElementType()
2650 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2651 case APValue::ComplexFloat:
2652 return found(Subobj.getComplexFloatReal(),
2653 SubobjType->castAs<ComplexType>()->getElementType()
2654 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2655 case APValue::LValue:
2656 return foundPointer(Subobj, SubobjType);
2657 default:
2658 // FIXME: can this happen?
2659 Info.Diag(E);
2660 return false;
2661 }
2662 }
2663 bool found(APSInt &Value, QualType SubobjType) {
2664 if (!checkConst(SubobjType))
2665 return false;
2666
2667 if (!SubobjType->isIntegerType()) {
2668 // We don't support increment / decrement on integer-cast-to-pointer
2669 // values.
2670 Info.Diag(E);
2671 return false;
2672 }
2673
2674 if (Old) *Old = APValue(Value);
2675
2676 // bool arithmetic promotes to int, and the conversion back to bool
2677 // doesn't reduce mod 2^n, so special-case it.
2678 if (SubobjType->isBooleanType()) {
2679 if (AccessKind == AK_Increment)
2680 Value = 1;
2681 else
2682 Value = !Value;
2683 return true;
2684 }
2685
2686 bool WasNegative = Value.isNegative();
2687 if (AccessKind == AK_Increment) {
2688 ++Value;
2689
2690 if (!WasNegative && Value.isNegative() &&
2691 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2692 APSInt ActualValue(Value, /*IsUnsigned*/true);
2693 HandleOverflow(Info, E, ActualValue, SubobjType);
2694 }
2695 } else {
2696 --Value;
2697
2698 if (WasNegative && !Value.isNegative() &&
2699 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2700 unsigned BitWidth = Value.getBitWidth();
2701 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2702 ActualValue.setBit(BitWidth);
2703 HandleOverflow(Info, E, ActualValue, SubobjType);
2704 }
2705 }
2706 return true;
2707 }
2708 bool found(APFloat &Value, QualType SubobjType) {
2709 if (!checkConst(SubobjType))
2710 return false;
2711
2712 if (Old) *Old = APValue(Value);
2713
2714 APFloat One(Value.getSemantics(), 1);
2715 if (AccessKind == AK_Increment)
2716 Value.add(One, APFloat::rmNearestTiesToEven);
2717 else
2718 Value.subtract(One, APFloat::rmNearestTiesToEven);
2719 return true;
2720 }
2721 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2722 if (!checkConst(SubobjType))
2723 return false;
2724
2725 QualType PointeeType;
2726 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2727 PointeeType = PT->getPointeeType();
2728 else {
2729 Info.Diag(E);
2730 return false;
2731 }
2732
2733 LValue LVal;
2734 LVal.setFrom(Info.Ctx, Subobj);
2735 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2736 AccessKind == AK_Increment ? 1 : -1))
2737 return false;
2738 LVal.moveInto(Subobj);
2739 return true;
2740 }
2741 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2742 llvm_unreachable("shouldn't encounter string elements here");
2743 }
2744};
2745} // end anonymous namespace
2746
2747/// Perform an increment or decrement on LVal.
2748static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
2749 QualType LValType, bool IsIncrement, APValue *Old) {
2750 if (LVal.Designator.Invalid)
2751 return false;
2752
2753 if (!Info.getLangOpts().CPlusPlus1y) {
2754 Info.Diag(E);
2755 return false;
2756 }
2757
2758 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
2759 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
2760 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
2761 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2762}
2763
Richard Smithe97cbd72011-11-11 04:05:33 +00002764/// Build an lvalue for the object argument of a member function call.
2765static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2766 LValue &This) {
2767 if (Object->getType()->isPointerType())
2768 return EvaluatePointer(Object, This, Info);
2769
2770 if (Object->isGLValue())
2771 return EvaluateLValue(Object, This, Info);
2772
Richard Smithd9f663b2013-04-22 15:31:51 +00002773 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00002774 return EvaluateTemporary(Object, This, Info);
2775
2776 return false;
2777}
2778
2779/// HandleMemberPointerAccess - Evaluate a member access operation and build an
2780/// lvalue referring to the result.
2781///
2782/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00002783/// \param LV - An lvalue referring to the base of the member pointer.
2784/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00002785/// \param IncludeMember - Specifies whether the member itself is included in
2786/// the resulting LValue subobject designator. This is not possible when
2787/// creating a bound member function.
2788/// \return The field or method declaration to which the member pointer refers,
2789/// or 0 if evaluation fails.
2790static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00002791 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00002792 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00002793 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00002794 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00002795 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00002796 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Richard Smith027bf112011-11-17 22:56:20 +00002797 return 0;
2798
2799 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2800 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00002801 if (!MemPtr.getDecl()) {
2802 // FIXME: Specific diagnostic.
2803 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002804 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002805 }
Richard Smith253c2a32012-01-27 01:14:48 +00002806
Richard Smith027bf112011-11-17 22:56:20 +00002807 if (MemPtr.isDerivedMember()) {
2808 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00002809 // The end of the derived-to-base path for the base object must match the
2810 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00002811 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00002812 LV.Designator.Entries.size()) {
2813 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002814 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002815 }
Richard Smith027bf112011-11-17 22:56:20 +00002816 unsigned PathLengthToMember =
2817 LV.Designator.Entries.size() - MemPtr.Path.size();
2818 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
2819 const CXXRecordDecl *LVDecl = getAsBaseClass(
2820 LV.Designator.Entries[PathLengthToMember + I]);
2821 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00002822 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
2823 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002824 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002825 }
Richard Smith027bf112011-11-17 22:56:20 +00002826 }
2827
2828 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00002829 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00002830 PathLengthToMember))
2831 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002832 } else if (!MemPtr.Path.empty()) {
2833 // Extend the LValue path with the member pointer's path.
2834 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
2835 MemPtr.Path.size() + IncludeMember);
2836
2837 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00002838 if (const PointerType *PT = LVType->getAs<PointerType>())
2839 LVType = PT->getPointeeType();
2840 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
2841 assert(RD && "member pointer access on non-class-type expression");
2842 // The first class in the path is that of the lvalue.
2843 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
2844 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00002845 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
John McCalld7bca762012-05-01 00:38:49 +00002846 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002847 RD = Base;
2848 }
2849 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00002850 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
2851 MemPtr.getContainingRecord()))
John McCalld7bca762012-05-01 00:38:49 +00002852 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002853 }
2854
2855 // Add the member. Note that we cannot build bound member functions here.
2856 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00002857 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00002858 if (!HandleLValueMember(Info, RHS, LV, FD))
John McCalld7bca762012-05-01 00:38:49 +00002859 return 0;
2860 } else if (const IndirectFieldDecl *IFD =
2861 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00002862 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
John McCalld7bca762012-05-01 00:38:49 +00002863 return 0;
2864 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002865 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00002866 }
Richard Smith027bf112011-11-17 22:56:20 +00002867 }
2868
2869 return MemPtr.getDecl();
2870}
2871
Richard Smith84401042013-06-03 05:03:02 +00002872static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
2873 const BinaryOperator *BO,
2874 LValue &LV,
2875 bool IncludeMember = true) {
2876 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
2877
2878 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
2879 if (Info.keepEvaluatingAfterFailure()) {
2880 MemberPtr MemPtr;
2881 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
2882 }
2883 return 0;
2884 }
2885
2886 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
2887 BO->getRHS(), IncludeMember);
2888}
2889
Richard Smith027bf112011-11-17 22:56:20 +00002890/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
2891/// the provided lvalue, which currently refers to the base object.
2892static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
2893 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00002894 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002895 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00002896 return false;
2897
Richard Smitha8105bc2012-01-06 16:39:00 +00002898 QualType TargetQT = E->getType();
2899 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2900 TargetQT = PT->getPointeeType();
2901
2902 // Check this cast lands within the final derived-to-base subobject path.
2903 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002904 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002905 << D.MostDerivedType << TargetQT;
2906 return false;
2907 }
2908
Richard Smith027bf112011-11-17 22:56:20 +00002909 // Check the type of the final cast. We don't need to check the path,
2910 // since a cast can only be formed if the path is unique.
2911 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00002912 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2913 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00002914 if (NewEntriesSize == D.MostDerivedPathLength)
2915 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2916 else
Richard Smith027bf112011-11-17 22:56:20 +00002917 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00002918 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002919 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002920 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00002921 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00002922 }
Richard Smith027bf112011-11-17 22:56:20 +00002923
2924 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002925 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00002926}
2927
Mike Stump876387b2009-10-27 22:09:17 +00002928namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00002929enum EvalStmtResult {
2930 /// Evaluation failed.
2931 ESR_Failed,
2932 /// Hit a 'return' statement.
2933 ESR_Returned,
2934 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00002935 ESR_Succeeded,
2936 /// Hit a 'continue' statement.
2937 ESR_Continue,
2938 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00002939 ESR_Break,
2940 /// Still scanning for 'case' or 'default' statement.
2941 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00002942};
2943}
2944
Richard Smithd9f663b2013-04-22 15:31:51 +00002945static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
2946 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2947 // We don't need to evaluate the initializer for a static local.
2948 if (!VD->hasLocalStorage())
2949 return true;
2950
2951 LValue Result;
2952 Result.set(VD, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00002953 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00002954
Richard Smith51f03172013-06-20 03:00:05 +00002955 if (!VD->getInit()) {
2956 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
2957 << false << VD->getType();
2958 Val = APValue();
2959 return false;
2960 }
2961
Richard Smithd9f663b2013-04-22 15:31:51 +00002962 if (!EvaluateInPlace(Val, Info, Result, VD->getInit())) {
2963 // Wipe out any partially-computed value, to allow tracking that this
2964 // evaluation failed.
2965 Val = APValue();
2966 return false;
2967 }
2968 }
2969
2970 return true;
2971}
2972
Richard Smith4e18ca52013-05-06 05:56:11 +00002973/// Evaluate a condition (either a variable declaration or an expression).
2974static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
2975 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002976 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00002977 if (CondDecl && !EvaluateDecl(Info, CondDecl))
2978 return false;
2979 return EvaluateAsBooleanCondition(Cond, Result, Info);
2980}
2981
2982static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00002983 const Stmt *S, const SwitchCase *SC = 0);
Richard Smith4e18ca52013-05-06 05:56:11 +00002984
2985/// Evaluate the body of a loop, and translate the result as appropriate.
2986static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00002987 const Stmt *Body,
2988 const SwitchCase *Case = 0) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002989 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00002990 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00002991 case ESR_Break:
2992 return ESR_Succeeded;
2993 case ESR_Succeeded:
2994 case ESR_Continue:
2995 return ESR_Continue;
2996 case ESR_Failed:
2997 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00002998 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00002999 return ESR;
3000 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003001 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003002}
3003
Richard Smith496ddcf2013-05-12 17:32:42 +00003004/// Evaluate a switch statement.
3005static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
3006 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003007 BlockScopeRAII Scope(Info);
3008
Richard Smith496ddcf2013-05-12 17:32:42 +00003009 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003010 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003011 {
3012 FullExpressionRAII Scope(Info);
3013 if (SS->getConditionVariable() &&
3014 !EvaluateDecl(Info, SS->getConditionVariable()))
3015 return ESR_Failed;
3016 if (!EvaluateInteger(SS->getCond(), Value, Info))
3017 return ESR_Failed;
3018 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003019
3020 // Find the switch case corresponding to the value of the condition.
3021 // FIXME: Cache this lookup.
3022 const SwitchCase *Found = 0;
3023 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3024 SC = SC->getNextSwitchCase()) {
3025 if (isa<DefaultStmt>(SC)) {
3026 Found = SC;
3027 continue;
3028 }
3029
3030 const CaseStmt *CS = cast<CaseStmt>(SC);
3031 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3032 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3033 : LHS;
3034 if (LHS <= Value && Value <= RHS) {
3035 Found = SC;
3036 break;
3037 }
3038 }
3039
3040 if (!Found)
3041 return ESR_Succeeded;
3042
3043 // Search the switch body for the switch case and evaluate it from there.
3044 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3045 case ESR_Break:
3046 return ESR_Succeeded;
3047 case ESR_Succeeded:
3048 case ESR_Continue:
3049 case ESR_Failed:
3050 case ESR_Returned:
3051 return ESR;
3052 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003053 // This can only happen if the switch case is nested within a statement
3054 // expression. We have no intention of supporting that.
3055 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3056 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003057 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003058 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003059}
3060
Richard Smith254a73d2011-10-28 22:34:42 +00003061// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00003062static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003063 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003064 if (!Info.nextStep(S))
3065 return ESR_Failed;
3066
Richard Smith496ddcf2013-05-12 17:32:42 +00003067 // If we're hunting down a 'case' or 'default' label, recurse through
3068 // substatements until we hit the label.
3069 if (Case) {
3070 // FIXME: We don't start the lifetime of objects whose initialization we
3071 // jump over. However, such objects must be of class type with a trivial
3072 // default constructor that initialize all subobjects, so must be empty,
3073 // so this almost never matters.
3074 switch (S->getStmtClass()) {
3075 case Stmt::CompoundStmtClass:
3076 // FIXME: Precompute which substatement of a compound statement we
3077 // would jump to, and go straight there rather than performing a
3078 // linear scan each time.
3079 case Stmt::LabelStmtClass:
3080 case Stmt::AttributedStmtClass:
3081 case Stmt::DoStmtClass:
3082 break;
3083
3084 case Stmt::CaseStmtClass:
3085 case Stmt::DefaultStmtClass:
3086 if (Case == S)
3087 Case = 0;
3088 break;
3089
3090 case Stmt::IfStmtClass: {
3091 // FIXME: Precompute which side of an 'if' we would jump to, and go
3092 // straight there rather than scanning both sides.
3093 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003094
3095 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3096 // preceded by our switch label.
3097 BlockScopeRAII Scope(Info);
3098
Richard Smith496ddcf2013-05-12 17:32:42 +00003099 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3100 if (ESR != ESR_CaseNotFound || !IS->getElse())
3101 return ESR;
3102 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3103 }
3104
3105 case Stmt::WhileStmtClass: {
3106 EvalStmtResult ESR =
3107 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3108 if (ESR != ESR_Continue)
3109 return ESR;
3110 break;
3111 }
3112
3113 case Stmt::ForStmtClass: {
3114 const ForStmt *FS = cast<ForStmt>(S);
3115 EvalStmtResult ESR =
3116 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3117 if (ESR != ESR_Continue)
3118 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003119 if (FS->getInc()) {
3120 FullExpressionRAII IncScope(Info);
3121 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3122 return ESR_Failed;
3123 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003124 break;
3125 }
3126
3127 case Stmt::DeclStmtClass:
3128 // FIXME: If the variable has initialization that can't be jumped over,
3129 // bail out of any immediately-surrounding compound-statement too.
3130 default:
3131 return ESR_CaseNotFound;
3132 }
3133 }
3134
Richard Smith254a73d2011-10-28 22:34:42 +00003135 switch (S->getStmtClass()) {
3136 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003137 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003138 // Don't bother evaluating beyond an expression-statement which couldn't
3139 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003140 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003141 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003142 return ESR_Failed;
3143 return ESR_Succeeded;
3144 }
3145
3146 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003147 return ESR_Failed;
3148
3149 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003150 return ESR_Succeeded;
3151
Richard Smithd9f663b2013-04-22 15:31:51 +00003152 case Stmt::DeclStmtClass: {
3153 const DeclStmt *DS = cast<DeclStmt>(S);
3154 for (DeclStmt::const_decl_iterator DclIt = DS->decl_begin(),
Richard Smith08d6a2c2013-07-24 07:11:57 +00003155 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
3156 // Each declaration initialization is its own full-expression.
3157 // FIXME: This isn't quite right; if we're performing aggregate
3158 // initialization, each braced subexpression is its own full-expression.
3159 FullExpressionRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003160 if (!EvaluateDecl(Info, *DclIt) && !Info.keepEvaluatingAfterFailure())
3161 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003162 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003163 return ESR_Succeeded;
3164 }
3165
Richard Smith357362d2011-12-13 06:39:58 +00003166 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003167 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003168 FullExpressionRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003169 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00003170 return ESR_Failed;
3171 return ESR_Returned;
3172 }
Richard Smith254a73d2011-10-28 22:34:42 +00003173
3174 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003175 BlockScopeRAII Scope(Info);
3176
Richard Smith254a73d2011-10-28 22:34:42 +00003177 const CompoundStmt *CS = cast<CompoundStmt>(S);
3178 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
3179 BE = CS->body_end(); BI != BE; ++BI) {
Richard Smith496ddcf2013-05-12 17:32:42 +00003180 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI, Case);
3181 if (ESR == ESR_Succeeded)
3182 Case = 0;
3183 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003184 return ESR;
3185 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003186 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003187 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003188
3189 case Stmt::IfStmtClass: {
3190 const IfStmt *IS = cast<IfStmt>(S);
3191
3192 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003193 BlockScopeRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003194 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003195 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003196 return ESR_Failed;
3197
3198 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3199 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3200 if (ESR != ESR_Succeeded)
3201 return ESR;
3202 }
3203 return ESR_Succeeded;
3204 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003205
3206 case Stmt::WhileStmtClass: {
3207 const WhileStmt *WS = cast<WhileStmt>(S);
3208 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003209 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003210 bool Continue;
3211 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3212 Continue))
3213 return ESR_Failed;
3214 if (!Continue)
3215 break;
3216
3217 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3218 if (ESR != ESR_Continue)
3219 return ESR;
3220 }
3221 return ESR_Succeeded;
3222 }
3223
3224 case Stmt::DoStmtClass: {
3225 const DoStmt *DS = cast<DoStmt>(S);
3226 bool Continue;
3227 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003228 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003229 if (ESR != ESR_Continue)
3230 return ESR;
Richard Smith496ddcf2013-05-12 17:32:42 +00003231 Case = 0;
Richard Smith4e18ca52013-05-06 05:56:11 +00003232
Richard Smith08d6a2c2013-07-24 07:11:57 +00003233 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003234 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3235 return ESR_Failed;
3236 } while (Continue);
3237 return ESR_Succeeded;
3238 }
3239
3240 case Stmt::ForStmtClass: {
3241 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003242 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003243 if (FS->getInit()) {
3244 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3245 if (ESR != ESR_Succeeded)
3246 return ESR;
3247 }
3248 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003249 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003250 bool Continue = true;
3251 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3252 FS->getCond(), Continue))
3253 return ESR_Failed;
3254 if (!Continue)
3255 break;
3256
3257 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3258 if (ESR != ESR_Continue)
3259 return ESR;
3260
Richard Smith08d6a2c2013-07-24 07:11:57 +00003261 if (FS->getInc()) {
3262 FullExpressionRAII IncScope(Info);
3263 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3264 return ESR_Failed;
3265 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003266 }
3267 return ESR_Succeeded;
3268 }
3269
Richard Smith896e0d72013-05-06 06:51:17 +00003270 case Stmt::CXXForRangeStmtClass: {
3271 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003272 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003273
3274 // Initialize the __range variable.
3275 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3276 if (ESR != ESR_Succeeded)
3277 return ESR;
3278
3279 // Create the __begin and __end iterators.
3280 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3281 if (ESR != ESR_Succeeded)
3282 return ESR;
3283
3284 while (true) {
3285 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003286 {
3287 bool Continue = true;
3288 FullExpressionRAII CondExpr(Info);
3289 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3290 return ESR_Failed;
3291 if (!Continue)
3292 break;
3293 }
Richard Smith896e0d72013-05-06 06:51:17 +00003294
3295 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003296 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003297 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3298 if (ESR != ESR_Succeeded)
3299 return ESR;
3300
3301 // Loop body.
3302 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3303 if (ESR != ESR_Continue)
3304 return ESR;
3305
3306 // Increment: ++__begin
3307 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3308 return ESR_Failed;
3309 }
3310
3311 return ESR_Succeeded;
3312 }
3313
Richard Smith496ddcf2013-05-12 17:32:42 +00003314 case Stmt::SwitchStmtClass:
3315 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3316
Richard Smith4e18ca52013-05-06 05:56:11 +00003317 case Stmt::ContinueStmtClass:
3318 return ESR_Continue;
3319
3320 case Stmt::BreakStmtClass:
3321 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003322
3323 case Stmt::LabelStmtClass:
3324 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3325
3326 case Stmt::AttributedStmtClass:
3327 // As a general principle, C++11 attributes can be ignored without
3328 // any semantic impact.
3329 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3330 Case);
3331
3332 case Stmt::CaseStmtClass:
3333 case Stmt::DefaultStmtClass:
3334 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003335 }
3336}
3337
Richard Smithcc36f692011-12-22 02:22:31 +00003338/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3339/// default constructor. If so, we'll fold it whether or not it's marked as
3340/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3341/// so we need special handling.
3342static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003343 const CXXConstructorDecl *CD,
3344 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003345 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3346 return false;
3347
Richard Smith66e05fe2012-01-18 05:21:49 +00003348 // Value-initialization does not call a trivial default constructor, so such a
3349 // call is a core constant expression whether or not the constructor is
3350 // constexpr.
3351 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003352 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003353 // FIXME: If DiagDecl is an implicitly-declared special member function,
3354 // we should be much more explicit about why it's not constexpr.
3355 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3356 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3357 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003358 } else {
3359 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3360 }
3361 }
3362 return true;
3363}
3364
Richard Smith357362d2011-12-13 06:39:58 +00003365/// CheckConstexprFunction - Check that a function can be called in a constant
3366/// expression.
3367static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3368 const FunctionDecl *Declaration,
3369 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00003370 // Potential constant expressions can contain calls to declared, but not yet
3371 // defined, constexpr functions.
3372 if (Info.CheckingPotentialConstantExpression && !Definition &&
3373 Declaration->isConstexpr())
3374 return false;
3375
Richard Smith0838f3a2013-05-14 05:18:44 +00003376 // Bail out with no diagnostic if the function declaration itself is invalid.
3377 // We will have produced a relevant diagnostic while parsing it.
3378 if (Declaration->isInvalidDecl())
3379 return false;
3380
Richard Smith357362d2011-12-13 06:39:58 +00003381 // Can we evaluate this function call?
3382 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3383 return true;
3384
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003385 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003386 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003387 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3388 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003389 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3390 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3391 << DiagDecl;
3392 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3393 } else {
3394 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3395 }
3396 return false;
3397}
3398
Richard Smithd62306a2011-11-10 06:34:14 +00003399namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003400typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003401}
3402
3403/// EvaluateArgs - Evaluate the arguments to a function call.
3404static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3405 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003406 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003407 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003408 I != E; ++I) {
3409 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3410 // If we're checking for a potential constant expression, evaluate all
3411 // initializers even if some of them fail.
3412 if (!Info.keepEvaluatingAfterFailure())
3413 return false;
3414 Success = false;
3415 }
3416 }
3417 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003418}
3419
Richard Smith254a73d2011-10-28 22:34:42 +00003420/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003421static bool HandleFunctionCall(SourceLocation CallLoc,
3422 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003423 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00003424 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003425 ArgVector ArgValues(Args.size());
3426 if (!EvaluateArgs(Args, ArgValues, Info))
3427 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003428
Richard Smith253c2a32012-01-27 01:14:48 +00003429 if (!Info.CheckCallLimit(CallLoc))
3430 return false;
3431
3432 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003433
3434 // For a trivial copy or move assignment, perform an APValue copy. This is
3435 // essential for unions, where the operations performed by the assignment
3436 // operator cannot be represented as statements.
3437 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3438 if (MD && MD->isDefaulted() && MD->isTrivial()) {
3439 assert(This &&
3440 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3441 LValue RHS;
3442 RHS.setFrom(Info.Ctx, ArgValues[0]);
3443 APValue RHSValue;
3444 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3445 RHS, RHSValue))
3446 return false;
3447 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3448 RHSValue))
3449 return false;
3450 This->moveInto(Result);
3451 return true;
3452 }
3453
Richard Smithd9f663b2013-04-22 15:31:51 +00003454 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003455 if (ESR == ESR_Succeeded) {
3456 if (Callee->getResultType()->isVoidType())
3457 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003458 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003459 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003460 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003461}
3462
Richard Smithd62306a2011-11-10 06:34:14 +00003463/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003464static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003465 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003466 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003467 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003468 ArgVector ArgValues(Args.size());
3469 if (!EvaluateArgs(Args, ArgValues, Info))
3470 return false;
3471
Richard Smith253c2a32012-01-27 01:14:48 +00003472 if (!Info.CheckCallLimit(CallLoc))
3473 return false;
3474
Richard Smith3607ffe2012-02-13 03:54:03 +00003475 const CXXRecordDecl *RD = Definition->getParent();
3476 if (RD->getNumVBases()) {
3477 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3478 return false;
3479 }
3480
Richard Smith253c2a32012-01-27 01:14:48 +00003481 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003482
3483 // If it's a delegating constructor, just delegate.
3484 if (Definition->isDelegatingConstructor()) {
3485 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smithd9f663b2013-04-22 15:31:51 +00003486 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3487 return false;
3488 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003489 }
3490
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003491 // For a trivial copy or move constructor, perform an APValue copy. This is
3492 // essential for unions, where the operations performed by the constructor
3493 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003494 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00003495 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3496 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003497 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003498 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003499 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003500 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003501 }
3502
3503 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003504 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003505 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3506 std::distance(RD->field_begin(), RD->field_end()));
3507
John McCalld7bca762012-05-01 00:38:49 +00003508 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003509 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3510
Richard Smith08d6a2c2013-07-24 07:11:57 +00003511 // A scope for temporaries lifetime-extended by reference members.
3512 BlockScopeRAII LifetimeExtendedScope(Info);
3513
Richard Smith253c2a32012-01-27 01:14:48 +00003514 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003515 unsigned BasesSeen = 0;
3516#ifndef NDEBUG
3517 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3518#endif
3519 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
3520 E = Definition->init_end(); I != E; ++I) {
Richard Smith253c2a32012-01-27 01:14:48 +00003521 LValue Subobject = This;
3522 APValue *Value = &Result;
3523
3524 // Determine the subobject to initialize.
Richard Smithd62306a2011-11-10 06:34:14 +00003525 if ((*I)->isBaseInitializer()) {
3526 QualType BaseType((*I)->getBaseClass(), 0);
3527#ifndef NDEBUG
3528 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003529 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003530 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3531 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3532 "base class initializers not in expected order");
3533 ++BaseIt;
3534#endif
John McCalld7bca762012-05-01 00:38:49 +00003535 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
3536 BaseType->getAsCXXRecordDecl(), &Layout))
3537 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003538 Value = &Result.getStructBase(BasesSeen++);
Richard Smithd62306a2011-11-10 06:34:14 +00003539 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCalld7bca762012-05-01 00:38:49 +00003540 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
3541 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003542 if (RD->isUnion()) {
3543 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003544 Value = &Result.getUnionValue();
3545 } else {
3546 Value = &Result.getStructField(FD->getFieldIndex());
3547 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00003548 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003549 // Walk the indirect field decl's chain to find the object to initialize,
3550 // and make sure we've initialized every step along it.
3551 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
3552 CE = IFD->chain_end();
3553 C != CE; ++C) {
3554 FieldDecl *FD = cast<FieldDecl>(*C);
3555 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3556 // Switch the union field if it differs. This happens if we had
3557 // preceding zero-initialization, and we're now initializing a union
3558 // subobject other than the first.
3559 // FIXME: In this case, the values of the other subobjects are
3560 // specified, since zero-initialization sets all padding bits to zero.
3561 if (Value->isUninit() ||
3562 (Value->isUnion() && Value->getUnionField() != FD)) {
3563 if (CD->isUnion())
3564 *Value = APValue(FD);
3565 else
3566 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
3567 std::distance(CD->field_begin(), CD->field_end()));
3568 }
John McCalld7bca762012-05-01 00:38:49 +00003569 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
3570 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003571 if (CD->isUnion())
3572 Value = &Value->getUnionValue();
3573 else
3574 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00003575 }
Richard Smithd62306a2011-11-10 06:34:14 +00003576 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003577 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00003578 }
Richard Smith253c2a32012-01-27 01:14:48 +00003579
Richard Smith08d6a2c2013-07-24 07:11:57 +00003580 FullExpressionRAII InitScope(Info);
Richard Smith7525ff62013-05-09 07:14:00 +00003581 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit())) {
Richard Smith253c2a32012-01-27 01:14:48 +00003582 // If we're checking for a potential constant expression, evaluate all
3583 // initializers even if some of them fail.
3584 if (!Info.keepEvaluatingAfterFailure())
3585 return false;
3586 Success = false;
3587 }
Richard Smithd62306a2011-11-10 06:34:14 +00003588 }
3589
Richard Smithd9f663b2013-04-22 15:31:51 +00003590 return Success &&
3591 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003592}
3593
Eli Friedman9a156e52008-11-12 09:44:48 +00003594//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00003595// Generic Evaluation
3596//===----------------------------------------------------------------------===//
3597namespace {
3598
Richard Smithf57d8cb2011-12-09 22:58:01 +00003599// FIXME: RetTy is always bool. Remove it.
3600template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00003601class ExprEvaluatorBase
3602 : public ConstStmtVisitor<Derived, RetTy> {
3603private:
Richard Smith2e312c82012-03-03 22:46:17 +00003604 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003605 return static_cast<Derived*>(this)->Success(V, E);
3606 }
Richard Smithfddd3842011-12-30 21:15:51 +00003607 RetTy DerivedZeroInitialization(const Expr *E) {
3608 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003609 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003610
Richard Smith17100ba2012-02-16 02:46:34 +00003611 // Check whether a conditional operator with a non-constant condition is a
3612 // potential constant expression. If neither arm is a potential constant
3613 // expression, then the conditional operator is not either.
3614 template<typename ConditionalOperator>
3615 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
3616 assert(Info.CheckingPotentialConstantExpression);
3617
3618 // Speculatively evaluate both arms.
3619 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003620 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00003621 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3622
3623 StmtVisitorTy::Visit(E->getFalseExpr());
3624 if (Diag.empty())
3625 return;
3626
3627 Diag.clear();
3628 StmtVisitorTy::Visit(E->getTrueExpr());
3629 if (Diag.empty())
3630 return;
3631 }
3632
3633 Error(E, diag::note_constexpr_conditional_never_const);
3634 }
3635
3636
3637 template<typename ConditionalOperator>
3638 bool HandleConditionalOperator(const ConditionalOperator *E) {
3639 bool BoolResult;
3640 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
3641 if (Info.CheckingPotentialConstantExpression)
3642 CheckPotentialConstantConditional(E);
3643 return false;
3644 }
3645
3646 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3647 return StmtVisitorTy::Visit(EvalExpr);
3648 }
3649
Peter Collingbournee9200682011-05-13 03:29:01 +00003650protected:
3651 EvalInfo &Info;
3652 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
3653 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3654
Richard Smith92b1ce02011-12-12 09:28:41 +00003655 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003656 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003657 }
3658
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003659 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
3660
3661public:
3662 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3663
3664 EvalInfo &getEvalInfo() { return Info; }
3665
Richard Smithf57d8cb2011-12-09 22:58:01 +00003666 /// Report an evaluation error. This should only be called when an error is
3667 /// first discovered. When propagating an error, just return false.
3668 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003669 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003670 return false;
3671 }
3672 bool Error(const Expr *E) {
3673 return Error(E, diag::note_invalid_subexpr_in_const_expr);
3674 }
3675
Peter Collingbournee9200682011-05-13 03:29:01 +00003676 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00003677 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00003678 }
3679 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003680 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003681 }
3682
3683 RetTy VisitParenExpr(const ParenExpr *E)
3684 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3685 RetTy VisitUnaryExtension(const UnaryOperator *E)
3686 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3687 RetTy VisitUnaryPlus(const UnaryOperator *E)
3688 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3689 RetTy VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00003690 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003691 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
3692 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00003693 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
3694 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00003695 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
3696 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith852c9db2013-04-20 22:23:05 +00003697 RetTy VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
3698 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00003699 // We cannot create any objects for which cleanups are required, so there is
3700 // nothing to do here; all cleanups must come from unevaluated subexpressions.
3701 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
3702 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003703
Richard Smith6d6ecc32011-12-12 12:46:16 +00003704 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
3705 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3706 return static_cast<Derived*>(this)->VisitCastExpr(E);
3707 }
3708 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
3709 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3710 return static_cast<Derived*>(this)->VisitCastExpr(E);
3711 }
3712
Richard Smith027bf112011-11-17 22:56:20 +00003713 RetTy VisitBinaryOperator(const BinaryOperator *E) {
3714 switch (E->getOpcode()) {
3715 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003716 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003717
3718 case BO_Comma:
3719 VisitIgnoredValue(E->getLHS());
3720 return StmtVisitorTy::Visit(E->getRHS());
3721
3722 case BO_PtrMemD:
3723 case BO_PtrMemI: {
3724 LValue Obj;
3725 if (!HandleMemberPointerAccess(Info, E, Obj))
3726 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003727 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00003728 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00003729 return false;
3730 return DerivedSuccess(Result, E);
3731 }
3732 }
3733 }
3734
Peter Collingbournee9200682011-05-13 03:29:01 +00003735 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003736 // Evaluate and cache the common expression. We treat it as a temporary,
3737 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003738 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00003739 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003740 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00003741
Richard Smith17100ba2012-02-16 02:46:34 +00003742 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003743 }
3744
3745 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003746 bool IsBcpCall = false;
3747 // If the condition (ignoring parens) is a __builtin_constant_p call,
3748 // the result is a constant expression if it can be folded without
3749 // side-effects. This is an important GNU extension. See GCC PR38377
3750 // for discussion.
3751 if (const CallExpr *CallCE =
3752 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
3753 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
3754 IsBcpCall = true;
3755
3756 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3757 // constant expression; we can't check whether it's potentially foldable.
3758 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
3759 return false;
3760
3761 FoldConstant Fold(Info);
3762
Richard Smith17100ba2012-02-16 02:46:34 +00003763 if (!HandleConditionalOperator(E))
Richard Smith84f6dcf2012-02-02 01:16:57 +00003764 return false;
3765
3766 if (IsBcpCall)
3767 Fold.Fold(Info);
3768
3769 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00003770 }
3771
3772 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003773 if (APValue *Value = Info.CurrentCall->getTemporary(E))
3774 return DerivedSuccess(*Value, E);
3775
3776 const Expr *Source = E->getSourceExpr();
3777 if (!Source)
3778 return Error(E);
3779 if (Source == E) { // sanity checking.
3780 assert(0 && "OpaqueValueExpr recursively refers to itself");
3781 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003782 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003783 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00003784 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003785
Richard Smith254a73d2011-10-28 22:34:42 +00003786 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003787 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00003788 QualType CalleeType = Callee->getType();
3789
Richard Smith254a73d2011-10-28 22:34:42 +00003790 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00003791 LValue *This = 0, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003792 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00003793 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00003794
Richard Smithe97cbd72011-11-11 04:05:33 +00003795 // Extract function decl and 'this' pointer from the callee.
3796 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003797 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00003798 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3799 // Explicit bound member calls, such as x.f() or p->g();
3800 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003801 return false;
3802 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00003803 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00003804 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00003805 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
3806 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00003807 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
3808 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00003809 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00003810 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003811 return Error(Callee);
3812
3813 FD = dyn_cast<FunctionDecl>(Member);
3814 if (!FD)
3815 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003816 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003817 LValue Call;
3818 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003819 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00003820
Richard Smitha8105bc2012-01-06 16:39:00 +00003821 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003822 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00003823 FD = dyn_cast_or_null<FunctionDecl>(
3824 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00003825 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003826 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003827
3828 // Overloaded operator calls to member functions are represented as normal
3829 // calls with '*this' as the first argument.
3830 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
3831 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003832 // FIXME: When selecting an implicit conversion for an overloaded
3833 // operator delete, we sometimes try to evaluate calls to conversion
3834 // operators without a 'this' parameter!
3835 if (Args.empty())
3836 return Error(E);
3837
Richard Smithe97cbd72011-11-11 04:05:33 +00003838 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
3839 return false;
3840 This = &ThisVal;
3841 Args = Args.slice(1);
3842 }
3843
3844 // Don't call function pointers which have been cast to some other type.
3845 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003846 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00003847 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003848 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00003849
Richard Smith47b34932012-02-01 02:39:43 +00003850 if (This && !This->checkSubobject(Info, E, CSK_This))
3851 return false;
3852
Richard Smith3607ffe2012-02-13 03:54:03 +00003853 // DR1358 allows virtual constexpr functions in some cases. Don't allow
3854 // calls to such functions in constant expressions.
3855 if (This && !HasQualifier &&
3856 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
3857 return Error(E, diag::note_constexpr_virtual_call);
3858
Richard Smith357362d2011-12-13 06:39:58 +00003859 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00003860 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00003861 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00003862
Richard Smith357362d2011-12-13 06:39:58 +00003863 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00003864 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
3865 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003866 return false;
3867
Richard Smithb228a862012-02-15 02:18:13 +00003868 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00003869 }
3870
Richard Smith11562c52011-10-28 17:51:58 +00003871 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
3872 return StmtVisitorTy::Visit(E->getInitializer());
3873 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003874 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00003875 if (E->getNumInits() == 0)
3876 return DerivedZeroInitialization(E);
3877 if (E->getNumInits() == 1)
3878 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00003879 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003880 }
3881 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003882 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003883 }
3884 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003885 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003886 }
Richard Smith027bf112011-11-17 22:56:20 +00003887 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003888 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00003889 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003890
Richard Smithd62306a2011-11-10 06:34:14 +00003891 /// A member expression where the object is a prvalue is itself a prvalue.
3892 RetTy VisitMemberExpr(const MemberExpr *E) {
3893 assert(!E->isArrow() && "missing call to bound member function?");
3894
Richard Smith2e312c82012-03-03 22:46:17 +00003895 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00003896 if (!Evaluate(Val, Info, E->getBase()))
3897 return false;
3898
3899 QualType BaseTy = E->getBase()->getType();
3900
3901 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003902 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003903 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00003904 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00003905 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3906
Richard Smith3229b742013-05-05 21:17:10 +00003907 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00003908 SubobjectDesignator Designator(BaseTy);
3909 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00003910
Richard Smith3229b742013-05-05 21:17:10 +00003911 APValue Result;
3912 return extractSubobject(Info, E, Obj, Designator, Result) &&
3913 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00003914 }
3915
Richard Smith11562c52011-10-28 17:51:58 +00003916 RetTy VisitCastExpr(const CastExpr *E) {
3917 switch (E->getCastKind()) {
3918 default:
3919 break;
3920
Richard Smitha23ab512013-05-23 00:30:41 +00003921 case CK_AtomicToNonAtomic: {
3922 APValue AtomicVal;
3923 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
3924 return false;
3925 return DerivedSuccess(AtomicVal, E);
3926 }
3927
Richard Smith11562c52011-10-28 17:51:58 +00003928 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00003929 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00003930 return StmtVisitorTy::Visit(E->getSubExpr());
3931
3932 case CK_LValueToRValue: {
3933 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003934 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
3935 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003936 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00003937 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00003938 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00003939 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003940 return false;
3941 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00003942 }
3943 }
3944
Richard Smithf57d8cb2011-12-09 22:58:01 +00003945 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003946 }
3947
Richard Smith243ef902013-05-05 23:31:59 +00003948 RetTy VisitUnaryPostInc(const UnaryOperator *UO) {
3949 return VisitUnaryPostIncDec(UO);
3950 }
3951 RetTy VisitUnaryPostDec(const UnaryOperator *UO) {
3952 return VisitUnaryPostIncDec(UO);
3953 }
3954 RetTy VisitUnaryPostIncDec(const UnaryOperator *UO) {
3955 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
3956 return Error(UO);
3957
3958 LValue LVal;
3959 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
3960 return false;
3961 APValue RVal;
3962 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
3963 UO->isIncrementOp(), &RVal))
3964 return false;
3965 return DerivedSuccess(RVal, UO);
3966 }
3967
Richard Smith51f03172013-06-20 03:00:05 +00003968 RetTy VisitStmtExpr(const StmtExpr *E) {
3969 // We will have checked the full-expressions inside the statement expression
3970 // when they were completed, and don't need to check them again now.
3971 if (Info.getIntOverflowCheckMode())
3972 return Error(E);
3973
Richard Smith08d6a2c2013-07-24 07:11:57 +00003974 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00003975 const CompoundStmt *CS = E->getSubStmt();
3976 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
3977 BE = CS->body_end();
3978 /**/; ++BI) {
3979 if (BI + 1 == BE) {
3980 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
3981 if (!FinalExpr) {
3982 Info.Diag((*BI)->getLocStart(),
3983 diag::note_constexpr_stmt_expr_unsupported);
3984 return false;
3985 }
3986 return this->Visit(FinalExpr);
3987 }
3988
3989 APValue ReturnValue;
3990 EvalStmtResult ESR = EvaluateStmt(ReturnValue, Info, *BI);
3991 if (ESR != ESR_Succeeded) {
3992 // FIXME: If the statement-expression terminated due to 'return',
3993 // 'break', or 'continue', it would be nice to propagate that to
3994 // the outer statement evaluation rather than bailing out.
3995 if (ESR != ESR_Failed)
3996 Info.Diag((*BI)->getLocStart(),
3997 diag::note_constexpr_stmt_expr_unsupported);
3998 return false;
3999 }
4000 }
4001 }
4002
Richard Smith4a678122011-10-24 18:44:57 +00004003 /// Visit a value which is evaluated, but whose value is ignored.
4004 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004005 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004006 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004007};
4008
4009}
4010
4011//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004012// Common base class for lvalue and temporary evaluation.
4013//===----------------------------------------------------------------------===//
4014namespace {
4015template<class Derived>
4016class LValueExprEvaluatorBase
4017 : public ExprEvaluatorBase<Derived, bool> {
4018protected:
4019 LValue &Result;
4020 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4021 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
4022
4023 bool Success(APValue::LValueBase B) {
4024 Result.set(B);
4025 return true;
4026 }
4027
4028public:
4029 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4030 ExprEvaluatorBaseTy(Info), Result(Result) {}
4031
Richard Smith2e312c82012-03-03 22:46:17 +00004032 bool Success(const APValue &V, const Expr *E) {
4033 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004034 return true;
4035 }
Richard Smith027bf112011-11-17 22:56:20 +00004036
Richard Smith027bf112011-11-17 22:56:20 +00004037 bool VisitMemberExpr(const MemberExpr *E) {
4038 // Handle non-static data members.
4039 QualType BaseTy;
4040 if (E->isArrow()) {
4041 if (!EvaluatePointer(E->getBase(), Result, this->Info))
4042 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00004043 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004044 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004045 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00004046 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
4047 return false;
4048 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004049 } else {
4050 if (!this->Visit(E->getBase()))
4051 return false;
4052 BaseTy = E->getBase()->getType();
4053 }
Richard Smith027bf112011-11-17 22:56:20 +00004054
Richard Smith1b78b3d2012-01-25 22:15:11 +00004055 const ValueDecl *MD = E->getMemberDecl();
4056 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4057 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4058 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4059 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004060 if (!HandleLValueMember(this->Info, E, Result, FD))
4061 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004062 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004063 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4064 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004065 } else
4066 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004067
Richard Smith1b78b3d2012-01-25 22:15:11 +00004068 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004069 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004070 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004071 RefValue))
4072 return false;
4073 return Success(RefValue, E);
4074 }
4075 return true;
4076 }
4077
4078 bool VisitBinaryOperator(const BinaryOperator *E) {
4079 switch (E->getOpcode()) {
4080 default:
4081 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4082
4083 case BO_PtrMemD:
4084 case BO_PtrMemI:
4085 return HandleMemberPointerAccess(this->Info, E, Result);
4086 }
4087 }
4088
4089 bool VisitCastExpr(const CastExpr *E) {
4090 switch (E->getCastKind()) {
4091 default:
4092 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4093
4094 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004095 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004096 if (!this->Visit(E->getSubExpr()))
4097 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004098
4099 // Now figure out the necessary offset to add to the base LV to get from
4100 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004101 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4102 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004103 }
4104 }
4105};
4106}
4107
4108//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004109// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004110//
4111// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4112// function designators (in C), decl references to void objects (in C), and
4113// temporaries (if building with -Wno-address-of-temporary).
4114//
4115// LValue evaluation produces values comprising a base expression of one of the
4116// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004117// - Declarations
4118// * VarDecl
4119// * FunctionDecl
4120// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00004121// * CompoundLiteralExpr in C
4122// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004123// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004124// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004125// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004126// * ObjCEncodeExpr
4127// * AddrLabelExpr
4128// * BlockExpr
4129// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004130// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004131// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004132// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004133// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4134// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004135// * A MaterializeTemporaryExpr that has static storage duration, with no
4136// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004137// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004138//===----------------------------------------------------------------------===//
4139namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004140class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004141 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004142public:
Richard Smith027bf112011-11-17 22:56:20 +00004143 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4144 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004145
Richard Smith11562c52011-10-28 17:51:58 +00004146 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004147 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004148
Peter Collingbournee9200682011-05-13 03:29:01 +00004149 bool VisitDeclRefExpr(const DeclRefExpr *E);
4150 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004151 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004152 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4153 bool VisitMemberExpr(const MemberExpr *E);
4154 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4155 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004156 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004157 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004158 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4159 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004160 bool VisitUnaryReal(const UnaryOperator *E);
4161 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004162 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4163 return VisitUnaryPreIncDec(UO);
4164 }
4165 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4166 return VisitUnaryPreIncDec(UO);
4167 }
Richard Smith3229b742013-05-05 21:17:10 +00004168 bool VisitBinAssign(const BinaryOperator *BO);
4169 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004170
Peter Collingbournee9200682011-05-13 03:29:01 +00004171 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004172 switch (E->getCastKind()) {
4173 default:
Richard Smith027bf112011-11-17 22:56:20 +00004174 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004175
Eli Friedmance3e02a2011-10-11 00:13:24 +00004176 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004177 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004178 if (!Visit(E->getSubExpr()))
4179 return false;
4180 Result.Designator.setInvalid();
4181 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004182
Richard Smith027bf112011-11-17 22:56:20 +00004183 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004184 if (!Visit(E->getSubExpr()))
4185 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004186 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004187 }
4188 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004189};
4190} // end anonymous namespace
4191
Richard Smith11562c52011-10-28 17:51:58 +00004192/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smith9f8400e2013-05-01 19:00:39 +00004193/// expressions which are not glvalues, in two cases:
4194/// * function designators in C, and
4195/// * "extern void" objects
4196static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4197 assert(E->isGLValue() || E->getType()->isFunctionType() ||
4198 E->getType()->isVoidType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004199 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004200}
4201
Peter Collingbournee9200682011-05-13 03:29:01 +00004202bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004203 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
4204 return Success(FD);
4205 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004206 return VisitVarDecl(E, VD);
4207 return Error(E);
4208}
Richard Smith733237d2011-10-24 23:14:33 +00004209
Richard Smith11562c52011-10-28 17:51:58 +00004210bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith3229b742013-05-05 21:17:10 +00004211 CallStackFrame *Frame = 0;
4212 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4213 Frame = Info.CurrentCall;
4214
Richard Smithfec09922011-11-01 16:57:24 +00004215 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004216 if (Frame) {
4217 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004218 return true;
4219 }
Richard Smithce40ad62011-11-12 22:28:03 +00004220 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004221 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004222
Richard Smith3229b742013-05-05 21:17:10 +00004223 APValue *V;
4224 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004225 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004226 if (V->isUninit()) {
4227 if (!Info.CheckingPotentialConstantExpression)
4228 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4229 return false;
4230 }
Richard Smith3229b742013-05-05 21:17:10 +00004231 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004232}
4233
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004234bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4235 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004236 // Walk through the expression to find the materialized temporary itself.
4237 SmallVector<const Expr *, 2> CommaLHSs;
4238 SmallVector<SubobjectAdjustment, 2> Adjustments;
4239 const Expr *Inner = E->GetTemporaryExpr()->
4240 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004241
Richard Smith84401042013-06-03 05:03:02 +00004242 // If we passed any comma operators, evaluate their LHSs.
4243 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4244 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4245 return false;
4246
Richard Smithe6c01442013-06-05 00:46:14 +00004247 // A materialized temporary with static storage duration can appear within the
4248 // result of a constant expression evaluation, so we need to preserve its
4249 // value for use outside this evaluation.
4250 APValue *Value;
4251 if (E->getStorageDuration() == SD_Static) {
4252 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004253 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004254 Result.set(E);
4255 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004256 Value = &Info.CurrentCall->
4257 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00004258 Result.set(E, Info.CurrentCall->Index);
4259 }
4260
Richard Smithea4ad5d2013-06-06 08:19:16 +00004261 QualType Type = Inner->getType();
4262
Richard Smith84401042013-06-03 05:03:02 +00004263 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004264 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4265 (E->getStorageDuration() == SD_Static &&
4266 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4267 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004268 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004269 }
Richard Smith84401042013-06-03 05:03:02 +00004270
4271 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004272 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4273 --I;
4274 switch (Adjustments[I].Kind) {
4275 case SubobjectAdjustment::DerivedToBaseAdjustment:
4276 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4277 Type, Result))
4278 return false;
4279 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4280 break;
4281
4282 case SubobjectAdjustment::FieldAdjustment:
4283 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4284 return false;
4285 Type = Adjustments[I].Field->getType();
4286 break;
4287
4288 case SubobjectAdjustment::MemberPointerAdjustment:
4289 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4290 Adjustments[I].Ptr.RHS))
4291 return false;
4292 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4293 break;
4294 }
4295 }
4296
4297 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004298}
4299
Peter Collingbournee9200682011-05-13 03:29:01 +00004300bool
4301LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004302 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4303 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4304 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004305 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004306}
4307
Richard Smith6e525142011-12-27 12:18:28 +00004308bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004309 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004310 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004311
4312 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4313 << E->getExprOperand()->getType()
4314 << E->getExprOperand()->getSourceRange();
4315 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004316}
4317
Francois Pichet0066db92012-04-16 04:08:35 +00004318bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4319 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004320}
Francois Pichet0066db92012-04-16 04:08:35 +00004321
Peter Collingbournee9200682011-05-13 03:29:01 +00004322bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004323 // Handle static data members.
4324 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4325 VisitIgnoredValue(E->getBase());
4326 return VisitVarDecl(E, VD);
4327 }
4328
Richard Smith254a73d2011-10-28 22:34:42 +00004329 // Handle static member functions.
4330 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4331 if (MD->isStatic()) {
4332 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004333 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004334 }
4335 }
4336
Richard Smithd62306a2011-11-10 06:34:14 +00004337 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004338 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004339}
4340
Peter Collingbournee9200682011-05-13 03:29:01 +00004341bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004342 // FIXME: Deal with vectors as array subscript bases.
4343 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004344 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004345
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004346 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004347 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004348
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004349 APSInt Index;
4350 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004351 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004352
Richard Smith861b5b52013-05-07 23:34:45 +00004353 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4354 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004355}
Eli Friedman9a156e52008-11-12 09:44:48 +00004356
Peter Collingbournee9200682011-05-13 03:29:01 +00004357bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004358 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004359}
4360
Richard Smith66c96992012-02-18 22:04:06 +00004361bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4362 if (!Visit(E->getSubExpr()))
4363 return false;
4364 // __real is a no-op on scalar lvalues.
4365 if (E->getSubExpr()->getType()->isAnyComplexType())
4366 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4367 return true;
4368}
4369
4370bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4371 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4372 "lvalue __imag__ on scalar?");
4373 if (!Visit(E->getSubExpr()))
4374 return false;
4375 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4376 return true;
4377}
4378
Richard Smith243ef902013-05-05 23:31:59 +00004379bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4380 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004381 return Error(UO);
4382
4383 if (!this->Visit(UO->getSubExpr()))
4384 return false;
4385
Richard Smith243ef902013-05-05 23:31:59 +00004386 return handleIncDec(
4387 this->Info, UO, Result, UO->getSubExpr()->getType(),
4388 UO->isIncrementOp(), 0);
Richard Smith3229b742013-05-05 21:17:10 +00004389}
4390
4391bool LValueExprEvaluator::VisitCompoundAssignOperator(
4392 const CompoundAssignOperator *CAO) {
Richard Smith243ef902013-05-05 23:31:59 +00004393 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004394 return Error(CAO);
4395
Richard Smith3229b742013-05-05 21:17:10 +00004396 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004397
4398 // The overall lvalue result is the result of evaluating the LHS.
4399 if (!this->Visit(CAO->getLHS())) {
4400 if (Info.keepEvaluatingAfterFailure())
4401 Evaluate(RHS, this->Info, CAO->getRHS());
4402 return false;
4403 }
4404
Richard Smith3229b742013-05-05 21:17:10 +00004405 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4406 return false;
4407
Richard Smith43e77732013-05-07 04:50:00 +00004408 return handleCompoundAssignment(
4409 this->Info, CAO,
4410 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4411 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004412}
4413
4414bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Richard Smith243ef902013-05-05 23:31:59 +00004415 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4416 return Error(E);
4417
Richard Smith3229b742013-05-05 21:17:10 +00004418 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004419
4420 if (!this->Visit(E->getLHS())) {
4421 if (Info.keepEvaluatingAfterFailure())
4422 Evaluate(NewVal, this->Info, E->getRHS());
4423 return false;
4424 }
4425
Richard Smith3229b742013-05-05 21:17:10 +00004426 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4427 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004428
4429 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004430 NewVal);
4431}
4432
Eli Friedman9a156e52008-11-12 09:44:48 +00004433//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004434// Pointer Evaluation
4435//===----------------------------------------------------------------------===//
4436
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004437namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004438class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004439 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00004440 LValue &Result;
4441
Peter Collingbournee9200682011-05-13 03:29:01 +00004442 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004443 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004444 return true;
4445 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004446public:
Mike Stump11289f42009-09-09 15:08:12 +00004447
John McCall45d55e42010-05-07 21:00:08 +00004448 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004449 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004450
Richard Smith2e312c82012-03-03 22:46:17 +00004451 bool Success(const APValue &V, const Expr *E) {
4452 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004453 return true;
4454 }
Richard Smithfddd3842011-12-30 21:15:51 +00004455 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00004456 return Success((Expr*)0);
4457 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004458
John McCall45d55e42010-05-07 21:00:08 +00004459 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004460 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004461 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004462 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004463 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004464 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00004465 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004466 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004467 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004468 bool VisitCallExpr(const CallExpr *E);
4469 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004470 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004471 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004472 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004473 }
Richard Smithd62306a2011-11-10 06:34:14 +00004474 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004475 // Can't look at 'this' when checking a potential constant expression.
4476 if (Info.CheckingPotentialConstantExpression)
4477 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004478 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004479 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004480 Result = *Info.CurrentCall->This;
4481 return true;
4482 }
John McCallc07a0c72011-02-17 10:25:35 +00004483
Eli Friedman449fe542009-03-23 04:56:01 +00004484 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004485};
Chris Lattner05706e882008-07-11 18:11:29 +00004486} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004487
John McCall45d55e42010-05-07 21:00:08 +00004488static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004489 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004490 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004491}
4492
John McCall45d55e42010-05-07 21:00:08 +00004493bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004494 if (E->getOpcode() != BO_Add &&
4495 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004496 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004497
Chris Lattner05706e882008-07-11 18:11:29 +00004498 const Expr *PExp = E->getLHS();
4499 const Expr *IExp = E->getRHS();
4500 if (IExp->getType()->isPointerType())
4501 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004502
Richard Smith253c2a32012-01-27 01:14:48 +00004503 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4504 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004505 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004506
John McCall45d55e42010-05-07 21:00:08 +00004507 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004508 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004509 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004510
4511 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004512 if (E->getOpcode() == BO_Sub)
4513 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004514
Ted Kremenek28831752012-08-23 20:46:57 +00004515 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004516 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4517 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004518}
Eli Friedman9a156e52008-11-12 09:44:48 +00004519
John McCall45d55e42010-05-07 21:00:08 +00004520bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4521 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004522}
Mike Stump11289f42009-09-09 15:08:12 +00004523
Peter Collingbournee9200682011-05-13 03:29:01 +00004524bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4525 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004526
Eli Friedman847a2bc2009-12-27 05:43:15 +00004527 switch (E->getCastKind()) {
4528 default:
4529 break;
4530
John McCalle3027922010-08-25 11:45:40 +00004531 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004532 case CK_CPointerToObjCPointerCast:
4533 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004534 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004535 if (!Visit(SubExpr))
4536 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004537 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4538 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4539 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004540 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004541 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004542 if (SubExpr->getType()->isVoidPointerType())
4543 CCEDiag(E, diag::note_constexpr_invalid_cast)
4544 << 3 << SubExpr->getType();
4545 else
4546 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4547 }
Richard Smith96e0c102011-11-04 02:25:55 +00004548 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004549
Anders Carlsson18275092010-10-31 20:41:46 +00004550 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004551 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00004552 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004553 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004554 if (!Result.Base && Result.Offset.isZero())
4555 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00004556
Richard Smithd62306a2011-11-10 06:34:14 +00004557 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00004558 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004559 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4560 castAs<PointerType>()->getPointeeType(),
4561 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00004562
Richard Smith027bf112011-11-17 22:56:20 +00004563 case CK_BaseToDerived:
4564 if (!Visit(E->getSubExpr()))
4565 return false;
4566 if (!Result.Base && Result.Offset.isZero())
4567 return true;
4568 return HandleBaseToDerivedCast(Info, E, Result);
4569
Richard Smith0b0a0b62011-10-29 20:57:55 +00004570 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004571 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004572 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00004573
John McCalle3027922010-08-25 11:45:40 +00004574 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004575 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4576
Richard Smith2e312c82012-03-03 22:46:17 +00004577 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00004578 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00004579 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00004580
John McCall45d55e42010-05-07 21:00:08 +00004581 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004582 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4583 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00004584 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004585 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00004586 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00004587 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004588 return true;
4589 } else {
4590 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00004591 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00004592 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00004593 }
4594 }
John McCalle3027922010-08-25 11:45:40 +00004595 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00004596 if (SubExpr->isGLValue()) {
4597 if (!EvaluateLValue(SubExpr, Result, Info))
4598 return false;
4599 } else {
Richard Smithb228a862012-02-15 02:18:13 +00004600 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004601 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00004602 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00004603 return false;
4604 }
Richard Smith96e0c102011-11-04 02:25:55 +00004605 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00004606 if (const ConstantArrayType *CAT
4607 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4608 Result.addArray(Info, E, CAT);
4609 else
4610 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00004611 return true;
Richard Smithdd785442011-10-31 20:57:44 +00004612
John McCalle3027922010-08-25 11:45:40 +00004613 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00004614 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004615 }
4616
Richard Smith11562c52011-10-28 17:51:58 +00004617 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00004618}
Chris Lattner05706e882008-07-11 18:11:29 +00004619
Peter Collingbournee9200682011-05-13 03:29:01 +00004620bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004621 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00004622 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00004623
Richard Smith6cbd65d2013-07-11 02:27:57 +00004624 switch (E->isBuiltinCall()) {
4625 case Builtin::BI__builtin_addressof:
4626 return EvaluateLValue(E->getArg(0), Result, Info);
4627
4628 default:
4629 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4630 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004631}
Chris Lattner05706e882008-07-11 18:11:29 +00004632
4633//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004634// Member Pointer Evaluation
4635//===----------------------------------------------------------------------===//
4636
4637namespace {
4638class MemberPointerExprEvaluator
4639 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
4640 MemberPtr &Result;
4641
4642 bool Success(const ValueDecl *D) {
4643 Result = MemberPtr(D);
4644 return true;
4645 }
4646public:
4647
4648 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
4649 : ExprEvaluatorBaseTy(Info), Result(Result) {}
4650
Richard Smith2e312c82012-03-03 22:46:17 +00004651 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004652 Result.setFrom(V);
4653 return true;
4654 }
Richard Smithfddd3842011-12-30 21:15:51 +00004655 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004656 return Success((const ValueDecl*)0);
4657 }
4658
4659 bool VisitCastExpr(const CastExpr *E);
4660 bool VisitUnaryAddrOf(const UnaryOperator *E);
4661};
4662} // end anonymous namespace
4663
4664static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
4665 EvalInfo &Info) {
4666 assert(E->isRValue() && E->getType()->isMemberPointerType());
4667 return MemberPointerExprEvaluator(Info, Result).Visit(E);
4668}
4669
4670bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
4671 switch (E->getCastKind()) {
4672 default:
4673 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4674
4675 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004676 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004677 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004678
4679 case CK_BaseToDerivedMemberPointer: {
4680 if (!Visit(E->getSubExpr()))
4681 return false;
4682 if (E->path_empty())
4683 return true;
4684 // Base-to-derived member pointer casts store the path in derived-to-base
4685 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
4686 // the wrong end of the derived->base arc, so stagger the path by one class.
4687 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
4688 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
4689 PathI != PathE; ++PathI) {
4690 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4691 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
4692 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004693 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004694 }
4695 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
4696 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004697 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004698 return true;
4699 }
4700
4701 case CK_DerivedToBaseMemberPointer:
4702 if (!Visit(E->getSubExpr()))
4703 return false;
4704 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4705 PathE = E->path_end(); PathI != PathE; ++PathI) {
4706 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4707 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4708 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004709 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004710 }
4711 return true;
4712 }
4713}
4714
4715bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4716 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
4717 // member can be formed.
4718 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
4719}
4720
4721//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00004722// Record Evaluation
4723//===----------------------------------------------------------------------===//
4724
4725namespace {
4726 class RecordExprEvaluator
4727 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
4728 const LValue &This;
4729 APValue &Result;
4730 public:
4731
4732 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
4733 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
4734
Richard Smith2e312c82012-03-03 22:46:17 +00004735 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004736 Result = V;
4737 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00004738 }
Richard Smithfddd3842011-12-30 21:15:51 +00004739 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004740
Richard Smithe97cbd72011-11-11 04:05:33 +00004741 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004742 bool VisitInitListExpr(const InitListExpr *E);
4743 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc1b96d2013-06-12 22:31:48 +00004744 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004745 };
4746}
4747
Richard Smithfddd3842011-12-30 21:15:51 +00004748/// Perform zero-initialization on an object of non-union class type.
4749/// C++11 [dcl.init]p5:
4750/// To zero-initialize an object or reference of type T means:
4751/// [...]
4752/// -- if T is a (possibly cv-qualified) non-union class type,
4753/// each non-static data member and each base-class subobject is
4754/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00004755static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
4756 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00004757 const LValue &This, APValue &Result) {
4758 assert(!RD->isUnion() && "Expected non-union class type");
4759 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
4760 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
4761 std::distance(RD->field_begin(), RD->field_end()));
4762
John McCalld7bca762012-05-01 00:38:49 +00004763 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004764 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4765
4766 if (CD) {
4767 unsigned Index = 0;
4768 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00004769 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00004770 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4771 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004772 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4773 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004774 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00004775 Result.getStructBase(Index)))
4776 return false;
4777 }
4778 }
4779
Richard Smitha8105bc2012-01-06 16:39:00 +00004780 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
4781 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00004782 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004783 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00004784 continue;
4785
4786 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004787 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004788 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004789
David Blaikie2d7c57e2012-04-30 02:36:29 +00004790 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004791 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00004792 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004793 return false;
4794 }
4795
4796 return true;
4797}
4798
4799bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
4800 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004801 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004802 if (RD->isUnion()) {
4803 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4804 // object's first non-static named data member is zero-initialized
4805 RecordDecl::field_iterator I = RD->field_begin();
4806 if (I == RD->field_end()) {
4807 Result = APValue((const FieldDecl*)0);
4808 return true;
4809 }
4810
4811 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004812 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00004813 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00004814 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00004815 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004816 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004817 }
4818
Richard Smith5d108602012-02-17 00:44:16 +00004819 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004820 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00004821 return false;
4822 }
4823
Richard Smitha8105bc2012-01-06 16:39:00 +00004824 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00004825}
4826
Richard Smithe97cbd72011-11-11 04:05:33 +00004827bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
4828 switch (E->getCastKind()) {
4829 default:
4830 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4831
4832 case CK_ConstructorConversion:
4833 return Visit(E->getSubExpr());
4834
4835 case CK_DerivedToBase:
4836 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00004837 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004838 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00004839 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004840 if (!DerivedObject.isStruct())
4841 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00004842
4843 // Derived-to-base rvalue conversion: just slice off the derived part.
4844 APValue *Value = &DerivedObject;
4845 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
4846 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4847 PathE = E->path_end(); PathI != PathE; ++PathI) {
4848 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
4849 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4850 Value = &Value->getStructBase(getBaseIndex(RD, Base));
4851 RD = Base;
4852 }
4853 Result = *Value;
4854 return true;
4855 }
4856 }
4857}
4858
Richard Smithd62306a2011-11-10 06:34:14 +00004859bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
4860 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004861 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004862 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4863
4864 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00004865 const FieldDecl *Field = E->getInitializedFieldInUnion();
4866 Result = APValue(Field);
4867 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00004868 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00004869
4870 // If the initializer list for a union does not contain any elements, the
4871 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00004872 // FIXME: The element should be initialized from an initializer list.
4873 // Is this difference ever observable for initializer lists which
4874 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00004875 ImplicitValueInitExpr VIE(Field->getType());
4876 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
4877
Richard Smithd62306a2011-11-10 06:34:14 +00004878 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004879 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
4880 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00004881
4882 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4883 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4884 isa<CXXDefaultInitExpr>(InitExpr));
4885
Richard Smithb228a862012-02-15 02:18:13 +00004886 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00004887 }
4888
4889 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
4890 "initializer list for class with base classes");
4891 Result = APValue(APValue::UninitStruct(), 0,
4892 std::distance(RD->field_begin(), RD->field_end()));
4893 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00004894 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004895 for (RecordDecl::field_iterator Field = RD->field_begin(),
4896 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
4897 // Anonymous bit-fields are not considered members of the class for
4898 // purposes of aggregate initialization.
4899 if (Field->isUnnamedBitfield())
4900 continue;
4901
4902 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00004903
Richard Smith253c2a32012-01-27 01:14:48 +00004904 bool HaveInit = ElementNo < E->getNumInits();
4905
4906 // FIXME: Diagnostics here should point to the end of the initializer
4907 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00004908 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie40ed2972012-06-06 20:45:41 +00004909 Subobject, *Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004910 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004911
4912 // Perform an implicit value-initialization for members beyond the end of
4913 // the initializer list.
4914 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00004915 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00004916
Richard Smith852c9db2013-04-20 22:23:05 +00004917 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4918 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4919 isa<CXXDefaultInitExpr>(Init));
4920
4921 if (!EvaluateInPlace(Result.getStructField(Field->getFieldIndex()), Info,
4922 Subobject, Init)) {
Richard Smith253c2a32012-01-27 01:14:48 +00004923 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00004924 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004925 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00004926 }
4927 }
4928
Richard Smith253c2a32012-01-27 01:14:48 +00004929 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004930}
4931
4932bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
4933 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00004934 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
4935
Richard Smithfddd3842011-12-30 21:15:51 +00004936 bool ZeroInit = E->requiresZeroInitialization();
4937 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00004938 // If we've already performed zero-initialization, we're already done.
4939 if (!Result.isUninit())
4940 return true;
4941
Richard Smithfddd3842011-12-30 21:15:51 +00004942 if (ZeroInit)
4943 return ZeroInitialization(E);
4944
Richard Smithcc36f692011-12-22 02:22:31 +00004945 const CXXRecordDecl *RD = FD->getParent();
4946 if (RD->isUnion())
4947 Result = APValue((FieldDecl*)0);
4948 else
4949 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4950 std::distance(RD->field_begin(), RD->field_end()));
4951 return true;
4952 }
4953
Richard Smithd62306a2011-11-10 06:34:14 +00004954 const FunctionDecl *Definition = 0;
4955 FD->getBody(Definition);
4956
Richard Smith357362d2011-12-13 06:39:58 +00004957 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
4958 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004959
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004960 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00004961 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00004962 if (const MaterializeTemporaryExpr *ME
4963 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
4964 return Visit(ME->GetTemporaryExpr());
4965
Richard Smithfddd3842011-12-30 21:15:51 +00004966 if (ZeroInit && !ZeroInitialization(E))
4967 return false;
4968
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004969 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00004970 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004971 cast<CXXConstructorDecl>(Definition), Info,
4972 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00004973}
4974
Richard Smithcc1b96d2013-06-12 22:31:48 +00004975bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
4976 const CXXStdInitializerListExpr *E) {
4977 const ConstantArrayType *ArrayType =
4978 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
4979
4980 LValue Array;
4981 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
4982 return false;
4983
4984 // Get a pointer to the first element of the array.
4985 Array.addArray(Info, E, ArrayType);
4986
4987 // FIXME: Perform the checks on the field types in SemaInit.
4988 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
4989 RecordDecl::field_iterator Field = Record->field_begin();
4990 if (Field == Record->field_end())
4991 return Error(E);
4992
4993 // Start pointer.
4994 if (!Field->getType()->isPointerType() ||
4995 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
4996 ArrayType->getElementType()))
4997 return Error(E);
4998
4999 // FIXME: What if the initializer_list type has base classes, etc?
5000 Result = APValue(APValue::UninitStruct(), 0, 2);
5001 Array.moveInto(Result.getStructField(0));
5002
5003 if (++Field == Record->field_end())
5004 return Error(E);
5005
5006 if (Field->getType()->isPointerType() &&
5007 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5008 ArrayType->getElementType())) {
5009 // End pointer.
5010 if (!HandleLValueArrayAdjustment(Info, E, Array,
5011 ArrayType->getElementType(),
5012 ArrayType->getSize().getZExtValue()))
5013 return false;
5014 Array.moveInto(Result.getStructField(1));
5015 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5016 // Length.
5017 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5018 else
5019 return Error(E);
5020
5021 if (++Field != Record->field_end())
5022 return Error(E);
5023
5024 return true;
5025}
5026
Richard Smithd62306a2011-11-10 06:34:14 +00005027static bool EvaluateRecord(const Expr *E, const LValue &This,
5028 APValue &Result, EvalInfo &Info) {
5029 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005030 "can't evaluate expression as a record rvalue");
5031 return RecordExprEvaluator(Info, This, Result).Visit(E);
5032}
5033
5034//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005035// Temporary Evaluation
5036//
5037// Temporaries are represented in the AST as rvalues, but generally behave like
5038// lvalues. The full-object of which the temporary is a subobject is implicitly
5039// materialized so that a reference can bind to it.
5040//===----------------------------------------------------------------------===//
5041namespace {
5042class TemporaryExprEvaluator
5043 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5044public:
5045 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5046 LValueExprEvaluatorBaseTy(Info, Result) {}
5047
5048 /// Visit an expression which constructs the value of this temporary.
5049 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005050 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005051 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5052 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005053 }
5054
5055 bool VisitCastExpr(const CastExpr *E) {
5056 switch (E->getCastKind()) {
5057 default:
5058 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5059
5060 case CK_ConstructorConversion:
5061 return VisitConstructExpr(E->getSubExpr());
5062 }
5063 }
5064 bool VisitInitListExpr(const InitListExpr *E) {
5065 return VisitConstructExpr(E);
5066 }
5067 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5068 return VisitConstructExpr(E);
5069 }
5070 bool VisitCallExpr(const CallExpr *E) {
5071 return VisitConstructExpr(E);
5072 }
5073};
5074} // end anonymous namespace
5075
5076/// Evaluate an expression of record type as a temporary.
5077static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005078 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005079 return TemporaryExprEvaluator(Info, Result).Visit(E);
5080}
5081
5082//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005083// Vector Evaluation
5084//===----------------------------------------------------------------------===//
5085
5086namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005087 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00005088 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
5089 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005090 public:
Mike Stump11289f42009-09-09 15:08:12 +00005091
Richard Smith2d406342011-10-22 21:10:00 +00005092 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5093 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00005094
Richard Smith2d406342011-10-22 21:10:00 +00005095 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
5096 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5097 // FIXME: remove this APValue copy.
5098 Result = APValue(V.data(), V.size());
5099 return true;
5100 }
Richard Smith2e312c82012-03-03 22:46:17 +00005101 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00005102 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00005103 Result = V;
5104 return true;
5105 }
Richard Smithfddd3842011-12-30 21:15:51 +00005106 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00005107
Richard Smith2d406342011-10-22 21:10:00 +00005108 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00005109 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00005110 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00005111 bool VisitInitListExpr(const InitListExpr *E);
5112 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005113 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00005114 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00005115 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005116 };
5117} // end anonymous namespace
5118
5119static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005120 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00005121 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005122}
5123
Richard Smith2d406342011-10-22 21:10:00 +00005124bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5125 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005126 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005127
Richard Smith161f09a2011-12-06 22:44:34 +00005128 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00005129 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005130
Eli Friedmanc757de22011-03-25 00:43:55 +00005131 switch (E->getCastKind()) {
5132 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00005133 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00005134 if (SETy->isIntegerType()) {
5135 APSInt IntResult;
5136 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005137 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005138 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00005139 } else if (SETy->isRealFloatingType()) {
5140 APFloat F(0.0);
5141 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005142 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005143 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00005144 } else {
Richard Smith2d406342011-10-22 21:10:00 +00005145 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005146 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005147
5148 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00005149 SmallVector<APValue, 4> Elts(NElts, Val);
5150 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00005151 }
Eli Friedman803acb32011-12-22 03:51:45 +00005152 case CK_BitCast: {
5153 // Evaluate the operand into an APInt we can extract from.
5154 llvm::APInt SValInt;
5155 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5156 return false;
5157 // Extract the elements
5158 QualType EltTy = VTy->getElementType();
5159 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5160 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5161 SmallVector<APValue, 4> Elts;
5162 if (EltTy->isRealFloatingType()) {
5163 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00005164 unsigned FloatEltSize = EltSize;
5165 if (&Sem == &APFloat::x87DoubleExtended)
5166 FloatEltSize = 80;
5167 for (unsigned i = 0; i < NElts; i++) {
5168 llvm::APInt Elt;
5169 if (BigEndian)
5170 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5171 else
5172 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00005173 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00005174 }
5175 } else if (EltTy->isIntegerType()) {
5176 for (unsigned i = 0; i < NElts; i++) {
5177 llvm::APInt Elt;
5178 if (BigEndian)
5179 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5180 else
5181 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5182 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5183 }
5184 } else {
5185 return Error(E);
5186 }
5187 return Success(Elts, E);
5188 }
Eli Friedmanc757de22011-03-25 00:43:55 +00005189 default:
Richard Smith11562c52011-10-28 17:51:58 +00005190 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005191 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005192}
5193
Richard Smith2d406342011-10-22 21:10:00 +00005194bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005195VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005196 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005197 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00005198 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005199
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005200 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005201 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005202
Eli Friedmanb9c71292012-01-03 23:24:20 +00005203 // The number of initializers can be less than the number of
5204 // vector elements. For OpenCL, this can be due to nested vector
5205 // initialization. For GCC compatibility, missing trailing elements
5206 // should be initialized with zeroes.
5207 unsigned CountInits = 0, CountElts = 0;
5208 while (CountElts < NumElements) {
5209 // Handle nested vector initialization.
5210 if (CountInits < NumInits
5211 && E->getInit(CountInits)->getType()->isExtVectorType()) {
5212 APValue v;
5213 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5214 return Error(E);
5215 unsigned vlen = v.getVectorLength();
5216 for (unsigned j = 0; j < vlen; j++)
5217 Elements.push_back(v.getVectorElt(j));
5218 CountElts += vlen;
5219 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005220 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005221 if (CountInits < NumInits) {
5222 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005223 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005224 } else // trailing integer zero.
5225 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5226 Elements.push_back(APValue(sInt));
5227 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005228 } else {
5229 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005230 if (CountInits < NumInits) {
5231 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005232 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005233 } else // trailing float zero.
5234 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5235 Elements.push_back(APValue(f));
5236 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00005237 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00005238 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005239 }
Richard Smith2d406342011-10-22 21:10:00 +00005240 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005241}
5242
Richard Smith2d406342011-10-22 21:10:00 +00005243bool
Richard Smithfddd3842011-12-30 21:15:51 +00005244VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005245 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00005246 QualType EltTy = VT->getElementType();
5247 APValue ZeroElement;
5248 if (EltTy->isIntegerType())
5249 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5250 else
5251 ZeroElement =
5252 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5253
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005254 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00005255 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005256}
5257
Richard Smith2d406342011-10-22 21:10:00 +00005258bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00005259 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005260 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005261}
5262
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005263//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00005264// Array Evaluation
5265//===----------------------------------------------------------------------===//
5266
5267namespace {
5268 class ArrayExprEvaluator
5269 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00005270 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00005271 APValue &Result;
5272 public:
5273
Richard Smithd62306a2011-11-10 06:34:14 +00005274 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5275 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00005276
5277 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00005278 assert((V.isArray() || V.isLValue()) &&
5279 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00005280 Result = V;
5281 return true;
5282 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005283
Richard Smithfddd3842011-12-30 21:15:51 +00005284 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005285 const ConstantArrayType *CAT =
5286 Info.Ctx.getAsConstantArrayType(E->getType());
5287 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005288 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005289
5290 Result = APValue(APValue::UninitArray(), 0,
5291 CAT->getSize().getZExtValue());
5292 if (!Result.hasArrayFiller()) return true;
5293
Richard Smithfddd3842011-12-30 21:15:51 +00005294 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00005295 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005296 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00005297 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00005298 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00005299 }
5300
Richard Smithf3e9e432011-11-07 09:22:26 +00005301 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00005302 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00005303 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5304 const LValue &Subobject,
5305 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00005306 };
5307} // end anonymous namespace
5308
Richard Smithd62306a2011-11-10 06:34:14 +00005309static bool EvaluateArray(const Expr *E, const LValue &This,
5310 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00005311 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00005312 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005313}
5314
5315bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5316 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5317 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005318 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005319
Richard Smithca2cfbf2011-12-22 01:07:19 +00005320 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5321 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00005322 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00005323 LValue LV;
5324 if (!EvaluateLValue(E->getInit(0), LV, Info))
5325 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005326 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00005327 LV.moveInto(Val);
5328 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00005329 }
5330
Richard Smith253c2a32012-01-27 01:14:48 +00005331 bool Success = true;
5332
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005333 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5334 "zero-initialized array shouldn't have any initialized elts");
5335 APValue Filler;
5336 if (Result.isArray() && Result.hasArrayFiller())
5337 Filler = Result.getArrayFiller();
5338
Richard Smith9543c5e2013-04-22 14:44:29 +00005339 unsigned NumEltsToInit = E->getNumInits();
5340 unsigned NumElts = CAT->getSize().getZExtValue();
5341 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
5342
5343 // If the initializer might depend on the array index, run it for each
5344 // array element. For now, just whitelist non-class value-initialization.
5345 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5346 NumEltsToInit = NumElts;
5347
5348 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005349
5350 // If the array was previously zero-initialized, preserve the
5351 // zero-initialized values.
5352 if (!Filler.isUninit()) {
5353 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5354 Result.getArrayInitializedElt(I) = Filler;
5355 if (Result.hasArrayFiller())
5356 Result.getArrayFiller() = Filler;
5357 }
5358
Richard Smithd62306a2011-11-10 06:34:14 +00005359 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005360 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00005361 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5362 const Expr *Init =
5363 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00005364 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00005365 Info, Subobject, Init) ||
5366 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00005367 CAT->getElementType(), 1)) {
5368 if (!Info.keepEvaluatingAfterFailure())
5369 return false;
5370 Success = false;
5371 }
Richard Smithd62306a2011-11-10 06:34:14 +00005372 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005373
Richard Smith9543c5e2013-04-22 14:44:29 +00005374 if (!Result.hasArrayFiller())
5375 return Success;
5376
5377 // If we get here, we have a trivial filler, which we can just evaluate
5378 // once and splat over the rest of the array elements.
5379 assert(FillerExpr && "no array filler for incomplete init list");
5380 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5381 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00005382}
5383
Richard Smith027bf112011-11-17 22:56:20 +00005384bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005385 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5386}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005387
Richard Smith9543c5e2013-04-22 14:44:29 +00005388bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5389 const LValue &Subobject,
5390 APValue *Value,
5391 QualType Type) {
5392 bool HadZeroInit = !Value->isUninit();
5393
5394 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5395 unsigned N = CAT->getSize().getZExtValue();
5396
5397 // Preserve the array filler if we had prior zero-initialization.
5398 APValue Filler =
5399 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5400 : APValue();
5401
5402 *Value = APValue(APValue::UninitArray(), N, N);
5403
5404 if (HadZeroInit)
5405 for (unsigned I = 0; I != N; ++I)
5406 Value->getArrayInitializedElt(I) = Filler;
5407
5408 // Initialize the elements.
5409 LValue ArrayElt = Subobject;
5410 ArrayElt.addArray(Info, E, CAT);
5411 for (unsigned I = 0; I != N; ++I)
5412 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5413 CAT->getElementType()) ||
5414 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5415 CAT->getElementType(), 1))
5416 return false;
5417
5418 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005419 }
Richard Smith027bf112011-11-17 22:56:20 +00005420
Richard Smith9543c5e2013-04-22 14:44:29 +00005421 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00005422 return Error(E);
5423
Richard Smith027bf112011-11-17 22:56:20 +00005424 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00005425
Richard Smithfddd3842011-12-30 21:15:51 +00005426 bool ZeroInit = E->requiresZeroInitialization();
5427 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005428 if (HadZeroInit)
5429 return true;
5430
Richard Smithfddd3842011-12-30 21:15:51 +00005431 if (ZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005432 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005433 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005434 }
5435
Richard Smithcc36f692011-12-22 02:22:31 +00005436 const CXXRecordDecl *RD = FD->getParent();
5437 if (RD->isUnion())
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005438 *Value = APValue((FieldDecl*)0);
Richard Smithcc36f692011-12-22 02:22:31 +00005439 else
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005440 *Value =
Richard Smithcc36f692011-12-22 02:22:31 +00005441 APValue(APValue::UninitStruct(), RD->getNumBases(),
5442 std::distance(RD->field_begin(), RD->field_end()));
5443 return true;
5444 }
5445
Richard Smith027bf112011-11-17 22:56:20 +00005446 const FunctionDecl *Definition = 0;
5447 FD->getBody(Definition);
5448
Richard Smith357362d2011-12-13 06:39:58 +00005449 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5450 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005451
Richard Smith9eae7232012-01-12 18:54:33 +00005452 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005453 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005454 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005455 return false;
5456 }
5457
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005458 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005459 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00005460 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005461 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00005462}
5463
Richard Smithf3e9e432011-11-07 09:22:26 +00005464//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005465// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005466//
5467// As a GNU extension, we support casting pointers to sufficiently-wide integer
5468// types and back in constant folding. Integer values are thus represented
5469// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00005470//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005471
5472namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005473class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00005474 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith2e312c82012-03-03 22:46:17 +00005475 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005476public:
Richard Smith2e312c82012-03-03 22:46:17 +00005477 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005478 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005479
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005480 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005481 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005482 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005483 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005484 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005485 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005486 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005487 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005488 return true;
5489 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005490 bool Success(const llvm::APSInt &SI, const Expr *E) {
5491 return Success(SI, E, Result);
5492 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005493
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005494 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005495 assert(E->getType()->isIntegralOrEnumerationType() &&
5496 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005497 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005498 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005499 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005500 Result.getInt().setIsUnsigned(
5501 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005502 return true;
5503 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005504 bool Success(const llvm::APInt &I, const Expr *E) {
5505 return Success(I, E, Result);
5506 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005507
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005508 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005509 assert(E->getType()->isIntegralOrEnumerationType() &&
5510 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005511 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005512 return true;
5513 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005514 bool Success(uint64_t Value, const Expr *E) {
5515 return Success(Value, E, Result);
5516 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005517
Ken Dyckdbc01912011-03-11 02:13:43 +00005518 bool Success(CharUnits Size, const Expr *E) {
5519 return Success(Size.getQuantity(), E);
5520 }
5521
Richard Smith2e312c82012-03-03 22:46:17 +00005522 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005523 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00005524 Result = V;
5525 return true;
5526 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005527 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00005528 }
Mike Stump11289f42009-09-09 15:08:12 +00005529
Richard Smithfddd3842011-12-30 21:15:51 +00005530 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00005531
Peter Collingbournee9200682011-05-13 03:29:01 +00005532 //===--------------------------------------------------------------------===//
5533 // Visitor Methods
5534 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005535
Chris Lattner7174bf32008-07-12 00:38:25 +00005536 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005537 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005538 }
5539 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005540 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005541 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005542
5543 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5544 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005545 if (CheckReferencedDecl(E, E->getDecl()))
5546 return true;
5547
5548 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005549 }
5550 bool VisitMemberExpr(const MemberExpr *E) {
5551 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00005552 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005553 return true;
5554 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005555
5556 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005557 }
5558
Peter Collingbournee9200682011-05-13 03:29:01 +00005559 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005560 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00005561 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005562 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00005563
Peter Collingbournee9200682011-05-13 03:29:01 +00005564 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005565 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00005566
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005567 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005568 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005569 }
Mike Stump11289f42009-09-09 15:08:12 +00005570
Ted Kremeneke65b0862012-03-06 20:05:56 +00005571 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5572 return Success(E->getValue(), E);
5573 }
5574
Richard Smith4ce706a2011-10-11 21:43:33 +00005575 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00005576 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005577 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005578 }
5579
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005580 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005581 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005582 }
5583
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005584 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
5585 return Success(E->getValue(), E);
5586 }
5587
Douglas Gregor29c42f22012-02-24 07:38:34 +00005588 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5589 return Success(E->getValue(), E);
5590 }
5591
John Wiegley6242b6a2011-04-28 00:16:57 +00005592 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5593 return Success(E->getValue(), E);
5594 }
5595
John Wiegleyf9f65842011-04-25 06:54:41 +00005596 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5597 return Success(E->getValue(), E);
5598 }
5599
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005600 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005601 bool VisitUnaryImag(const UnaryOperator *E);
5602
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005603 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005604 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00005605
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005606private:
Ken Dyck160146e2010-01-27 17:10:57 +00005607 CharUnits GetAlignOfExpr(const Expr *E);
5608 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00005609 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00005610 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005611 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00005612};
Chris Lattner05706e882008-07-11 18:11:29 +00005613} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005614
Richard Smith11562c52011-10-28 17:51:58 +00005615/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
5616/// produce either the integer value or a pointer.
5617///
5618/// GCC has a heinous extension which folds casts between pointer types and
5619/// pointer-sized integral types. We support this by allowing the evaluation of
5620/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
5621/// Some simple arithmetic on such values is supported (they are treated much
5622/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00005623static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00005624 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005625 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005626 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00005627}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005628
Richard Smithf57d8cb2011-12-09 22:58:01 +00005629static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00005630 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005631 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00005632 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005633 if (!Val.isInt()) {
5634 // FIXME: It would be better to produce the diagnostic for casting
5635 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00005636 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005637 return false;
5638 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005639 Result = Val.getInt();
5640 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005641}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005642
Richard Smithf57d8cb2011-12-09 22:58:01 +00005643/// Check whether the given declaration can be directly converted to an integral
5644/// rvalue. If not, no diagnostic is produced; there are other things we can
5645/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005646bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00005647 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005648 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005649 // Check for signedness/width mismatches between E type and ECD value.
5650 bool SameSign = (ECD->getInitVal().isSigned()
5651 == E->getType()->isSignedIntegerOrEnumerationType());
5652 bool SameWidth = (ECD->getInitVal().getBitWidth()
5653 == Info.Ctx.getIntWidth(E->getType()));
5654 if (SameSign && SameWidth)
5655 return Success(ECD->getInitVal(), E);
5656 else {
5657 // Get rid of mismatch (otherwise Success assertions will fail)
5658 // by computing a new value matching the type of E.
5659 llvm::APSInt Val = ECD->getInitVal();
5660 if (!SameSign)
5661 Val.setIsSigned(!ECD->getInitVal().isSigned());
5662 if (!SameWidth)
5663 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
5664 return Success(Val, E);
5665 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005666 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005667 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00005668}
5669
Chris Lattner86ee2862008-10-06 06:40:35 +00005670/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
5671/// as GCC.
5672static int EvaluateBuiltinClassifyType(const CallExpr *E) {
5673 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005674 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00005675 enum gcc_type_class {
5676 no_type_class = -1,
5677 void_type_class, integer_type_class, char_type_class,
5678 enumeral_type_class, boolean_type_class,
5679 pointer_type_class, reference_type_class, offset_type_class,
5680 real_type_class, complex_type_class,
5681 function_type_class, method_type_class,
5682 record_type_class, union_type_class,
5683 array_type_class, string_type_class,
5684 lang_type_class
5685 };
Mike Stump11289f42009-09-09 15:08:12 +00005686
5687 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00005688 // ideal, however it is what gcc does.
5689 if (E->getNumArgs() == 0)
5690 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00005691
Chris Lattner86ee2862008-10-06 06:40:35 +00005692 QualType ArgTy = E->getArg(0)->getType();
5693 if (ArgTy->isVoidType())
5694 return void_type_class;
5695 else if (ArgTy->isEnumeralType())
5696 return enumeral_type_class;
5697 else if (ArgTy->isBooleanType())
5698 return boolean_type_class;
5699 else if (ArgTy->isCharType())
5700 return string_type_class; // gcc doesn't appear to use char_type_class
5701 else if (ArgTy->isIntegerType())
5702 return integer_type_class;
5703 else if (ArgTy->isPointerType())
5704 return pointer_type_class;
5705 else if (ArgTy->isReferenceType())
5706 return reference_type_class;
5707 else if (ArgTy->isRealType())
5708 return real_type_class;
5709 else if (ArgTy->isComplexType())
5710 return complex_type_class;
5711 else if (ArgTy->isFunctionType())
5712 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00005713 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00005714 return record_type_class;
5715 else if (ArgTy->isUnionType())
5716 return union_type_class;
5717 else if (ArgTy->isArrayType())
5718 return array_type_class;
5719 else if (ArgTy->isUnionType())
5720 return union_type_class;
5721 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00005722 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00005723}
5724
Richard Smith5fab0c92011-12-28 19:48:30 +00005725/// EvaluateBuiltinConstantPForLValue - Determine the result of
5726/// __builtin_constant_p when applied to the given lvalue.
5727///
5728/// An lvalue is only "constant" if it is a pointer or reference to the first
5729/// character of a string literal.
5730template<typename LValue>
5731static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00005732 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00005733 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
5734}
5735
5736/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
5737/// GCC as we can manage.
5738static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
5739 QualType ArgType = Arg->getType();
5740
5741 // __builtin_constant_p always has one operand. The rules which gcc follows
5742 // are not precisely documented, but are as follows:
5743 //
5744 // - If the operand is of integral, floating, complex or enumeration type,
5745 // and can be folded to a known value of that type, it returns 1.
5746 // - If the operand and can be folded to a pointer to the first character
5747 // of a string literal (or such a pointer cast to an integral type), it
5748 // returns 1.
5749 //
5750 // Otherwise, it returns 0.
5751 //
5752 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
5753 // its support for this does not currently work.
5754 if (ArgType->isIntegralOrEnumerationType()) {
5755 Expr::EvalResult Result;
5756 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
5757 return false;
5758
5759 APValue &V = Result.Val;
5760 if (V.getKind() == APValue::Int)
5761 return true;
5762
5763 return EvaluateBuiltinConstantPForLValue(V);
5764 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
5765 return Arg->isEvaluatable(Ctx);
5766 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
5767 LValue LV;
5768 Expr::EvalStatus Status;
5769 EvalInfo Info(Ctx, Status);
5770 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
5771 : EvaluatePointer(Arg, LV, Info)) &&
5772 !Status.HasSideEffects)
5773 return EvaluateBuiltinConstantPForLValue(LV);
5774 }
5775
5776 // Anything else isn't considered to be sufficiently constant.
5777 return false;
5778}
5779
John McCall95007602010-05-10 23:27:23 +00005780/// Retrieves the "underlying object type" of the given expression,
5781/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00005782QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
5783 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
5784 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00005785 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00005786 } else if (const Expr *E = B.get<const Expr*>()) {
5787 if (isa<CompoundLiteralExpr>(E))
5788 return E->getType();
John McCall95007602010-05-10 23:27:23 +00005789 }
5790
5791 return QualType();
5792}
5793
Peter Collingbournee9200682011-05-13 03:29:01 +00005794bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00005795 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00005796
5797 {
5798 // The operand of __builtin_object_size is never evaluated for side-effects.
5799 // If there are any, but we can determine the pointed-to object anyway, then
5800 // ignore the side-effects.
5801 SpeculativeEvaluationRAII SpeculativeEval(Info);
5802 if (!EvaluatePointer(E->getArg(0), Base, Info))
5803 return false;
5804 }
John McCall95007602010-05-10 23:27:23 +00005805
5806 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00005807 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00005808
Richard Smithce40ad62011-11-12 22:28:03 +00005809 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00005810 if (T.isNull() ||
5811 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00005812 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00005813 T->isVariablyModifiedType() ||
5814 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005815 return Error(E);
John McCall95007602010-05-10 23:27:23 +00005816
5817 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
5818 CharUnits Offset = Base.getLValueOffset();
5819
5820 if (!Offset.isNegative() && Offset <= Size)
5821 Size -= Offset;
5822 else
5823 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00005824 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00005825}
5826
Peter Collingbournee9200682011-05-13 03:29:01 +00005827bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith01ba47d2012-04-13 00:45:38 +00005828 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005829 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00005830 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005831
5832 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00005833 if (TryEvaluateBuiltinObjectSize(E))
5834 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00005835
Richard Smith0421ce72012-08-07 04:16:51 +00005836 // If evaluating the argument has side-effects, we can't determine the size
5837 // of the object, and so we lower it to unknown now. CodeGen relies on us to
5838 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005839 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00005840 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00005841 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00005842 return Success(0, E);
5843 }
Mike Stump876387b2009-10-27 22:09:17 +00005844
Richard Smith01ade172012-05-23 04:13:20 +00005845 // Expression had no side effects, but we couldn't statically determine the
5846 // size of the referenced object.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005847 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005848 }
5849
Benjamin Kramera801f4a2012-10-06 14:42:22 +00005850 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00005851 case Builtin::BI__builtin_bswap32:
5852 case Builtin::BI__builtin_bswap64: {
5853 APSInt Val;
5854 if (!EvaluateInteger(E->getArg(0), Val, Info))
5855 return false;
5856
5857 return Success(Val.byteSwap(), E);
5858 }
5859
Richard Smith8889a3d2013-06-13 06:26:32 +00005860 case Builtin::BI__builtin_classify_type:
5861 return Success(EvaluateBuiltinClassifyType(E), E);
5862
5863 // FIXME: BI__builtin_clrsb
5864 // FIXME: BI__builtin_clrsbl
5865 // FIXME: BI__builtin_clrsbll
5866
Richard Smith80b3c8e2013-06-13 05:04:16 +00005867 case Builtin::BI__builtin_clz:
5868 case Builtin::BI__builtin_clzl:
5869 case Builtin::BI__builtin_clzll: {
5870 APSInt Val;
5871 if (!EvaluateInteger(E->getArg(0), Val, Info))
5872 return false;
5873 if (!Val)
5874 return Error(E);
5875
5876 return Success(Val.countLeadingZeros(), E);
5877 }
5878
Richard Smith8889a3d2013-06-13 06:26:32 +00005879 case Builtin::BI__builtin_constant_p:
5880 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
5881
Richard Smith80b3c8e2013-06-13 05:04:16 +00005882 case Builtin::BI__builtin_ctz:
5883 case Builtin::BI__builtin_ctzl:
5884 case Builtin::BI__builtin_ctzll: {
5885 APSInt Val;
5886 if (!EvaluateInteger(E->getArg(0), Val, Info))
5887 return false;
5888 if (!Val)
5889 return Error(E);
5890
5891 return Success(Val.countTrailingZeros(), E);
5892 }
5893
Richard Smith8889a3d2013-06-13 06:26:32 +00005894 case Builtin::BI__builtin_eh_return_data_regno: {
5895 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
5896 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
5897 return Success(Operand, E);
5898 }
5899
5900 case Builtin::BI__builtin_expect:
5901 return Visit(E->getArg(0));
5902
5903 case Builtin::BI__builtin_ffs:
5904 case Builtin::BI__builtin_ffsl:
5905 case Builtin::BI__builtin_ffsll: {
5906 APSInt Val;
5907 if (!EvaluateInteger(E->getArg(0), Val, Info))
5908 return false;
5909
5910 unsigned N = Val.countTrailingZeros();
5911 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
5912 }
5913
5914 case Builtin::BI__builtin_fpclassify: {
5915 APFloat Val(0.0);
5916 if (!EvaluateFloat(E->getArg(5), Val, Info))
5917 return false;
5918 unsigned Arg;
5919 switch (Val.getCategory()) {
5920 case APFloat::fcNaN: Arg = 0; break;
5921 case APFloat::fcInfinity: Arg = 1; break;
5922 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
5923 case APFloat::fcZero: Arg = 4; break;
5924 }
5925 return Visit(E->getArg(Arg));
5926 }
5927
5928 case Builtin::BI__builtin_isinf_sign: {
5929 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00005930 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00005931 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
5932 }
5933
5934 case Builtin::BI__builtin_parity:
5935 case Builtin::BI__builtin_parityl:
5936 case Builtin::BI__builtin_parityll: {
5937 APSInt Val;
5938 if (!EvaluateInteger(E->getArg(0), Val, Info))
5939 return false;
5940
5941 return Success(Val.countPopulation() % 2, E);
5942 }
5943
Richard Smith80b3c8e2013-06-13 05:04:16 +00005944 case Builtin::BI__builtin_popcount:
5945 case Builtin::BI__builtin_popcountl:
5946 case Builtin::BI__builtin_popcountll: {
5947 APSInt Val;
5948 if (!EvaluateInteger(E->getArg(0), Val, Info))
5949 return false;
5950
5951 return Success(Val.countPopulation(), E);
5952 }
5953
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005954 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00005955 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005956 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00005957 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00005958 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
5959 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00005960 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00005961 // Fall through.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005962 case Builtin::BI__builtin_strlen:
5963 // As an extension, we support strlen() and __builtin_strlen() as constant
5964 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00005965 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005966 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
5967 // The string literal may have embedded null characters. Find the first
5968 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005969 StringRef Str = S->getString();
5970 StringRef::size_type Pos = Str.find(0);
5971 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005972 Str = Str.substr(0, Pos);
5973
5974 return Success(Str.size(), E);
5975 }
5976
Richard Smithf57d8cb2011-12-09 22:58:01 +00005977 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005978
Richard Smith01ba47d2012-04-13 00:45:38 +00005979 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00005980 case Builtin::BI__atomic_is_lock_free:
5981 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00005982 APSInt SizeVal;
5983 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
5984 return false;
5985
5986 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
5987 // of two less than the maximum inline atomic width, we know it is
5988 // lock-free. If the size isn't a power of two, or greater than the
5989 // maximum alignment where we promote atomics, we know it is not lock-free
5990 // (at least not in the sense of atomic_is_lock_free). Otherwise,
5991 // the answer can only be determined at runtime; for example, 16-byte
5992 // atomics have lock-free implementations on some, but not all,
5993 // x86-64 processors.
5994
5995 // Check power-of-two.
5996 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00005997 if (Size.isPowerOfTwo()) {
5998 // Check against inlining width.
5999 unsigned InlineWidthBits =
6000 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6001 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6002 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6003 Size == CharUnits::One() ||
6004 E->getArg(1)->isNullPointerConstant(Info.Ctx,
6005 Expr::NPC_NeverValueDependent))
6006 // OK, we will inline appropriately-aligned operations of this size,
6007 // and _Atomic(T) is appropriately-aligned.
6008 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006009
Richard Smith01ba47d2012-04-13 00:45:38 +00006010 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6011 castAs<PointerType>()->getPointeeType();
6012 if (!PointeeType->isIncompleteType() &&
6013 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6014 // OK, we will inline operations on this object.
6015 return Success(1, E);
6016 }
6017 }
6018 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006019
Richard Smith01ba47d2012-04-13 00:45:38 +00006020 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6021 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006022 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006023 }
Chris Lattner7174bf32008-07-12 00:38:25 +00006024}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006025
Richard Smith8b3497e2011-10-31 01:37:14 +00006026static bool HasSameBase(const LValue &A, const LValue &B) {
6027 if (!A.getLValueBase())
6028 return !B.getLValueBase();
6029 if (!B.getLValueBase())
6030 return false;
6031
Richard Smithce40ad62011-11-12 22:28:03 +00006032 if (A.getLValueBase().getOpaqueValue() !=
6033 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006034 const Decl *ADecl = GetLValueBaseDecl(A);
6035 if (!ADecl)
6036 return false;
6037 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00006038 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00006039 return false;
6040 }
6041
6042 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00006043 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00006044}
6045
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006046namespace {
Richard Smith11562c52011-10-28 17:51:58 +00006047
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006048/// \brief Data recursive integer evaluator of certain binary operators.
6049///
6050/// We use a data recursive algorithm for binary operators so that we are able
6051/// to handle extreme cases of chained binary operators without causing stack
6052/// overflow.
6053class DataRecursiveIntBinOpEvaluator {
6054 struct EvalResult {
6055 APValue Val;
6056 bool Failed;
6057
6058 EvalResult() : Failed(false) { }
6059
6060 void swap(EvalResult &RHS) {
6061 Val.swap(RHS.Val);
6062 Failed = RHS.Failed;
6063 RHS.Failed = false;
6064 }
6065 };
6066
6067 struct Job {
6068 const Expr *E;
6069 EvalResult LHSResult; // meaningful only for binary operator expression.
6070 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
6071
6072 Job() : StoredInfo(0) { }
6073 void startSpeculativeEval(EvalInfo &Info) {
6074 OldEvalStatus = Info.EvalStatus;
6075 Info.EvalStatus.Diag = 0;
6076 StoredInfo = &Info;
6077 }
6078 ~Job() {
6079 if (StoredInfo) {
6080 StoredInfo->EvalStatus = OldEvalStatus;
6081 }
6082 }
6083 private:
6084 EvalInfo *StoredInfo; // non-null if status changed.
6085 Expr::EvalStatus OldEvalStatus;
6086 };
6087
6088 SmallVector<Job, 16> Queue;
6089
6090 IntExprEvaluator &IntEval;
6091 EvalInfo &Info;
6092 APValue &FinalResult;
6093
6094public:
6095 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
6096 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
6097
6098 /// \brief True if \param E is a binary operator that we are going to handle
6099 /// data recursively.
6100 /// We handle binary operators that are comma, logical, or that have operands
6101 /// with integral or enumeration type.
6102 static bool shouldEnqueue(const BinaryOperator *E) {
6103 return E->getOpcode() == BO_Comma ||
6104 E->isLogicalOp() ||
6105 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6106 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00006107 }
6108
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006109 bool Traverse(const BinaryOperator *E) {
6110 enqueue(E);
6111 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00006112 while (!Queue.empty())
6113 process(PrevResult);
6114
6115 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006116
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006117 FinalResult.swap(PrevResult.Val);
6118 return true;
6119 }
6120
6121private:
6122 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6123 return IntEval.Success(Value, E, Result);
6124 }
6125 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6126 return IntEval.Success(Value, E, Result);
6127 }
6128 bool Error(const Expr *E) {
6129 return IntEval.Error(E);
6130 }
6131 bool Error(const Expr *E, diag::kind D) {
6132 return IntEval.Error(E, D);
6133 }
6134
6135 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6136 return Info.CCEDiag(E, D);
6137 }
6138
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006139 // \brief Returns true if visiting the RHS is necessary, false otherwise.
6140 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006141 bool &SuppressRHSDiags);
6142
6143 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6144 const BinaryOperator *E, APValue &Result);
6145
6146 void EvaluateExpr(const Expr *E, EvalResult &Result) {
6147 Result.Failed = !Evaluate(Result.Val, Info, E);
6148 if (Result.Failed)
6149 Result.Val = APValue();
6150 }
6151
Richard Trieuba4d0872012-03-21 23:30:30 +00006152 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006153
6154 void enqueue(const Expr *E) {
6155 E = E->IgnoreParens();
6156 Queue.resize(Queue.size()+1);
6157 Queue.back().E = E;
6158 Queue.back().Kind = Job::AnyExprKind;
6159 }
6160};
6161
6162}
6163
6164bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006165 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006166 bool &SuppressRHSDiags) {
6167 if (E->getOpcode() == BO_Comma) {
6168 // Ignore LHS but note if we could not evaluate it.
6169 if (LHSResult.Failed)
6170 Info.EvalStatus.HasSideEffects = true;
6171 return true;
6172 }
6173
6174 if (E->isLogicalOp()) {
6175 bool lhsResult;
6176 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006177 // We were able to evaluate the LHS, see if we can get away with not
6178 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006179 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006180 Success(lhsResult, E, LHSResult.Val);
6181 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006182 }
6183 } else {
6184 // Since we weren't able to evaluate the left hand side, it
6185 // must have had side effects.
6186 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006187
6188 // We can't evaluate the LHS; however, sometimes the result
6189 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6190 // Don't ignore RHS and suppress diagnostics from this arm.
6191 SuppressRHSDiags = true;
6192 }
6193
6194 return true;
6195 }
6196
6197 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6198 E->getRHS()->getType()->isIntegralOrEnumerationType());
6199
6200 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006201 return false; // Ignore RHS;
6202
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006203 return true;
6204}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006205
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006206bool DataRecursiveIntBinOpEvaluator::
6207 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6208 const BinaryOperator *E, APValue &Result) {
6209 if (E->getOpcode() == BO_Comma) {
6210 if (RHSResult.Failed)
6211 return false;
6212 Result = RHSResult.Val;
6213 return true;
6214 }
6215
6216 if (E->isLogicalOp()) {
6217 bool lhsResult, rhsResult;
6218 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
6219 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
6220
6221 if (LHSIsOK) {
6222 if (RHSIsOK) {
6223 if (E->getOpcode() == BO_LOr)
6224 return Success(lhsResult || rhsResult, E, Result);
6225 else
6226 return Success(lhsResult && rhsResult, E, Result);
6227 }
6228 } else {
6229 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006230 // We can't evaluate the LHS; however, sometimes the result
6231 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6232 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006233 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006234 }
6235 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006236
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006237 return false;
6238 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006239
6240 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6241 E->getRHS()->getType()->isIntegralOrEnumerationType());
6242
6243 if (LHSResult.Failed || RHSResult.Failed)
6244 return false;
6245
6246 const APValue &LHSVal = LHSResult.Val;
6247 const APValue &RHSVal = RHSResult.Val;
6248
6249 // Handle cases like (unsigned long)&a + 4.
6250 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
6251 Result = LHSVal;
6252 CharUnits AdditionalOffset = CharUnits::fromQuantity(
6253 RHSVal.getInt().getZExtValue());
6254 if (E->getOpcode() == BO_Add)
6255 Result.getLValueOffset() += AdditionalOffset;
6256 else
6257 Result.getLValueOffset() -= AdditionalOffset;
6258 return true;
6259 }
6260
6261 // Handle cases like 4 + (unsigned long)&a
6262 if (E->getOpcode() == BO_Add &&
6263 RHSVal.isLValue() && LHSVal.isInt()) {
6264 Result = RHSVal;
6265 Result.getLValueOffset() += CharUnits::fromQuantity(
6266 LHSVal.getInt().getZExtValue());
6267 return true;
6268 }
6269
6270 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
6271 // Handle (intptr_t)&&A - (intptr_t)&&B.
6272 if (!LHSVal.getLValueOffset().isZero() ||
6273 !RHSVal.getLValueOffset().isZero())
6274 return false;
6275 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
6276 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
6277 if (!LHSExpr || !RHSExpr)
6278 return false;
6279 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6280 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6281 if (!LHSAddrExpr || !RHSAddrExpr)
6282 return false;
6283 // Make sure both labels come from the same function.
6284 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6285 RHSAddrExpr->getLabel()->getDeclContext())
6286 return false;
6287 Result = APValue(LHSAddrExpr, RHSAddrExpr);
6288 return true;
6289 }
Richard Smith43e77732013-05-07 04:50:00 +00006290
6291 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006292 if (!LHSVal.isInt() || !RHSVal.isInt())
6293 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00006294
6295 // Set up the width and signedness manually, in case it can't be deduced
6296 // from the operation we're performing.
6297 // FIXME: Don't do this in the cases where we can deduce it.
6298 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
6299 E->getType()->isUnsignedIntegerOrEnumerationType());
6300 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
6301 RHSVal.getInt(), Value))
6302 return false;
6303 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006304}
6305
Richard Trieuba4d0872012-03-21 23:30:30 +00006306void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006307 Job &job = Queue.back();
6308
6309 switch (job.Kind) {
6310 case Job::AnyExprKind: {
6311 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
6312 if (shouldEnqueue(Bop)) {
6313 job.Kind = Job::BinOpKind;
6314 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006315 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006316 }
6317 }
6318
6319 EvaluateExpr(job.E, Result);
6320 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006321 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006322 }
6323
6324 case Job::BinOpKind: {
6325 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006326 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006327 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006328 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006329 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006330 }
6331 if (SuppressRHSDiags)
6332 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006333 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006334 job.Kind = Job::BinOpVisitedLHSKind;
6335 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006336 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006337 }
6338
6339 case Job::BinOpVisitedLHSKind: {
6340 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6341 EvalResult RHS;
6342 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00006343 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006344 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006345 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006346 }
6347 }
6348
6349 llvm_unreachable("Invalid Job::Kind!");
6350}
6351
6352bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6353 if (E->isAssignmentOp())
6354 return Error(E);
6355
6356 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
6357 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006358
Anders Carlssonacc79812008-11-16 07:17:21 +00006359 QualType LHSTy = E->getLHS()->getType();
6360 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006361
6362 if (LHSTy->isAnyComplexType()) {
6363 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00006364 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006365
Richard Smith253c2a32012-01-27 01:14:48 +00006366 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
6367 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006368 return false;
6369
Richard Smith253c2a32012-01-27 01:14:48 +00006370 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006371 return false;
6372
6373 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00006374 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006375 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00006376 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006377 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
6378
John McCalle3027922010-08-25 11:45:40 +00006379 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006380 return Success((CR_r == APFloat::cmpEqual &&
6381 CR_i == APFloat::cmpEqual), E);
6382 else {
John McCalle3027922010-08-25 11:45:40 +00006383 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006384 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00006385 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006386 CR_r == APFloat::cmpLessThan ||
6387 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00006388 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006389 CR_i == APFloat::cmpLessThan ||
6390 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006391 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006392 } else {
John McCalle3027922010-08-25 11:45:40 +00006393 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006394 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
6395 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
6396 else {
John McCalle3027922010-08-25 11:45:40 +00006397 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006398 "Invalid compex comparison.");
6399 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
6400 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
6401 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006402 }
6403 }
Mike Stump11289f42009-09-09 15:08:12 +00006404
Anders Carlssonacc79812008-11-16 07:17:21 +00006405 if (LHSTy->isRealFloatingType() &&
6406 RHSTy->isRealFloatingType()) {
6407 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00006408
Richard Smith253c2a32012-01-27 01:14:48 +00006409 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
6410 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00006411 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006412
Richard Smith253c2a32012-01-27 01:14:48 +00006413 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00006414 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006415
Anders Carlssonacc79812008-11-16 07:17:21 +00006416 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00006417
Anders Carlssonacc79812008-11-16 07:17:21 +00006418 switch (E->getOpcode()) {
6419 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006420 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00006421 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006422 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00006423 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006424 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00006425 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006426 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006427 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00006428 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006429 E);
John McCalle3027922010-08-25 11:45:40 +00006430 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006431 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006432 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00006433 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00006434 || CR == APFloat::cmpLessThan
6435 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00006436 }
Anders Carlssonacc79812008-11-16 07:17:21 +00006437 }
Mike Stump11289f42009-09-09 15:08:12 +00006438
Eli Friedmana38da572009-04-28 19:17:36 +00006439 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006440 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00006441 LValue LHSValue, RHSValue;
6442
6443 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6444 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006445 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006446
Richard Smith253c2a32012-01-27 01:14:48 +00006447 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006448 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006449
Richard Smith8b3497e2011-10-31 01:37:14 +00006450 // Reject differing bases from the normal codepath; we special-case
6451 // comparisons to null.
6452 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006453 if (E->getOpcode() == BO_Sub) {
6454 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006455 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6456 return false;
6457 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00006458 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006459 if (!LHSExpr || !RHSExpr)
6460 return false;
6461 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6462 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6463 if (!LHSAddrExpr || !RHSAddrExpr)
6464 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006465 // Make sure both labels come from the same function.
6466 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6467 RHSAddrExpr->getLabel()->getDeclContext())
6468 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006469 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006470 return true;
6471 }
Richard Smith83c68212011-10-31 05:11:32 +00006472 // Inequalities and subtractions between unrelated pointers have
6473 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00006474 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006475 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006476 // A constant address may compare equal to the address of a symbol.
6477 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00006478 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006479 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6480 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006481 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006482 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00006483 // distinct addresses. In clang, the result of such a comparison is
6484 // unspecified, so it is not a constant expression. However, we do know
6485 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00006486 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6487 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006488 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006489 // We can't tell whether weak symbols will end up pointing to the same
6490 // object.
6491 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006492 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006493 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00006494 // (Note that clang defaults to -fmerge-all-constants, which can
6495 // lead to inconsistent results for comparisons involving the address
6496 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00006497 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00006498 }
Eli Friedman64004332009-03-23 04:38:34 +00006499
Richard Smith1b470412012-02-01 08:10:20 +00006500 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
6501 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
6502
Richard Smith84f6dcf2012-02-02 01:16:57 +00006503 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
6504 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
6505
John McCalle3027922010-08-25 11:45:40 +00006506 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00006507 // C++11 [expr.add]p6:
6508 // Unless both pointers point to elements of the same array object, or
6509 // one past the last element of the array object, the behavior is
6510 // undefined.
6511 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6512 !AreElementsOfSameArray(getType(LHSValue.Base),
6513 LHSDesignator, RHSDesignator))
6514 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
6515
Chris Lattner882bdf22010-04-20 17:13:14 +00006516 QualType Type = E->getLHS()->getType();
6517 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006518
Richard Smithd62306a2011-11-10 06:34:14 +00006519 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00006520 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00006521 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006522
Richard Smith1b470412012-02-01 08:10:20 +00006523 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
6524 // and produce incorrect results when it overflows. Such behavior
6525 // appears to be non-conforming, but is common, so perhaps we should
6526 // assume the standard intended for such cases to be undefined behavior
6527 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00006528
Richard Smith1b470412012-02-01 08:10:20 +00006529 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
6530 // overflow in the final conversion to ptrdiff_t.
6531 APSInt LHS(
6532 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
6533 APSInt RHS(
6534 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
6535 APSInt ElemSize(
6536 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
6537 APSInt TrueResult = (LHS - RHS) / ElemSize;
6538 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
6539
6540 if (Result.extend(65) != TrueResult)
6541 HandleOverflow(Info, E, TrueResult, E->getType());
6542 return Success(Result, E);
6543 }
Richard Smithde21b242012-01-31 06:41:30 +00006544
6545 // C++11 [expr.rel]p3:
6546 // Pointers to void (after pointer conversions) can be compared, with a
6547 // result defined as follows: If both pointers represent the same
6548 // address or are both the null pointer value, the result is true if the
6549 // operator is <= or >= and false otherwise; otherwise the result is
6550 // unspecified.
6551 // We interpret this as applying to pointers to *cv* void.
6552 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00006553 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00006554 CCEDiag(E, diag::note_constexpr_void_comparison);
6555
Richard Smith84f6dcf2012-02-02 01:16:57 +00006556 // C++11 [expr.rel]p2:
6557 // - If two pointers point to non-static data members of the same object,
6558 // or to subobjects or array elements fo such members, recursively, the
6559 // pointer to the later declared member compares greater provided the
6560 // two members have the same access control and provided their class is
6561 // not a union.
6562 // [...]
6563 // - Otherwise pointer comparisons are unspecified.
6564 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6565 E->isRelationalOp()) {
6566 bool WasArrayIndex;
6567 unsigned Mismatch =
6568 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
6569 RHSDesignator, WasArrayIndex);
6570 // At the point where the designators diverge, the comparison has a
6571 // specified value if:
6572 // - we are comparing array indices
6573 // - we are comparing fields of a union, or fields with the same access
6574 // Otherwise, the result is unspecified and thus the comparison is not a
6575 // constant expression.
6576 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
6577 Mismatch < RHSDesignator.Entries.size()) {
6578 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
6579 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
6580 if (!LF && !RF)
6581 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
6582 else if (!LF)
6583 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6584 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
6585 << RF->getParent() << RF;
6586 else if (!RF)
6587 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6588 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
6589 << LF->getParent() << LF;
6590 else if (!LF->getParent()->isUnion() &&
6591 LF->getAccess() != RF->getAccess())
6592 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
6593 << LF << LF->getAccess() << RF << RF->getAccess()
6594 << LF->getParent();
6595 }
6596 }
6597
Eli Friedman6c31cb42012-04-16 04:30:08 +00006598 // The comparison here must be unsigned, and performed with the same
6599 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00006600 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
6601 uint64_t CompareLHS = LHSOffset.getQuantity();
6602 uint64_t CompareRHS = RHSOffset.getQuantity();
6603 assert(PtrSize <= 64 && "Unexpected pointer width");
6604 uint64_t Mask = ~0ULL >> (64 - PtrSize);
6605 CompareLHS &= Mask;
6606 CompareRHS &= Mask;
6607
Eli Friedman2f5b7c52012-04-16 19:23:57 +00006608 // If there is a base and this is a relational operator, we can only
6609 // compare pointers within the object in question; otherwise, the result
6610 // depends on where the object is located in memory.
6611 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
6612 QualType BaseTy = getType(LHSValue.Base);
6613 if (BaseTy->isIncompleteType())
6614 return Error(E);
6615 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
6616 uint64_t OffsetLimit = Size.getQuantity();
6617 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
6618 return Error(E);
6619 }
6620
Richard Smith8b3497e2011-10-31 01:37:14 +00006621 switch (E->getOpcode()) {
6622 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00006623 case BO_LT: return Success(CompareLHS < CompareRHS, E);
6624 case BO_GT: return Success(CompareLHS > CompareRHS, E);
6625 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
6626 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
6627 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
6628 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00006629 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006630 }
6631 }
Richard Smith7bb00672012-02-01 01:42:44 +00006632
6633 if (LHSTy->isMemberPointerType()) {
6634 assert(E->isEqualityOp() && "unexpected member pointer operation");
6635 assert(RHSTy->isMemberPointerType() && "invalid comparison");
6636
6637 MemberPtr LHSValue, RHSValue;
6638
6639 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
6640 if (!LHSOK && Info.keepEvaluatingAfterFailure())
6641 return false;
6642
6643 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6644 return false;
6645
6646 // C++11 [expr.eq]p2:
6647 // If both operands are null, they compare equal. Otherwise if only one is
6648 // null, they compare unequal.
6649 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
6650 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
6651 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6652 }
6653
6654 // Otherwise if either is a pointer to a virtual member function, the
6655 // result is unspecified.
6656 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
6657 if (MD->isVirtual())
6658 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6659 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
6660 if (MD->isVirtual())
6661 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6662
6663 // Otherwise they compare equal if and only if they would refer to the
6664 // same member of the same most derived object or the same subobject if
6665 // they were dereferenced with a hypothetical object of the associated
6666 // class type.
6667 bool Equal = LHSValue == RHSValue;
6668 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6669 }
6670
Richard Smithab44d9b2012-02-14 22:35:28 +00006671 if (LHSTy->isNullPtrType()) {
6672 assert(E->isComparisonOp() && "unexpected nullptr operation");
6673 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
6674 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
6675 // are compared, the result is true of the operator is <=, >= or ==, and
6676 // false otherwise.
6677 BinaryOperator::Opcode Opcode = E->getOpcode();
6678 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
6679 }
6680
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006681 assert((!LHSTy->isIntegralOrEnumerationType() ||
6682 !RHSTy->isIntegralOrEnumerationType()) &&
6683 "DataRecursiveIntBinOpEvaluator should have handled integral types");
6684 // We can't continue from here for non-integral types.
6685 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00006686}
6687
Ken Dyck160146e2010-01-27 17:10:57 +00006688CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00006689 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
6690 // result shall be the alignment of the referenced type."
6691 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6692 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00006693
6694 // __alignof is defined to return the preferred alignment.
6695 return Info.Ctx.toCharUnitsFromBits(
6696 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00006697}
6698
Ken Dyck160146e2010-01-27 17:10:57 +00006699CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00006700 E = E->IgnoreParens();
6701
John McCall768439e2013-05-06 07:40:34 +00006702 // The kinds of expressions that we have special-case logic here for
6703 // should be kept up to date with the special checks for those
6704 // expressions in Sema.
6705
Chris Lattner68061312009-01-24 21:53:27 +00006706 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00006707 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00006708 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006709 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6710 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00006711
Chris Lattner68061312009-01-24 21:53:27 +00006712 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006713 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6714 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00006715
Chris Lattner24aeeab2009-01-24 21:09:06 +00006716 return GetAlignOfType(E->getType());
6717}
6718
6719
Peter Collingbournee190dee2011-03-11 19:24:49 +00006720/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
6721/// a result as the expression's type.
6722bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
6723 const UnaryExprOrTypeTraitExpr *E) {
6724 switch(E->getKind()) {
6725 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00006726 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00006727 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006728 else
Ken Dyckdbc01912011-03-11 02:13:43 +00006729 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006730 }
Eli Friedman64004332009-03-23 04:38:34 +00006731
Peter Collingbournee190dee2011-03-11 19:24:49 +00006732 case UETT_VecStep: {
6733 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00006734
Peter Collingbournee190dee2011-03-11 19:24:49 +00006735 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00006736 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00006737
Peter Collingbournee190dee2011-03-11 19:24:49 +00006738 // The vec_step built-in functions that take a 3-component
6739 // vector return 4. (OpenCL 1.1 spec 6.11.12)
6740 if (n == 3)
6741 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00006742
Peter Collingbournee190dee2011-03-11 19:24:49 +00006743 return Success(n, E);
6744 } else
6745 return Success(1, E);
6746 }
6747
6748 case UETT_SizeOf: {
6749 QualType SrcTy = E->getTypeOfArgument();
6750 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
6751 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00006752 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
6753 SrcTy = Ref->getPointeeType();
6754
Richard Smithd62306a2011-11-10 06:34:14 +00006755 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00006756 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00006757 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006758 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006759 }
6760 }
6761
6762 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006763}
6764
Peter Collingbournee9200682011-05-13 03:29:01 +00006765bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00006766 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00006767 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00006768 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006769 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00006770 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00006771 for (unsigned i = 0; i != n; ++i) {
6772 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
6773 switch (ON.getKind()) {
6774 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00006775 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00006776 APSInt IdxResult;
6777 if (!EvaluateInteger(Idx, IdxResult, Info))
6778 return false;
6779 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
6780 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006781 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006782 CurrentType = AT->getElementType();
6783 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
6784 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00006785 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00006786 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006787
Douglas Gregor882211c2010-04-28 22:16:22 +00006788 case OffsetOfExpr::OffsetOfNode::Field: {
6789 FieldDecl *MemberDecl = ON.getField();
6790 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006791 if (!RT)
6792 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006793 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006794 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00006795 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00006796 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00006797 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00006798 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00006799 CurrentType = MemberDecl->getType().getNonReferenceType();
6800 break;
6801 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006802
Douglas Gregor882211c2010-04-28 22:16:22 +00006803 case OffsetOfExpr::OffsetOfNode::Identifier:
6804 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00006805
Douglas Gregord1702062010-04-29 00:18:15 +00006806 case OffsetOfExpr::OffsetOfNode::Base: {
6807 CXXBaseSpecifier *BaseSpec = ON.getBase();
6808 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006809 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006810
6811 // Find the layout of the class whose base we are looking into.
6812 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006813 if (!RT)
6814 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006815 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006816 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00006817 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
6818
6819 // Find the base class itself.
6820 CurrentType = BaseSpec->getType();
6821 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
6822 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006823 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006824
6825 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00006826 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00006827 break;
6828 }
Douglas Gregor882211c2010-04-28 22:16:22 +00006829 }
6830 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006831 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006832}
6833
Chris Lattnere13042c2008-07-11 19:10:17 +00006834bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006835 switch (E->getOpcode()) {
6836 default:
6837 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
6838 // See C99 6.6p3.
6839 return Error(E);
6840 case UO_Extension:
6841 // FIXME: Should extension allow i-c-e extension expressions in its scope?
6842 // If so, we could clear the diagnostic ID.
6843 return Visit(E->getSubExpr());
6844 case UO_Plus:
6845 // The result is just the value.
6846 return Visit(E->getSubExpr());
6847 case UO_Minus: {
6848 if (!Visit(E->getSubExpr()))
6849 return false;
6850 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00006851 const APSInt &Value = Result.getInt();
6852 if (Value.isSigned() && Value.isMinSignedValue())
6853 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
6854 E->getType());
6855 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006856 }
6857 case UO_Not: {
6858 if (!Visit(E->getSubExpr()))
6859 return false;
6860 if (!Result.isInt()) return Error(E);
6861 return Success(~Result.getInt(), E);
6862 }
6863 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00006864 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00006865 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00006866 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006867 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006868 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006869 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006870}
Mike Stump11289f42009-09-09 15:08:12 +00006871
Chris Lattner477c4be2008-07-12 01:15:53 +00006872/// HandleCast - This is used to evaluate implicit or explicit casts where the
6873/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00006874bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
6875 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006876 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00006877 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006878
Eli Friedmanc757de22011-03-25 00:43:55 +00006879 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00006880 case CK_BaseToDerived:
6881 case CK_DerivedToBase:
6882 case CK_UncheckedDerivedToBase:
6883 case CK_Dynamic:
6884 case CK_ToUnion:
6885 case CK_ArrayToPointerDecay:
6886 case CK_FunctionToPointerDecay:
6887 case CK_NullToPointer:
6888 case CK_NullToMemberPointer:
6889 case CK_BaseToDerivedMemberPointer:
6890 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00006891 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00006892 case CK_ConstructorConversion:
6893 case CK_IntegralToPointer:
6894 case CK_ToVoid:
6895 case CK_VectorSplat:
6896 case CK_IntegralToFloating:
6897 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00006898 case CK_CPointerToObjCPointerCast:
6899 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006900 case CK_AnyPointerToBlockPointerCast:
6901 case CK_ObjCObjectLValueCast:
6902 case CK_FloatingRealToComplex:
6903 case CK_FloatingComplexToReal:
6904 case CK_FloatingComplexCast:
6905 case CK_FloatingComplexToIntegralComplex:
6906 case CK_IntegralRealToComplex:
6907 case CK_IntegralComplexCast:
6908 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00006909 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006910 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00006911 case CK_NonAtomicToAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00006912 llvm_unreachable("invalid cast kind for integral value");
6913
Eli Friedman9faf2f92011-03-25 19:07:11 +00006914 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006915 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006916 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00006917 case CK_ARCProduceObject:
6918 case CK_ARCConsumeObject:
6919 case CK_ARCReclaimReturnedObject:
6920 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00006921 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006922 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006923
Richard Smith4ef685b2012-01-17 21:17:26 +00006924 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00006925 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006926 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00006927 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00006928 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006929
6930 case CK_MemberPointerToBoolean:
6931 case CK_PointerToBoolean:
6932 case CK_IntegralToBoolean:
6933 case CK_FloatingToBoolean:
6934 case CK_FloatingComplexToBoolean:
6935 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006936 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00006937 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00006938 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006939 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006940 }
6941
Eli Friedmanc757de22011-03-25 00:43:55 +00006942 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00006943 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00006944 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00006945
Eli Friedman742421e2009-02-20 01:15:07 +00006946 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006947 // Allow casts of address-of-label differences if they are no-ops
6948 // or narrowing. (The narrowing case isn't actually guaranteed to
6949 // be constant-evaluatable except in some narrow cases which are hard
6950 // to detect here. We let it through on the assumption the user knows
6951 // what they are doing.)
6952 if (Result.isAddrLabelDiff())
6953 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00006954 // Only allow casts of lvalues if they are lossless.
6955 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
6956 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006957
Richard Smith911e1422012-01-30 22:27:01 +00006958 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
6959 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00006960 }
Mike Stump11289f42009-09-09 15:08:12 +00006961
Eli Friedmanc757de22011-03-25 00:43:55 +00006962 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00006963 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6964
John McCall45d55e42010-05-07 21:00:08 +00006965 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00006966 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00006967 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00006968
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006969 if (LV.getLValueBase()) {
6970 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00006971 // FIXME: Allow a larger integer size than the pointer size, and allow
6972 // narrowing back down to pointer width in subsequent integral casts.
6973 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006974 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006975 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006976
Richard Smithcf74da72011-11-16 07:18:12 +00006977 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00006978 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006979 return true;
6980 }
6981
Ken Dyck02990832010-01-15 12:37:54 +00006982 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
6983 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00006984 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006985 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006986
Eli Friedmanc757de22011-03-25 00:43:55 +00006987 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00006988 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006989 if (!EvaluateComplex(SubExpr, C, Info))
6990 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00006991 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006992 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00006993
Eli Friedmanc757de22011-03-25 00:43:55 +00006994 case CK_FloatingToIntegral: {
6995 APFloat F(0.0);
6996 if (!EvaluateFloat(SubExpr, F, Info))
6997 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00006998
Richard Smith357362d2011-12-13 06:39:58 +00006999 APSInt Value;
7000 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7001 return false;
7002 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007003 }
7004 }
Mike Stump11289f42009-09-09 15:08:12 +00007005
Eli Friedmanc757de22011-03-25 00:43:55 +00007006 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00007007}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007008
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007009bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7010 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007011 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007012 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7013 return false;
7014 if (!LV.isComplexInt())
7015 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007016 return Success(LV.getComplexIntReal(), E);
7017 }
7018
7019 return Visit(E->getSubExpr());
7020}
7021
Eli Friedman4e7a2412009-02-27 04:45:43 +00007022bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007023 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007024 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007025 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7026 return false;
7027 if (!LV.isComplexInt())
7028 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007029 return Success(LV.getComplexIntImag(), E);
7030 }
7031
Richard Smith4a678122011-10-24 18:44:57 +00007032 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00007033 return Success(0, E);
7034}
7035
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007036bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
7037 return Success(E->getPackLength(), E);
7038}
7039
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007040bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
7041 return Success(E->getValue(), E);
7042}
7043
Chris Lattner05706e882008-07-11 18:11:29 +00007044//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00007045// Float Evaluation
7046//===----------------------------------------------------------------------===//
7047
7048namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007049class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00007050 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00007051 APFloat &Result;
7052public:
7053 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007054 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00007055
Richard Smith2e312c82012-03-03 22:46:17 +00007056 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007057 Result = V.getFloat();
7058 return true;
7059 }
Eli Friedman24c01542008-08-22 00:06:13 +00007060
Richard Smithfddd3842011-12-30 21:15:51 +00007061 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00007062 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
7063 return true;
7064 }
7065
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007066 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007067
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007068 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007069 bool VisitBinaryOperator(const BinaryOperator *E);
7070 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007071 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00007072
John McCallb1fb0d32010-05-07 22:08:54 +00007073 bool VisitUnaryReal(const UnaryOperator *E);
7074 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00007075
Richard Smithfddd3842011-12-30 21:15:51 +00007076 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00007077};
7078} // end anonymous namespace
7079
7080static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007081 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007082 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00007083}
7084
Jay Foad39c79802011-01-12 09:06:06 +00007085static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00007086 QualType ResultTy,
7087 const Expr *Arg,
7088 bool SNaN,
7089 llvm::APFloat &Result) {
7090 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
7091 if (!S) return false;
7092
7093 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
7094
7095 llvm::APInt fill;
7096
7097 // Treat empty strings as if they were zero.
7098 if (S->getString().empty())
7099 fill = llvm::APInt(32, 0);
7100 else if (S->getString().getAsInteger(0, fill))
7101 return false;
7102
7103 if (SNaN)
7104 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7105 else
7106 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7107 return true;
7108}
7109
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007110bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00007111 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007112 default:
7113 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7114
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007115 case Builtin::BI__builtin_huge_val:
7116 case Builtin::BI__builtin_huge_valf:
7117 case Builtin::BI__builtin_huge_vall:
7118 case Builtin::BI__builtin_inf:
7119 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007120 case Builtin::BI__builtin_infl: {
7121 const llvm::fltSemantics &Sem =
7122 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00007123 Result = llvm::APFloat::getInf(Sem);
7124 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007125 }
Mike Stump11289f42009-09-09 15:08:12 +00007126
John McCall16291492010-02-28 13:00:19 +00007127 case Builtin::BI__builtin_nans:
7128 case Builtin::BI__builtin_nansf:
7129 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007130 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7131 true, Result))
7132 return Error(E);
7133 return true;
John McCall16291492010-02-28 13:00:19 +00007134
Chris Lattner0b7282e2008-10-06 06:31:58 +00007135 case Builtin::BI__builtin_nan:
7136 case Builtin::BI__builtin_nanf:
7137 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00007138 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00007139 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00007140 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7141 false, Result))
7142 return Error(E);
7143 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007144
7145 case Builtin::BI__builtin_fabs:
7146 case Builtin::BI__builtin_fabsf:
7147 case Builtin::BI__builtin_fabsl:
7148 if (!EvaluateFloat(E->getArg(0), Result, Info))
7149 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007150
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007151 if (Result.isNegative())
7152 Result.changeSign();
7153 return true;
7154
Richard Smith8889a3d2013-06-13 06:26:32 +00007155 // FIXME: Builtin::BI__builtin_powi
7156 // FIXME: Builtin::BI__builtin_powif
7157 // FIXME: Builtin::BI__builtin_powil
7158
Mike Stump11289f42009-09-09 15:08:12 +00007159 case Builtin::BI__builtin_copysign:
7160 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007161 case Builtin::BI__builtin_copysignl: {
7162 APFloat RHS(0.);
7163 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
7164 !EvaluateFloat(E->getArg(1), RHS, Info))
7165 return false;
7166 Result.copySign(RHS);
7167 return true;
7168 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007169 }
7170}
7171
John McCallb1fb0d32010-05-07 22:08:54 +00007172bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007173 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7174 ComplexValue CV;
7175 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7176 return false;
7177 Result = CV.FloatReal;
7178 return true;
7179 }
7180
7181 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00007182}
7183
7184bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007185 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7186 ComplexValue CV;
7187 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7188 return false;
7189 Result = CV.FloatImag;
7190 return true;
7191 }
7192
Richard Smith4a678122011-10-24 18:44:57 +00007193 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00007194 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
7195 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00007196 return true;
7197}
7198
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007199bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007200 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007201 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007202 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00007203 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00007204 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00007205 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
7206 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007207 Result.changeSign();
7208 return true;
7209 }
7210}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007211
Eli Friedman24c01542008-08-22 00:06:13 +00007212bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007213 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7214 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00007215
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007216 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00007217 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
7218 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00007219 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00007220 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
7221 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00007222}
7223
7224bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
7225 Result = E->getValue();
7226 return true;
7227}
7228
Peter Collingbournee9200682011-05-13 03:29:01 +00007229bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
7230 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00007231
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007232 switch (E->getCastKind()) {
7233 default:
Richard Smith11562c52011-10-28 17:51:58 +00007234 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007235
7236 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007237 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00007238 return EvaluateInteger(SubExpr, IntResult, Info) &&
7239 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
7240 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007241 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007242
7243 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007244 if (!Visit(SubExpr))
7245 return false;
Richard Smith357362d2011-12-13 06:39:58 +00007246 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
7247 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007248 }
John McCalld7646252010-11-14 08:17:51 +00007249
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007250 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00007251 ComplexValue V;
7252 if (!EvaluateComplex(SubExpr, V, Info))
7253 return false;
7254 Result = V.getComplexFloatReal();
7255 return true;
7256 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007257 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007258}
7259
Eli Friedman24c01542008-08-22 00:06:13 +00007260//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007261// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00007262//===----------------------------------------------------------------------===//
7263
7264namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007265class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00007266 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00007267 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00007268
Anders Carlsson537969c2008-11-16 20:27:53 +00007269public:
John McCall93d91dc2010-05-07 17:22:02 +00007270 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007271 : ExprEvaluatorBaseTy(info), Result(Result) {}
7272
Richard Smith2e312c82012-03-03 22:46:17 +00007273 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007274 Result.setFrom(V);
7275 return true;
7276 }
Mike Stump11289f42009-09-09 15:08:12 +00007277
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007278 bool ZeroInitialization(const Expr *E);
7279
Anders Carlsson537969c2008-11-16 20:27:53 +00007280 //===--------------------------------------------------------------------===//
7281 // Visitor Methods
7282 //===--------------------------------------------------------------------===//
7283
Peter Collingbournee9200682011-05-13 03:29:01 +00007284 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007285 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00007286 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007287 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007288 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007289};
7290} // end anonymous namespace
7291
John McCall93d91dc2010-05-07 17:22:02 +00007292static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
7293 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007294 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007295 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007296}
7297
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007298bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00007299 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007300 if (ElemTy->isRealFloatingType()) {
7301 Result.makeComplexFloat();
7302 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
7303 Result.FloatReal = Zero;
7304 Result.FloatImag = Zero;
7305 } else {
7306 Result.makeComplexInt();
7307 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
7308 Result.IntReal = Zero;
7309 Result.IntImag = Zero;
7310 }
7311 return true;
7312}
7313
Peter Collingbournee9200682011-05-13 03:29:01 +00007314bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
7315 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007316
7317 if (SubExpr->getType()->isRealFloatingType()) {
7318 Result.makeComplexFloat();
7319 APFloat &Imag = Result.FloatImag;
7320 if (!EvaluateFloat(SubExpr, Imag, Info))
7321 return false;
7322
7323 Result.FloatReal = APFloat(Imag.getSemantics());
7324 return true;
7325 } else {
7326 assert(SubExpr->getType()->isIntegerType() &&
7327 "Unexpected imaginary literal.");
7328
7329 Result.makeComplexInt();
7330 APSInt &Imag = Result.IntImag;
7331 if (!EvaluateInteger(SubExpr, Imag, Info))
7332 return false;
7333
7334 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
7335 return true;
7336 }
7337}
7338
Peter Collingbournee9200682011-05-13 03:29:01 +00007339bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007340
John McCallfcef3cf2010-12-14 17:51:41 +00007341 switch (E->getCastKind()) {
7342 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007343 case CK_BaseToDerived:
7344 case CK_DerivedToBase:
7345 case CK_UncheckedDerivedToBase:
7346 case CK_Dynamic:
7347 case CK_ToUnion:
7348 case CK_ArrayToPointerDecay:
7349 case CK_FunctionToPointerDecay:
7350 case CK_NullToPointer:
7351 case CK_NullToMemberPointer:
7352 case CK_BaseToDerivedMemberPointer:
7353 case CK_DerivedToBaseMemberPointer:
7354 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00007355 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00007356 case CK_ConstructorConversion:
7357 case CK_IntegralToPointer:
7358 case CK_PointerToIntegral:
7359 case CK_PointerToBoolean:
7360 case CK_ToVoid:
7361 case CK_VectorSplat:
7362 case CK_IntegralCast:
7363 case CK_IntegralToBoolean:
7364 case CK_IntegralToFloating:
7365 case CK_FloatingToIntegral:
7366 case CK_FloatingToBoolean:
7367 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007368 case CK_CPointerToObjCPointerCast:
7369 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007370 case CK_AnyPointerToBlockPointerCast:
7371 case CK_ObjCObjectLValueCast:
7372 case CK_FloatingComplexToReal:
7373 case CK_FloatingComplexToBoolean:
7374 case CK_IntegralComplexToReal:
7375 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00007376 case CK_ARCProduceObject:
7377 case CK_ARCConsumeObject:
7378 case CK_ARCReclaimReturnedObject:
7379 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007380 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00007381 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007382 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007383 case CK_NonAtomicToAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00007384 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00007385
John McCallfcef3cf2010-12-14 17:51:41 +00007386 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007387 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00007388 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007389 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007390
7391 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007392 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007393 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007394 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007395
7396 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007397 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00007398 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007399 return false;
7400
John McCallfcef3cf2010-12-14 17:51:41 +00007401 Result.makeComplexFloat();
7402 Result.FloatImag = APFloat(Real.getSemantics());
7403 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007404 }
7405
John McCallfcef3cf2010-12-14 17:51:41 +00007406 case CK_FloatingComplexCast: {
7407 if (!Visit(E->getSubExpr()))
7408 return false;
7409
7410 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7411 QualType From
7412 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7413
Richard Smith357362d2011-12-13 06:39:58 +00007414 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
7415 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007416 }
7417
7418 case CK_FloatingComplexToIntegralComplex: {
7419 if (!Visit(E->getSubExpr()))
7420 return false;
7421
7422 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7423 QualType From
7424 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7425 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00007426 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
7427 To, Result.IntReal) &&
7428 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
7429 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007430 }
7431
7432 case CK_IntegralRealToComplex: {
7433 APSInt &Real = Result.IntReal;
7434 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
7435 return false;
7436
7437 Result.makeComplexInt();
7438 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
7439 return true;
7440 }
7441
7442 case CK_IntegralComplexCast: {
7443 if (!Visit(E->getSubExpr()))
7444 return false;
7445
7446 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7447 QualType From
7448 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7449
Richard Smith911e1422012-01-30 22:27:01 +00007450 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7451 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007452 return true;
7453 }
7454
7455 case CK_IntegralComplexToFloatingComplex: {
7456 if (!Visit(E->getSubExpr()))
7457 return false;
7458
Ted Kremenek28831752012-08-23 20:46:57 +00007459 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007460 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00007461 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007462 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00007463 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7464 To, Result.FloatReal) &&
7465 HandleIntToFloatCast(Info, E, From, Result.IntImag,
7466 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007467 }
7468 }
7469
7470 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007471}
7472
John McCall93d91dc2010-05-07 17:22:02 +00007473bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007474 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00007475 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7476
Richard Smith253c2a32012-01-27 01:14:48 +00007477 bool LHSOK = Visit(E->getLHS());
7478 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00007479 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007480
John McCall93d91dc2010-05-07 17:22:02 +00007481 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00007482 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00007483 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007484
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007485 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
7486 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007487 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007488 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007489 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007490 if (Result.isComplexFloat()) {
7491 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
7492 APFloat::rmNearestTiesToEven);
7493 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
7494 APFloat::rmNearestTiesToEven);
7495 } else {
7496 Result.getComplexIntReal() += RHS.getComplexIntReal();
7497 Result.getComplexIntImag() += RHS.getComplexIntImag();
7498 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007499 break;
John McCalle3027922010-08-25 11:45:40 +00007500 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007501 if (Result.isComplexFloat()) {
7502 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
7503 APFloat::rmNearestTiesToEven);
7504 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
7505 APFloat::rmNearestTiesToEven);
7506 } else {
7507 Result.getComplexIntReal() -= RHS.getComplexIntReal();
7508 Result.getComplexIntImag() -= RHS.getComplexIntImag();
7509 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007510 break;
John McCalle3027922010-08-25 11:45:40 +00007511 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007512 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00007513 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007514 APFloat &LHS_r = LHS.getComplexFloatReal();
7515 APFloat &LHS_i = LHS.getComplexFloatImag();
7516 APFloat &RHS_r = RHS.getComplexFloatReal();
7517 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00007518
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007519 APFloat Tmp = LHS_r;
7520 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7521 Result.getComplexFloatReal() = Tmp;
7522 Tmp = LHS_i;
7523 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7524 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
7525
7526 Tmp = LHS_r;
7527 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7528 Result.getComplexFloatImag() = Tmp;
7529 Tmp = LHS_i;
7530 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7531 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
7532 } else {
John McCall93d91dc2010-05-07 17:22:02 +00007533 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00007534 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007535 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
7536 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00007537 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007538 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
7539 LHS.getComplexIntImag() * RHS.getComplexIntReal());
7540 }
7541 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007542 case BO_Div:
7543 if (Result.isComplexFloat()) {
7544 ComplexValue LHS = Result;
7545 APFloat &LHS_r = LHS.getComplexFloatReal();
7546 APFloat &LHS_i = LHS.getComplexFloatImag();
7547 APFloat &RHS_r = RHS.getComplexFloatReal();
7548 APFloat &RHS_i = RHS.getComplexFloatImag();
7549 APFloat &Res_r = Result.getComplexFloatReal();
7550 APFloat &Res_i = Result.getComplexFloatImag();
7551
7552 APFloat Den = RHS_r;
7553 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7554 APFloat Tmp = RHS_i;
7555 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7556 Den.add(Tmp, APFloat::rmNearestTiesToEven);
7557
7558 Res_r = LHS_r;
7559 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7560 Tmp = LHS_i;
7561 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7562 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
7563 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
7564
7565 Res_i = LHS_i;
7566 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7567 Tmp = LHS_r;
7568 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7569 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
7570 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
7571 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007572 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
7573 return Error(E, diag::note_expr_divide_by_zero);
7574
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007575 ComplexValue LHS = Result;
7576 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
7577 RHS.getComplexIntImag() * RHS.getComplexIntImag();
7578 Result.getComplexIntReal() =
7579 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
7580 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
7581 Result.getComplexIntImag() =
7582 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
7583 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
7584 }
7585 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007586 }
7587
John McCall93d91dc2010-05-07 17:22:02 +00007588 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007589}
7590
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007591bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7592 // Get the operand value into 'Result'.
7593 if (!Visit(E->getSubExpr()))
7594 return false;
7595
7596 switch (E->getOpcode()) {
7597 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007598 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007599 case UO_Extension:
7600 return true;
7601 case UO_Plus:
7602 // The result is always just the subexpr.
7603 return true;
7604 case UO_Minus:
7605 if (Result.isComplexFloat()) {
7606 Result.getComplexFloatReal().changeSign();
7607 Result.getComplexFloatImag().changeSign();
7608 }
7609 else {
7610 Result.getComplexIntReal() = -Result.getComplexIntReal();
7611 Result.getComplexIntImag() = -Result.getComplexIntImag();
7612 }
7613 return true;
7614 case UO_Not:
7615 if (Result.isComplexFloat())
7616 Result.getComplexFloatImag().changeSign();
7617 else
7618 Result.getComplexIntImag() = -Result.getComplexIntImag();
7619 return true;
7620 }
7621}
7622
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007623bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7624 if (E->getNumInits() == 2) {
7625 if (E->getType()->isComplexType()) {
7626 Result.makeComplexFloat();
7627 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
7628 return false;
7629 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
7630 return false;
7631 } else {
7632 Result.makeComplexInt();
7633 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
7634 return false;
7635 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
7636 return false;
7637 }
7638 return true;
7639 }
7640 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
7641}
7642
Anders Carlsson537969c2008-11-16 20:27:53 +00007643//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00007644// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
7645// implicit conversion.
7646//===----------------------------------------------------------------------===//
7647
7648namespace {
7649class AtomicExprEvaluator :
7650 public ExprEvaluatorBase<AtomicExprEvaluator, bool> {
7651 APValue &Result;
7652public:
7653 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
7654 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7655
7656 bool Success(const APValue &V, const Expr *E) {
7657 Result = V;
7658 return true;
7659 }
7660
7661 bool ZeroInitialization(const Expr *E) {
7662 ImplicitValueInitExpr VIE(
7663 E->getType()->castAs<AtomicType>()->getValueType());
7664 return Evaluate(Result, Info, &VIE);
7665 }
7666
7667 bool VisitCastExpr(const CastExpr *E) {
7668 switch (E->getCastKind()) {
7669 default:
7670 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7671 case CK_NonAtomicToAtomic:
7672 return Evaluate(Result, Info, E->getSubExpr());
7673 }
7674 }
7675};
7676} // end anonymous namespace
7677
7678static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
7679 assert(E->isRValue() && E->getType()->isAtomicType());
7680 return AtomicExprEvaluator(Info, Result).Visit(E);
7681}
7682
7683//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00007684// Void expression evaluation, primarily for a cast to void on the LHS of a
7685// comma operator
7686//===----------------------------------------------------------------------===//
7687
7688namespace {
7689class VoidExprEvaluator
7690 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
7691public:
7692 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
7693
Richard Smith2e312c82012-03-03 22:46:17 +00007694 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00007695
7696 bool VisitCastExpr(const CastExpr *E) {
7697 switch (E->getCastKind()) {
7698 default:
7699 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7700 case CK_ToVoid:
7701 VisitIgnoredValue(E->getSubExpr());
7702 return true;
7703 }
7704 }
7705};
7706} // end anonymous namespace
7707
7708static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
7709 assert(E->isRValue() && E->getType()->isVoidType());
7710 return VoidExprEvaluator(Info).Visit(E);
7711}
7712
7713//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00007714// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00007715//===----------------------------------------------------------------------===//
7716
Richard Smith2e312c82012-03-03 22:46:17 +00007717static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007718 // In C, function designators are not lvalues, but we evaluate them as if they
7719 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00007720 QualType T = E->getType();
7721 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00007722 LValue LV;
7723 if (!EvaluateLValue(E, LV, Info))
7724 return false;
7725 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007726 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007727 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007728 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007729 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007730 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007731 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007732 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00007733 LValue LV;
7734 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007735 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007736 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007737 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00007738 llvm::APFloat F(0.0);
7739 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007740 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007741 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00007742 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00007743 ComplexValue C;
7744 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007745 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007746 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007747 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00007748 MemberPtr P;
7749 if (!EvaluateMemberPointer(E, P, Info))
7750 return false;
7751 P.moveInto(Result);
7752 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00007753 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007754 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007755 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00007756 APValue &Value = Info.CurrentCall->createTemporary(E, false);
7757 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00007758 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00007759 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00007760 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007761 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007762 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00007763 APValue &Value = Info.CurrentCall->createTemporary(E, false);
7764 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00007765 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00007766 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00007767 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007768 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007769 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00007770 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00007771 if (!EvaluateVoid(E, Info))
7772 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007773 } else if (T->isAtomicType()) {
7774 if (!EvaluateAtomic(E, Result, Info))
7775 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007776 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007777 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00007778 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007779 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007780 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00007781 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007782 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007783
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00007784 return true;
7785}
7786
Richard Smithb228a862012-02-15 02:18:13 +00007787/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
7788/// cases, the in-place evaluation is essential, since later initializers for
7789/// an object can indirectly refer to subobjects which were initialized earlier.
7790static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00007791 const Expr *E, bool AllowNonLiteralTypes) {
7792 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00007793 return false;
7794
7795 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00007796 // Evaluate arrays and record types in-place, so that later initializers can
7797 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00007798 if (E->getType()->isArrayType())
7799 return EvaluateArray(E, This, Result, Info);
7800 else if (E->getType()->isRecordType())
7801 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00007802 }
7803
7804 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00007805 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00007806}
7807
Richard Smithf57d8cb2011-12-09 22:58:01 +00007808/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
7809/// lvalue-to-rvalue cast if it is an lvalue.
7810static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00007811 if (!CheckLiteralType(Info, E))
7812 return false;
7813
Richard Smith2e312c82012-03-03 22:46:17 +00007814 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007815 return false;
7816
7817 if (E->isGLValue()) {
7818 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00007819 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00007820 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007821 return false;
7822 }
7823
Richard Smith2e312c82012-03-03 22:46:17 +00007824 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00007825 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007826}
Richard Smith11562c52011-10-28 17:51:58 +00007827
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007828static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
7829 const ASTContext &Ctx, bool &IsConst) {
7830 // Fast-path evaluations of integer literals, since we sometimes see files
7831 // containing vast quantities of these.
7832 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
7833 Result.Val = APValue(APSInt(L->getValue(),
7834 L->getType()->isUnsignedIntegerType()));
7835 IsConst = true;
7836 return true;
7837 }
7838
7839 // FIXME: Evaluating values of large array and record types can cause
7840 // performance problems. Only do so in C++11 for now.
7841 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
7842 Exp->getType()->isRecordType()) &&
7843 !Ctx.getLangOpts().CPlusPlus11) {
7844 IsConst = false;
7845 return true;
7846 }
7847 return false;
7848}
7849
7850
Richard Smith7b553f12011-10-29 00:50:52 +00007851/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00007852/// any crazy technique (that has nothing to do with language standards) that
7853/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00007854/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
7855/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00007856bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007857 bool IsConst;
7858 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
7859 return IsConst;
7860
Richard Smithf57d8cb2011-12-09 22:58:01 +00007861 EvalInfo Info(Ctx, Result);
7862 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00007863}
7864
Jay Foad39c79802011-01-12 09:06:06 +00007865bool Expr::EvaluateAsBooleanCondition(bool &Result,
7866 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00007867 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00007868 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00007869 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00007870}
7871
Richard Smith5fab0c92011-12-28 19:48:30 +00007872bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
7873 SideEffectsKind AllowSideEffects) const {
7874 if (!getType()->isIntegralOrEnumerationType())
7875 return false;
7876
Richard Smith11562c52011-10-28 17:51:58 +00007877 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00007878 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
7879 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00007880 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007881
Richard Smith11562c52011-10-28 17:51:58 +00007882 Result = ExprResult.Val.getInt();
7883 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00007884}
7885
Jay Foad39c79802011-01-12 09:06:06 +00007886bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00007887 EvalInfo Info(Ctx, Result);
7888
John McCall45d55e42010-05-07 21:00:08 +00007889 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007890 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
7891 !CheckLValueConstantExpression(Info, getExprLoc(),
7892 Ctx.getLValueReferenceType(getType()), LV))
7893 return false;
7894
Richard Smith2e312c82012-03-03 22:46:17 +00007895 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00007896 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00007897}
7898
Richard Smithd0b4dd62011-12-19 06:19:21 +00007899bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
7900 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007901 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00007902 // FIXME: Evaluating initializers for large array and record types can cause
7903 // performance problems. Only do so in C++11 for now.
7904 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007905 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00007906 return false;
7907
Richard Smithd0b4dd62011-12-19 06:19:21 +00007908 Expr::EvalStatus EStatus;
7909 EStatus.Diag = &Notes;
7910
7911 EvalInfo InitInfo(Ctx, EStatus);
7912 InitInfo.setEvaluatingDecl(VD, Value);
7913
7914 LValue LVal;
7915 LVal.set(VD);
7916
Richard Smithfddd3842011-12-30 21:15:51 +00007917 // C++11 [basic.start.init]p2:
7918 // Variables with static storage duration or thread storage duration shall be
7919 // zero-initialized before any other initialization takes place.
7920 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007921 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00007922 !VD->getType()->isReferenceType()) {
7923 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00007924 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00007925 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00007926 return false;
7927 }
7928
Richard Smith7525ff62013-05-09 07:14:00 +00007929 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
7930 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00007931 EStatus.HasSideEffects)
7932 return false;
7933
7934 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
7935 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00007936}
7937
Richard Smith7b553f12011-10-29 00:50:52 +00007938/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
7939/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00007940bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00007941 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00007942 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00007943}
Anders Carlsson59689ed2008-11-22 21:04:56 +00007944
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007945APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007946 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007947 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007948 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00007949 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00007950 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00007951 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007952 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00007953
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007954 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00007955}
John McCall864e3962010-05-07 05:32:02 +00007956
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007957void Expr::EvaluateForOverflow(const ASTContext &Ctx,
7958 SmallVectorImpl<PartialDiagnosticAt> *Diags) const {
7959 bool IsConst;
7960 EvalResult EvalResult;
7961 EvalResult.Diag = Diags;
7962 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
7963 EvalInfo Info(Ctx, EvalResult, true);
7964 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
7965 }
7966}
7967
Richard Smithe6c01442013-06-05 00:46:14 +00007968bool Expr::EvalResult::isGlobalLValue() const {
7969 assert(Val.isLValue());
7970 return IsGlobalLValue(Val.getLValueBase());
7971}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00007972
7973
John McCall864e3962010-05-07 05:32:02 +00007974/// isIntegerConstantExpr - this recursive routine will test if an expression is
7975/// an integer constant expression.
7976
7977/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
7978/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00007979
7980// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00007981// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
7982// and a (possibly null) SourceLocation indicating the location of the problem.
7983//
John McCall864e3962010-05-07 05:32:02 +00007984// Note that to reduce code duplication, this helper does no evaluation
7985// itself; the caller checks whether the expression is evaluatable, and
7986// in the rare cases where CheckICE actually cares about the evaluated
7987// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00007988
Dan Gohman28ade552010-07-26 21:25:24 +00007989namespace {
7990
Richard Smith9e575da2012-12-28 13:25:52 +00007991enum ICEKind {
7992 /// This expression is an ICE.
7993 IK_ICE,
7994 /// This expression is not an ICE, but if it isn't evaluated, it's
7995 /// a legal subexpression for an ICE. This return value is used to handle
7996 /// the comma operator in C99 mode, and non-constant subexpressions.
7997 IK_ICEIfUnevaluated,
7998 /// This expression is not an ICE, and is not a legal subexpression for one.
7999 IK_NotICE
8000};
8001
John McCall864e3962010-05-07 05:32:02 +00008002struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00008003 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00008004 SourceLocation Loc;
8005
Richard Smith9e575da2012-12-28 13:25:52 +00008006 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00008007};
8008
Dan Gohman28ade552010-07-26 21:25:24 +00008009}
8010
Richard Smith9e575da2012-12-28 13:25:52 +00008011static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
8012
8013static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00008014
8015static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
8016 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00008017 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00008018 !EVResult.Val.isInt())
8019 return ICEDiag(IK_NotICE, E->getLocStart());
8020
John McCall864e3962010-05-07 05:32:02 +00008021 return NoDiag();
8022}
8023
8024static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
8025 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00008026 if (!E->getType()->isIntegralOrEnumerationType())
8027 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008028
8029 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00008030#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00008031#define STMT(Node, Base) case Expr::Node##Class:
8032#define EXPR(Node, Base)
8033#include "clang/AST/StmtNodes.inc"
8034 case Expr::PredefinedExprClass:
8035 case Expr::FloatingLiteralClass:
8036 case Expr::ImaginaryLiteralClass:
8037 case Expr::StringLiteralClass:
8038 case Expr::ArraySubscriptExprClass:
8039 case Expr::MemberExprClass:
8040 case Expr::CompoundAssignOperatorClass:
8041 case Expr::CompoundLiteralExprClass:
8042 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00008043 case Expr::DesignatedInitExprClass:
8044 case Expr::ImplicitValueInitExprClass:
8045 case Expr::ParenListExprClass:
8046 case Expr::VAArgExprClass:
8047 case Expr::AddrLabelExprClass:
8048 case Expr::StmtExprClass:
8049 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00008050 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00008051 case Expr::CXXDynamicCastExprClass:
8052 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00008053 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00008054 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008055 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00008056 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008057 case Expr::CXXThisExprClass:
8058 case Expr::CXXThrowExprClass:
8059 case Expr::CXXNewExprClass:
8060 case Expr::CXXDeleteExprClass:
8061 case Expr::CXXPseudoDestructorExprClass:
8062 case Expr::UnresolvedLookupExprClass:
8063 case Expr::DependentScopeDeclRefExprClass:
8064 case Expr::CXXConstructExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00008065 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00008066 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00008067 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00008068 case Expr::CXXTemporaryObjectExprClass:
8069 case Expr::CXXUnresolvedConstructExprClass:
8070 case Expr::CXXDependentScopeMemberExprClass:
8071 case Expr::UnresolvedMemberExprClass:
8072 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00008073 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008074 case Expr::ObjCArrayLiteralClass:
8075 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008076 case Expr::ObjCEncodeExprClass:
8077 case Expr::ObjCMessageExprClass:
8078 case Expr::ObjCSelectorExprClass:
8079 case Expr::ObjCProtocolExprClass:
8080 case Expr::ObjCIvarRefExprClass:
8081 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008082 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008083 case Expr::ObjCIsaExprClass:
8084 case Expr::ShuffleVectorExprClass:
8085 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00008086 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00008087 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00008088 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00008089 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00008090 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00008091 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00008092 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00008093 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00008094 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00008095 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00008096 case Expr::InitListExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00008097 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00008098 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00008099
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008100 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00008101 case Expr::GNUNullExprClass:
8102 // GCC considers the GNU __null value to be an integral constant expression.
8103 return NoDiag();
8104
John McCall7c454bb2011-07-15 05:09:51 +00008105 case Expr::SubstNonTypeTemplateParmExprClass:
8106 return
8107 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
8108
John McCall864e3962010-05-07 05:32:02 +00008109 case Expr::ParenExprClass:
8110 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00008111 case Expr::GenericSelectionExprClass:
8112 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008113 case Expr::IntegerLiteralClass:
8114 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008115 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00008116 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00008117 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00008118 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00008119 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00008120 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00008121 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00008122 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00008123 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00008124 return NoDiag();
8125 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00008126 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00008127 // C99 6.6/3 allows function calls within unevaluated subexpressions of
8128 // constant expressions, but they can never be ICEs because an ICE cannot
8129 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00008130 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00008131 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00008132 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008133 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008134 }
Richard Smith6365c912012-02-24 22:12:32 +00008135 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008136 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
8137 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00008138 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008139 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00008140 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00008141 // Parameter variables are never constants. Without this check,
8142 // getAnyInitializer() can find a default argument, which leads
8143 // to chaos.
8144 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00008145 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008146
8147 // C++ 7.1.5.1p2
8148 // A variable of non-volatile const-qualified integral or enumeration
8149 // type initialized by an ICE can be used in ICEs.
8150 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00008151 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00008152 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00008153
Richard Smithd0b4dd62011-12-19 06:19:21 +00008154 const VarDecl *VD;
8155 // Look for a declaration of this variable that has an initializer, and
8156 // check whether it is an ICE.
8157 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
8158 return NoDiag();
8159 else
Richard Smith9e575da2012-12-28 13:25:52 +00008160 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008161 }
8162 }
Richard Smith9e575da2012-12-28 13:25:52 +00008163 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00008164 }
John McCall864e3962010-05-07 05:32:02 +00008165 case Expr::UnaryOperatorClass: {
8166 const UnaryOperator *Exp = cast<UnaryOperator>(E);
8167 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008168 case UO_PostInc:
8169 case UO_PostDec:
8170 case UO_PreInc:
8171 case UO_PreDec:
8172 case UO_AddrOf:
8173 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00008174 // C99 6.6/3 allows increment and decrement within unevaluated
8175 // subexpressions of constant expressions, but they can never be ICEs
8176 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008177 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00008178 case UO_Extension:
8179 case UO_LNot:
8180 case UO_Plus:
8181 case UO_Minus:
8182 case UO_Not:
8183 case UO_Real:
8184 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00008185 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008186 }
Richard Smith9e575da2012-12-28 13:25:52 +00008187
John McCall864e3962010-05-07 05:32:02 +00008188 // OffsetOf falls through here.
8189 }
8190 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00008191 // Note that per C99, offsetof must be an ICE. And AFAIK, using
8192 // EvaluateAsRValue matches the proposed gcc behavior for cases like
8193 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
8194 // compliance: we should warn earlier for offsetof expressions with
8195 // array subscripts that aren't ICEs, and if the array subscripts
8196 // are ICEs, the value of the offsetof must be an integer constant.
8197 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008198 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00008199 case Expr::UnaryExprOrTypeTraitExprClass: {
8200 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
8201 if ((Exp->getKind() == UETT_SizeOf) &&
8202 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00008203 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008204 return NoDiag();
8205 }
8206 case Expr::BinaryOperatorClass: {
8207 const BinaryOperator *Exp = cast<BinaryOperator>(E);
8208 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008209 case BO_PtrMemD:
8210 case BO_PtrMemI:
8211 case BO_Assign:
8212 case BO_MulAssign:
8213 case BO_DivAssign:
8214 case BO_RemAssign:
8215 case BO_AddAssign:
8216 case BO_SubAssign:
8217 case BO_ShlAssign:
8218 case BO_ShrAssign:
8219 case BO_AndAssign:
8220 case BO_XorAssign:
8221 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00008222 // C99 6.6/3 allows assignments within unevaluated subexpressions of
8223 // constant expressions, but they can never be ICEs because an ICE cannot
8224 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008225 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008226
John McCalle3027922010-08-25 11:45:40 +00008227 case BO_Mul:
8228 case BO_Div:
8229 case BO_Rem:
8230 case BO_Add:
8231 case BO_Sub:
8232 case BO_Shl:
8233 case BO_Shr:
8234 case BO_LT:
8235 case BO_GT:
8236 case BO_LE:
8237 case BO_GE:
8238 case BO_EQ:
8239 case BO_NE:
8240 case BO_And:
8241 case BO_Xor:
8242 case BO_Or:
8243 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00008244 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8245 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00008246 if (Exp->getOpcode() == BO_Div ||
8247 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00008248 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00008249 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00008250 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00008251 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008252 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00008253 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008254 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00008255 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008256 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00008257 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008258 }
8259 }
8260 }
John McCalle3027922010-08-25 11:45:40 +00008261 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008262 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00008263 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
8264 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00008265 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
8266 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008267 } else {
8268 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00008269 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008270 }
8271 }
Richard Smith9e575da2012-12-28 13:25:52 +00008272 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008273 }
John McCalle3027922010-08-25 11:45:40 +00008274 case BO_LAnd:
8275 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00008276 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8277 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008278 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00008279 // Rare case where the RHS has a comma "side-effect"; we need
8280 // to actually check the condition to see whether the side
8281 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00008282 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00008283 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00008284 return RHSResult;
8285 return NoDiag();
8286 }
8287
Richard Smith9e575da2012-12-28 13:25:52 +00008288 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008289 }
8290 }
8291 }
8292 case Expr::ImplicitCastExprClass:
8293 case Expr::CStyleCastExprClass:
8294 case Expr::CXXFunctionalCastExprClass:
8295 case Expr::CXXStaticCastExprClass:
8296 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00008297 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00008298 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008299 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00008300 if (isa<ExplicitCastExpr>(E)) {
8301 if (const FloatingLiteral *FL
8302 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
8303 unsigned DestWidth = Ctx.getIntWidth(E->getType());
8304 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
8305 APSInt IgnoredVal(DestWidth, !DestSigned);
8306 bool Ignored;
8307 // If the value does not fit in the destination type, the behavior is
8308 // undefined, so we are not required to treat it as a constant
8309 // expression.
8310 if (FL->getValue().convertToInteger(IgnoredVal,
8311 llvm::APFloat::rmTowardZero,
8312 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00008313 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00008314 return NoDiag();
8315 }
8316 }
Eli Friedman76d4e432011-09-29 21:49:34 +00008317 switch (cast<CastExpr>(E)->getCastKind()) {
8318 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008319 case CK_AtomicToNonAtomic:
8320 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00008321 case CK_NoOp:
8322 case CK_IntegralToBoolean:
8323 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00008324 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00008325 default:
Richard Smith9e575da2012-12-28 13:25:52 +00008326 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00008327 }
John McCall864e3962010-05-07 05:32:02 +00008328 }
John McCallc07a0c72011-02-17 10:25:35 +00008329 case Expr::BinaryConditionalOperatorClass: {
8330 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
8331 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008332 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00008333 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008334 if (FalseResult.Kind == IK_NotICE) return FalseResult;
8335 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
8336 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00008337 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00008338 return FalseResult;
8339 }
John McCall864e3962010-05-07 05:32:02 +00008340 case Expr::ConditionalOperatorClass: {
8341 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
8342 // If the condition (ignoring parens) is a __builtin_constant_p call,
8343 // then only the true side is actually considered in an integer constant
8344 // expression, and it is fully evaluated. This is an important GNU
8345 // extension. See GCC PR38377 for discussion.
8346 if (const CallExpr *CallCE
8347 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00008348 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
8349 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008350 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008351 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008352 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008353
Richard Smithf57d8cb2011-12-09 22:58:01 +00008354 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
8355 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008356
Richard Smith9e575da2012-12-28 13:25:52 +00008357 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008358 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008359 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008360 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008361 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00008362 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008363 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00008364 return NoDiag();
8365 // Rare case where the diagnostics depend on which side is evaluated
8366 // Note that if we get here, CondResult is 0, and at least one of
8367 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00008368 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00008369 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00008370 return TrueResult;
8371 }
8372 case Expr::CXXDefaultArgExprClass:
8373 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00008374 case Expr::CXXDefaultInitExprClass:
8375 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008376 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +00008377 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008378 }
8379 }
8380
David Blaikiee4d798f2012-01-20 21:50:17 +00008381 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00008382}
8383
Richard Smithf57d8cb2011-12-09 22:58:01 +00008384/// Evaluate an expression as a C++11 integral constant expression.
8385static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
8386 const Expr *E,
8387 llvm::APSInt *Value,
8388 SourceLocation *Loc) {
8389 if (!E->getType()->isIntegralOrEnumerationType()) {
8390 if (Loc) *Loc = E->getExprLoc();
8391 return false;
8392 }
8393
Richard Smith66e05fe2012-01-18 05:21:49 +00008394 APValue Result;
8395 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00008396 return false;
8397
Richard Smith66e05fe2012-01-18 05:21:49 +00008398 assert(Result.isInt() && "pointer cast to int is not an ICE");
8399 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00008400 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008401}
8402
Richard Smith92b1ce02011-12-12 09:28:41 +00008403bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008404 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008405 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
8406
Richard Smith9e575da2012-12-28 13:25:52 +00008407 ICEDiag D = CheckICE(this, Ctx);
8408 if (D.Kind != IK_ICE) {
8409 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00008410 return false;
8411 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008412 return true;
8413}
8414
8415bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
8416 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008417 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008418 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
8419
8420 if (!isIntegerConstantExpr(Ctx, Loc))
8421 return false;
8422 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00008423 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00008424 return true;
8425}
Richard Smith66e05fe2012-01-18 05:21:49 +00008426
Richard Smith98a0a492012-02-14 21:38:30 +00008427bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00008428 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00008429}
8430
Richard Smith66e05fe2012-01-18 05:21:49 +00008431bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
8432 SourceLocation *Loc) const {
8433 // We support this checking in C++98 mode in order to diagnose compatibility
8434 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008435 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00008436
Richard Smith98a0a492012-02-14 21:38:30 +00008437 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00008438 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008439 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00008440 Status.Diag = &Diags;
8441 EvalInfo Info(Ctx, Status);
8442
8443 APValue Scratch;
8444 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
8445
8446 if (!Diags.empty()) {
8447 IsConstExpr = false;
8448 if (Loc) *Loc = Diags[0].first;
8449 } else if (!IsConstExpr) {
8450 // FIXME: This shouldn't happen.
8451 if (Loc) *Loc = getExprLoc();
8452 }
8453
8454 return IsConstExpr;
8455}
Richard Smith253c2a32012-01-27 01:14:48 +00008456
8457bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008458 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00008459 PartialDiagnosticAt> &Diags) {
8460 // FIXME: It would be useful to check constexpr function templates, but at the
8461 // moment the constant expression evaluator cannot cope with the non-rigorous
8462 // ASTs which we build for dependent expressions.
8463 if (FD->isDependentContext())
8464 return true;
8465
8466 Expr::EvalStatus Status;
8467 Status.Diag = &Diags;
8468
8469 EvalInfo Info(FD->getASTContext(), Status);
8470 Info.CheckingPotentialConstantExpression = true;
8471
8472 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8473 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
8474
Richard Smith7525ff62013-05-09 07:14:00 +00008475 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00008476 // is a temporary being used as the 'this' pointer.
8477 LValue This;
8478 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00008479 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00008480
Richard Smith253c2a32012-01-27 01:14:48 +00008481 ArrayRef<const Expr*> Args;
8482
8483 SourceLocation Loc = FD->getLocation();
8484
Richard Smith2e312c82012-03-03 22:46:17 +00008485 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00008486 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
8487 // Evaluate the call as a constant initializer, to allow the construction
8488 // of objects of non-literal types.
8489 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00008490 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00008491 } else
Richard Smith253c2a32012-01-27 01:14:48 +00008492 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
8493 Args, FD->getBody(), Info, Scratch);
8494
8495 return Diags.empty();
8496}