blob: 4c98c00474e149a2cff9dff062cca52d444200fc [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
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000305 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000306 /// 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) {
Eli Friedman07185912013-08-29 23:44:43 +0000370 // FIXME: Force the precision of the source value down so we don't
371 // print digits which are usually useless (we don't really care here if
372 // we truncate a digit by accident in edge cases). Ideally,
373 // APFloat::toString would automatically print the shortest
374 // representation which rounds to the correct value, but it's a bit
375 // tricky to implement.
376 unsigned precision =
377 llvm::APFloat::semanticsPrecision(F.getSemantics());
378 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000379 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000380 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000381 *Diag << StringRef(Buffer.data(), Buffer.size());
382 }
383 return *this;
384 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000385 };
386
Richard Smith08d6a2c2013-07-24 07:11:57 +0000387 /// A cleanup, and a flag indicating whether it is lifetime-extended.
388 class Cleanup {
389 llvm::PointerIntPair<APValue*, 1, bool> Value;
390
391 public:
392 Cleanup(APValue *Val, bool IsLifetimeExtended)
393 : Value(Val, IsLifetimeExtended) {}
394
395 bool isLifetimeExtended() const { return Value.getInt(); }
396 void endLifetime() {
397 *Value.getPointer() = APValue();
398 }
399 };
400
Richard Smithb228a862012-02-15 02:18:13 +0000401 /// EvalInfo - This is a private struct used by the evaluator to capture
402 /// information about a subexpression as it is folded. It retains information
403 /// about the AST context, but also maintains information about the folded
404 /// expression.
405 ///
406 /// If an expression could be evaluated, it is still possible it is not a C
407 /// "integer constant expression" or constant expression. If not, this struct
408 /// captures information about how and why not.
409 ///
410 /// One bit of information passed *into* the request for constant folding
411 /// indicates whether the subexpression is "evaluated" or not according to C
412 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
413 /// evaluate the expression regardless of what the RHS is, but C only allows
414 /// certain things in certain situations.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000415 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000416 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000417
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000418 /// EvalStatus - Contains information about the evaluation.
419 Expr::EvalStatus &EvalStatus;
420
421 /// CurrentCall - The top of the constexpr call stack.
422 CallStackFrame *CurrentCall;
423
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000424 /// CallStackDepth - The number of calls in the call stack right now.
425 unsigned CallStackDepth;
426
Richard Smithb228a862012-02-15 02:18:13 +0000427 /// NextCallIndex - The next call index to assign.
428 unsigned NextCallIndex;
429
Richard Smitha3d3bd22013-05-08 02:12:03 +0000430 /// StepsLeft - The remaining number of evaluation steps we're permitted
431 /// to perform. This is essentially a limit for the number of statements
432 /// we will evaluate.
433 unsigned StepsLeft;
434
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000435 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000436 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000437 CallStackFrame BottomFrame;
438
Richard Smith08d6a2c2013-07-24 07:11:57 +0000439 /// A stack of values whose lifetimes end at the end of some surrounding
440 /// evaluation frame.
441 llvm::SmallVector<Cleanup, 16> CleanupStack;
442
Richard Smithd62306a2011-11-10 06:34:14 +0000443 /// EvaluatingDecl - This is the declaration whose initializer is being
444 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000445 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000446
447 /// EvaluatingDeclValue - This is the value being constructed for the
448 /// declaration whose initializer is being evaluated, if any.
449 APValue *EvaluatingDeclValue;
450
Richard Smith357362d2011-12-13 06:39:58 +0000451 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
452 /// notes attached to it will also be stored, otherwise they will not be.
453 bool HasActiveDiagnostic;
454
Richard Smith6d4c6582013-11-05 22:18:15 +0000455 enum EvaluationMode {
456 /// Evaluate as a constant expression. Stop if we find that the expression
457 /// is not a constant expression.
458 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000459
Richard Smith6d4c6582013-11-05 22:18:15 +0000460 /// Evaluate as a potential constant expression. Keep going if we hit a
461 /// construct that we can't evaluate yet (because we don't yet know the
462 /// value of something) but stop if we hit something that could never be
463 /// a constant expression.
464 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000465
Richard Smith6d4c6582013-11-05 22:18:15 +0000466 /// Fold the expression to a constant. Stop if we hit a side-effect that
467 /// we can't model.
468 EM_ConstantFold,
469
470 /// Evaluate the expression looking for integer overflow and similar
471 /// issues. Don't worry about side-effects, and try to visit all
472 /// subexpressions.
473 EM_EvaluateForOverflow,
474
475 /// Evaluate in any way we know how. Don't worry about side-effects that
476 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000477 EM_IgnoreSideEffects,
478
479 /// Evaluate as a constant expression. Stop if we find that the expression
480 /// is not a constant expression. Some expressions can be retried in the
481 /// optimizer if we don't constant fold them here, but in an unevaluated
482 /// context we try to fold them immediately since the optimizer never
483 /// gets a chance to look at it.
484 EM_ConstantExpressionUnevaluated,
485
486 /// Evaluate as a potential constant expression. Keep going if we hit a
487 /// construct that we can't evaluate yet (because we don't yet know the
488 /// value of something) but stop if we hit something that could never be
489 /// a constant expression. Some expressions can be retried in the
490 /// optimizer if we don't constant fold them here, but in an unevaluated
491 /// context we try to fold them immediately since the optimizer never
492 /// gets a chance to look at it.
493 EM_PotentialConstantExpressionUnevaluated
Richard Smith6d4c6582013-11-05 22:18:15 +0000494 } EvalMode;
495
496 /// Are we checking whether the expression is a potential constant
497 /// expression?
498 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000499 return EvalMode == EM_PotentialConstantExpression ||
500 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000501 }
502
503 /// Are we checking an expression for overflow?
504 // FIXME: We should check for any kind of undefined or suspicious behavior
505 // in such constructs, not just overflow.
506 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
507
508 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Richard Smith92b1ce02011-12-12 09:28:41 +0000509 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smithb228a862012-02-15 02:18:13 +0000510 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000511 StepsLeft(getLangOpts().ConstexprStepLimit),
Richard Smithb228a862012-02-15 02:18:13 +0000512 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith7525ff62013-05-09 07:14:00 +0000513 EvaluatingDecl((const ValueDecl*)0), EvaluatingDeclValue(0),
Richard Smith6d4c6582013-11-05 22:18:15 +0000514 HasActiveDiagnostic(false), EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000515
Richard Smith7525ff62013-05-09 07:14:00 +0000516 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
517 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000518 EvaluatingDeclValue = &Value;
519 }
520
David Blaikiebbafb8a2012-03-11 07:00:24 +0000521 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000522
Richard Smith357362d2011-12-13 06:39:58 +0000523 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000524 // Don't perform any constexpr calls (other than the call we're checking)
525 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000526 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000527 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000528 if (NextCallIndex == 0) {
529 // NextCallIndex has wrapped around.
530 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
531 return false;
532 }
Richard Smith357362d2011-12-13 06:39:58 +0000533 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
534 return true;
535 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
536 << getLangOpts().ConstexprCallDepth;
537 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000538 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000539
Richard Smithb228a862012-02-15 02:18:13 +0000540 CallStackFrame *getCallFrame(unsigned CallIndex) {
541 assert(CallIndex && "no call index in getCallFrame");
542 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
543 // be null in this loop.
544 CallStackFrame *Frame = CurrentCall;
545 while (Frame->Index > CallIndex)
546 Frame = Frame->Caller;
547 return (Frame->Index == CallIndex) ? Frame : 0;
548 }
549
Richard Smitha3d3bd22013-05-08 02:12:03 +0000550 bool nextStep(const Stmt *S) {
551 if (!StepsLeft) {
552 Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
553 return false;
554 }
555 --StepsLeft;
556 return true;
557 }
558
Richard Smith357362d2011-12-13 06:39:58 +0000559 private:
560 /// Add a diagnostic to the diagnostics list.
561 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
562 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
563 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
564 return EvalStatus.Diag->back().second;
565 }
566
Richard Smithf6f003a2011-12-16 19:06:07 +0000567 /// Add notes containing a call stack to the current point of evaluation.
568 void addCallStack(unsigned Limit);
569
Richard Smith357362d2011-12-13 06:39:58 +0000570 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000571 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000572 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
573 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000574 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000575 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000576 // If we have a prior diagnostic, it will be noting that the expression
577 // isn't a constant expression. This diagnostic is more important,
578 // unless we require this evaluation to produce a constant expression.
579 //
580 // FIXME: We might want to show both diagnostics to the user in
581 // EM_ConstantFold mode.
582 if (!EvalStatus.Diag->empty()) {
583 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000584 case EM_ConstantFold:
585 case EM_IgnoreSideEffects:
586 case EM_EvaluateForOverflow:
587 if (!EvalStatus.HasSideEffects)
588 break;
589 // We've had side-effects; we want the diagnostic from them, not
590 // some later problem.
Richard Smith6d4c6582013-11-05 22:18:15 +0000591 case EM_ConstantExpression:
592 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000593 case EM_ConstantExpressionUnevaluated:
594 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000595 HasActiveDiagnostic = false;
596 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000597 }
598 }
599
Richard Smithf6f003a2011-12-16 19:06:07 +0000600 unsigned CallStackNotes = CallStackDepth - 1;
601 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
602 if (Limit)
603 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000604 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000605 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000606
Richard Smith357362d2011-12-13 06:39:58 +0000607 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000608 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000609 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
610 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000611 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000612 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000613 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000614 }
Richard Smith357362d2011-12-13 06:39:58 +0000615 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000616 return OptionalDiagnostic();
617 }
618
Richard Smithce1ec5e2012-03-15 04:53:45 +0000619 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
620 = diag::note_invalid_subexpr_in_const_expr,
621 unsigned ExtraNotes = 0) {
622 if (EvalStatus.Diag)
623 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
624 HasActiveDiagnostic = false;
625 return OptionalDiagnostic();
626 }
627
Richard Smith92b1ce02011-12-12 09:28:41 +0000628 /// Diagnose that the evaluation does not produce a C++11 core constant
629 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000630 ///
631 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
632 /// EM_PotentialConstantExpression mode and we produce one of these.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000633 template<typename LocArg>
634 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000635 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000636 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000637 // Don't override a previous diagnostic. Don't bother collecting
638 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000639 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000640 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000641 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000642 }
Richard Smith357362d2011-12-13 06:39:58 +0000643 return Diag(Loc, DiagId, ExtraNotes);
644 }
645
646 /// Add a note to a prior diagnostic.
647 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
648 if (!HasActiveDiagnostic)
649 return OptionalDiagnostic();
650 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000651 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000652
653 /// Add a stack of notes to a prior diagnostic.
654 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
655 if (HasActiveDiagnostic) {
656 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
657 Diags.begin(), Diags.end());
658 }
659 }
Richard Smith253c2a32012-01-27 01:14:48 +0000660
Richard Smith6d4c6582013-11-05 22:18:15 +0000661 /// Should we continue evaluation after encountering a side-effect that we
662 /// couldn't model?
663 bool keepEvaluatingAfterSideEffect() {
664 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000665 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000666 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000667 case EM_EvaluateForOverflow:
668 case EM_IgnoreSideEffects:
669 return true;
670
Richard Smith6d4c6582013-11-05 22:18:15 +0000671 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000672 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000673 case EM_ConstantFold:
674 return false;
675 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000676 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000677 }
678
679 /// Note that we have had a side-effect, and determine whether we should
680 /// keep evaluating.
681 bool noteSideEffect() {
682 EvalStatus.HasSideEffects = true;
683 return keepEvaluatingAfterSideEffect();
684 }
685
Richard Smith253c2a32012-01-27 01:14:48 +0000686 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000687 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000688 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000689 if (!StepsLeft)
690 return false;
691
692 switch (EvalMode) {
693 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000694 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000695 case EM_EvaluateForOverflow:
696 return true;
697
698 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000699 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000700 case EM_ConstantFold:
701 case EM_IgnoreSideEffects:
702 return false;
703 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000704 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000705 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000706 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000707
708 /// Object used to treat all foldable expressions as constant expressions.
709 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000710 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000711 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000712 bool HadNoPriorDiags;
713 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000714
Richard Smith6d4c6582013-11-05 22:18:15 +0000715 explicit FoldConstant(EvalInfo &Info, bool Enabled)
716 : Info(Info),
717 Enabled(Enabled),
718 HadNoPriorDiags(Info.EvalStatus.Diag &&
719 Info.EvalStatus.Diag->empty() &&
720 !Info.EvalStatus.HasSideEffects),
721 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000722 if (Enabled &&
723 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
724 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000725 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000726 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000727 void keepDiagnostics() { Enabled = false; }
728 ~FoldConstant() {
729 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000730 !Info.EvalStatus.HasSideEffects)
731 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000732 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000733 }
734 };
Richard Smith17100ba2012-02-16 02:46:34 +0000735
736 /// RAII object used to suppress diagnostics and side-effects from a
737 /// speculative evaluation.
738 class SpeculativeEvaluationRAII {
739 EvalInfo &Info;
740 Expr::EvalStatus Old;
741
742 public:
743 SpeculativeEvaluationRAII(EvalInfo &Info,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000744 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = 0)
Richard Smith17100ba2012-02-16 02:46:34 +0000745 : Info(Info), Old(Info.EvalStatus) {
746 Info.EvalStatus.Diag = NewDiag;
Richard Smith6d4c6582013-11-05 22:18:15 +0000747 // If we're speculatively evaluating, we may have skipped over some
748 // evaluations and missed out a side effect.
749 Info.EvalStatus.HasSideEffects = true;
Richard Smith17100ba2012-02-16 02:46:34 +0000750 }
751 ~SpeculativeEvaluationRAII() {
752 Info.EvalStatus = Old;
753 }
754 };
Richard Smith08d6a2c2013-07-24 07:11:57 +0000755
756 /// RAII object wrapping a full-expression or block scope, and handling
757 /// the ending of the lifetime of temporaries created within it.
758 template<bool IsFullExpression>
759 class ScopeRAII {
760 EvalInfo &Info;
761 unsigned OldStackSize;
762 public:
763 ScopeRAII(EvalInfo &Info)
764 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
765 ~ScopeRAII() {
766 // Body moved to a static method to encourage the compiler to inline away
767 // instances of this class.
768 cleanup(Info, OldStackSize);
769 }
770 private:
771 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
772 unsigned NewEnd = OldStackSize;
773 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
774 I != N; ++I) {
775 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
776 // Full-expression cleanup of a lifetime-extended temporary: nothing
777 // to do, just move this cleanup to the right place in the stack.
778 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
779 ++NewEnd;
780 } else {
781 // End the lifetime of the object.
782 Info.CleanupStack[I].endLifetime();
783 }
784 }
785 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
786 Info.CleanupStack.end());
787 }
788 };
789 typedef ScopeRAII<false> BlockScopeRAII;
790 typedef ScopeRAII<true> FullExpressionRAII;
Richard Smithf6f003a2011-12-16 19:06:07 +0000791}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000792
Richard Smitha8105bc2012-01-06 16:39:00 +0000793bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
794 CheckSubobjectKind CSK) {
795 if (Invalid)
796 return false;
797 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000798 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000799 << CSK;
800 setInvalid();
801 return false;
802 }
803 return true;
804}
805
806void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
807 const Expr *E, uint64_t N) {
808 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000809 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000810 << static_cast<int>(N) << /*array*/ 0
811 << static_cast<unsigned>(MostDerivedArraySize);
812 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000813 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000814 << static_cast<int>(N) << /*non-array*/ 1;
815 setInvalid();
816}
817
Richard Smithf6f003a2011-12-16 19:06:07 +0000818CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
819 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000820 APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000821 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000822 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000823 Info.CurrentCall = this;
824 ++Info.CallStackDepth;
825}
826
827CallStackFrame::~CallStackFrame() {
828 assert(Info.CurrentCall == this && "calls retired out of order");
829 --Info.CallStackDepth;
830 Info.CurrentCall = Caller;
831}
832
Richard Smith08d6a2c2013-07-24 07:11:57 +0000833APValue &CallStackFrame::createTemporary(const void *Key,
834 bool IsLifetimeExtended) {
835 APValue &Result = Temporaries[Key];
836 assert(Result.isUninit() && "temporary created multiple times");
837 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
838 return Result;
839}
840
Richard Smith84401042013-06-03 05:03:02 +0000841static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +0000842
843void EvalInfo::addCallStack(unsigned Limit) {
844 // Determine which calls to skip, if any.
845 unsigned ActiveCalls = CallStackDepth - 1;
846 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
847 if (Limit && Limit < ActiveCalls) {
848 SkipStart = Limit / 2 + Limit % 2;
849 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000850 }
851
Richard Smithf6f003a2011-12-16 19:06:07 +0000852 // Walk the call stack and add the diagnostics.
853 unsigned CallIdx = 0;
854 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
855 Frame = Frame->Caller, ++CallIdx) {
856 // Skip this call?
857 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
858 if (CallIdx == SkipStart) {
859 // Note that we're skipping calls.
860 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
861 << unsigned(ActiveCalls - Limit);
862 }
863 continue;
864 }
865
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000866 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +0000867 llvm::raw_svector_ostream Out(Buffer);
868 describeCall(Frame, Out);
869 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
870 }
871}
872
873namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000874 struct ComplexValue {
875 private:
876 bool IsInt;
877
878 public:
879 APSInt IntReal, IntImag;
880 APFloat FloatReal, FloatImag;
881
882 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
883
884 void makeComplexFloat() { IsInt = false; }
885 bool isComplexFloat() const { return !IsInt; }
886 APFloat &getComplexFloatReal() { return FloatReal; }
887 APFloat &getComplexFloatImag() { return FloatImag; }
888
889 void makeComplexInt() { IsInt = true; }
890 bool isComplexInt() const { return IsInt; }
891 APSInt &getComplexIntReal() { return IntReal; }
892 APSInt &getComplexIntImag() { return IntImag; }
893
Richard Smith2e312c82012-03-03 22:46:17 +0000894 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000895 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +0000896 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000897 else
Richard Smith2e312c82012-03-03 22:46:17 +0000898 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000899 }
Richard Smith2e312c82012-03-03 22:46:17 +0000900 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000901 assert(v.isComplexFloat() || v.isComplexInt());
902 if (v.isComplexFloat()) {
903 makeComplexFloat();
904 FloatReal = v.getComplexFloatReal();
905 FloatImag = v.getComplexFloatImag();
906 } else {
907 makeComplexInt();
908 IntReal = v.getComplexIntReal();
909 IntImag = v.getComplexIntImag();
910 }
911 }
John McCall93d91dc2010-05-07 17:22:02 +0000912 };
John McCall45d55e42010-05-07 21:00:08 +0000913
914 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000915 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000916 CharUnits Offset;
Richard Smithb228a862012-02-15 02:18:13 +0000917 unsigned CallIndex;
Richard Smith96e0c102011-11-04 02:25:55 +0000918 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000919
Richard Smithce40ad62011-11-12 22:28:03 +0000920 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000921 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000922 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +0000923 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +0000924 SubobjectDesignator &getLValueDesignator() { return Designator; }
925 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000926
Richard Smith2e312c82012-03-03 22:46:17 +0000927 void moveInto(APValue &V) const {
928 if (Designator.Invalid)
929 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
930 else
931 V = APValue(Base, Offset, Designator.Entries,
932 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000933 }
Richard Smith2e312c82012-03-03 22:46:17 +0000934 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000935 assert(V.isLValue());
936 Base = V.getLValueBase();
937 Offset = V.getLValueOffset();
Richard Smithb228a862012-02-15 02:18:13 +0000938 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +0000939 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +0000940 }
941
Richard Smithb228a862012-02-15 02:18:13 +0000942 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smithce40ad62011-11-12 22:28:03 +0000943 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000944 Offset = CharUnits::Zero();
Richard Smithb228a862012-02-15 02:18:13 +0000945 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +0000946 Designator = SubobjectDesignator(getType(B));
947 }
948
949 // Check that this LValue is not based on a null pointer. If it is, produce
950 // a diagnostic and mark the designator as invalid.
951 bool checkNullPointer(EvalInfo &Info, const Expr *E,
952 CheckSubobjectKind CSK) {
953 if (Designator.Invalid)
954 return false;
955 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000956 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000957 << CSK;
958 Designator.setInvalid();
959 return false;
960 }
961 return true;
962 }
963
964 // Check this LValue refers to an object. If not, set the designator to be
965 // invalid and emit a diagnostic.
966 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000967 // Outside C++11, do not build a designator referring to a subobject of
968 // any object: we won't use such a designator for anything.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000969 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000970 Designator.setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000971 return checkNullPointer(Info, E, CSK) &&
972 Designator.checkSubobject(Info, E, CSK);
973 }
974
975 void addDecl(EvalInfo &Info, const Expr *E,
976 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000977 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
978 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +0000979 }
980 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000981 if (checkSubobject(Info, E, CSK_ArrayToPointer))
982 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +0000983 }
Richard Smith66c96992012-02-18 22:04:06 +0000984 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000985 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
986 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +0000987 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000988 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000989 if (checkNullPointer(Info, E, CSK_ArrayIndex))
990 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +0000991 }
John McCall45d55e42010-05-07 21:00:08 +0000992 };
Richard Smith027bf112011-11-17 22:56:20 +0000993
994 struct MemberPtr {
995 MemberPtr() {}
996 explicit MemberPtr(const ValueDecl *Decl) :
997 DeclAndIsDerivedMember(Decl, false), Path() {}
998
999 /// The member or (direct or indirect) field referred to by this member
1000 /// pointer, or 0 if this is a null member pointer.
1001 const ValueDecl *getDecl() const {
1002 return DeclAndIsDerivedMember.getPointer();
1003 }
1004 /// Is this actually a member of some type derived from the relevant class?
1005 bool isDerivedMember() const {
1006 return DeclAndIsDerivedMember.getInt();
1007 }
1008 /// Get the class which the declaration actually lives in.
1009 const CXXRecordDecl *getContainingRecord() const {
1010 return cast<CXXRecordDecl>(
1011 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1012 }
1013
Richard Smith2e312c82012-03-03 22:46:17 +00001014 void moveInto(APValue &V) const {
1015 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001016 }
Richard Smith2e312c82012-03-03 22:46:17 +00001017 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001018 assert(V.isMemberPointer());
1019 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1020 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1021 Path.clear();
1022 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1023 Path.insert(Path.end(), P.begin(), P.end());
1024 }
1025
1026 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1027 /// whether the member is a member of some class derived from the class type
1028 /// of the member pointer.
1029 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1030 /// Path - The path of base/derived classes from the member declaration's
1031 /// class (exclusive) to the class type of the member pointer (inclusive).
1032 SmallVector<const CXXRecordDecl*, 4> Path;
1033
1034 /// Perform a cast towards the class of the Decl (either up or down the
1035 /// hierarchy).
1036 bool castBack(const CXXRecordDecl *Class) {
1037 assert(!Path.empty());
1038 const CXXRecordDecl *Expected;
1039 if (Path.size() >= 2)
1040 Expected = Path[Path.size() - 2];
1041 else
1042 Expected = getContainingRecord();
1043 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1044 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1045 // if B does not contain the original member and is not a base or
1046 // derived class of the class containing the original member, the result
1047 // of the cast is undefined.
1048 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1049 // (D::*). We consider that to be a language defect.
1050 return false;
1051 }
1052 Path.pop_back();
1053 return true;
1054 }
1055 /// Perform a base-to-derived member pointer cast.
1056 bool castToDerived(const CXXRecordDecl *Derived) {
1057 if (!getDecl())
1058 return true;
1059 if (!isDerivedMember()) {
1060 Path.push_back(Derived);
1061 return true;
1062 }
1063 if (!castBack(Derived))
1064 return false;
1065 if (Path.empty())
1066 DeclAndIsDerivedMember.setInt(false);
1067 return true;
1068 }
1069 /// Perform a derived-to-base member pointer cast.
1070 bool castToBase(const CXXRecordDecl *Base) {
1071 if (!getDecl())
1072 return true;
1073 if (Path.empty())
1074 DeclAndIsDerivedMember.setInt(true);
1075 if (isDerivedMember()) {
1076 Path.push_back(Base);
1077 return true;
1078 }
1079 return castBack(Base);
1080 }
1081 };
Richard Smith357362d2011-12-13 06:39:58 +00001082
Richard Smith7bb00672012-02-01 01:42:44 +00001083 /// Compare two member pointers, which are assumed to be of the same type.
1084 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1085 if (!LHS.getDecl() || !RHS.getDecl())
1086 return !LHS.getDecl() && !RHS.getDecl();
1087 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1088 return false;
1089 return LHS.Path == RHS.Path;
1090 }
John McCall93d91dc2010-05-07 17:22:02 +00001091}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001092
Richard Smith2e312c82012-03-03 22:46:17 +00001093static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001094static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1095 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001096 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +00001097static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1098static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +00001099static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1100 EvalInfo &Info);
1101static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +00001102static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001103static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001104 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001105static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001106static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +00001107static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +00001108
1109//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001110// Misc utilities
1111//===----------------------------------------------------------------------===//
1112
Richard Smith84401042013-06-03 05:03:02 +00001113/// Produce a string describing the given constexpr call.
1114static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1115 unsigned ArgIndex = 0;
1116 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1117 !isa<CXXConstructorDecl>(Frame->Callee) &&
1118 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1119
1120 if (!IsMemberCall)
1121 Out << *Frame->Callee << '(';
1122
1123 if (Frame->This && IsMemberCall) {
1124 APValue Val;
1125 Frame->This->moveInto(Val);
1126 Val.printPretty(Out, Frame->Info.Ctx,
1127 Frame->This->Designator.MostDerivedType);
1128 // FIXME: Add parens around Val if needed.
1129 Out << "->" << *Frame->Callee << '(';
1130 IsMemberCall = false;
1131 }
1132
1133 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1134 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1135 if (ArgIndex > (unsigned)IsMemberCall)
1136 Out << ", ";
1137
1138 const ParmVarDecl *Param = *I;
1139 const APValue &Arg = Frame->Arguments[ArgIndex];
1140 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1141
1142 if (ArgIndex == 0 && IsMemberCall)
1143 Out << "->" << *Frame->Callee << '(';
1144 }
1145
1146 Out << ')';
1147}
1148
Richard Smithd9f663b2013-04-22 15:31:51 +00001149/// Evaluate an expression to see if it had side-effects, and discard its
1150/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001151/// \return \c true if the caller should keep evaluating.
1152static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001153 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001154 if (!Evaluate(Scratch, Info, E))
1155 // We don't need the value, but we might have skipped a side effect here.
1156 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001157 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001158}
1159
Richard Smith861b5b52013-05-07 23:34:45 +00001160/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1161/// return its existing value.
1162static int64_t getExtValue(const APSInt &Value) {
1163 return Value.isSigned() ? Value.getSExtValue()
1164 : static_cast<int64_t>(Value.getZExtValue());
1165}
1166
Richard Smithd62306a2011-11-10 06:34:14 +00001167/// Should this call expression be treated as a string literal?
1168static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001169 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001170 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1171 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1172}
1173
Richard Smithce40ad62011-11-12 22:28:03 +00001174static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001175 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1176 // constant expression of pointer type that evaluates to...
1177
1178 // ... a null pointer value, or a prvalue core constant expression of type
1179 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001180 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001181
Richard Smithce40ad62011-11-12 22:28:03 +00001182 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1183 // ... the address of an object with static storage duration,
1184 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1185 return VD->hasGlobalStorage();
1186 // ... the address of a function,
1187 return isa<FunctionDecl>(D);
1188 }
1189
1190 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001191 switch (E->getStmtClass()) {
1192 default:
1193 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001194 case Expr::CompoundLiteralExprClass: {
1195 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1196 return CLE->isFileScope() && CLE->isLValue();
1197 }
Richard Smithe6c01442013-06-05 00:46:14 +00001198 case Expr::MaterializeTemporaryExprClass:
1199 // A materialized temporary might have been lifetime-extended to static
1200 // storage duration.
1201 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001202 // A string literal has static storage duration.
1203 case Expr::StringLiteralClass:
1204 case Expr::PredefinedExprClass:
1205 case Expr::ObjCStringLiteralClass:
1206 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001207 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001208 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001209 return true;
1210 case Expr::CallExprClass:
1211 return IsStringLiteralCall(cast<CallExpr>(E));
1212 // For GCC compatibility, &&label has static storage duration.
1213 case Expr::AddrLabelExprClass:
1214 return true;
1215 // A Block literal expression may be used as the initialization value for
1216 // Block variables at global or local static scope.
1217 case Expr::BlockExprClass:
1218 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001219 case Expr::ImplicitValueInitExprClass:
1220 // FIXME:
1221 // We can never form an lvalue with an implicit value initialization as its
1222 // base through expression evaluation, so these only appear in one case: the
1223 // implicit variable declaration we invent when checking whether a constexpr
1224 // constructor can produce a constant expression. We must assume that such
1225 // an expression might be a global lvalue.
1226 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001227 }
John McCall95007602010-05-10 23:27:23 +00001228}
1229
Richard Smithb228a862012-02-15 02:18:13 +00001230static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1231 assert(Base && "no location for a null lvalue");
1232 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1233 if (VD)
1234 Info.Note(VD->getLocation(), diag::note_declared_at);
1235 else
Ted Kremenek28831752012-08-23 20:46:57 +00001236 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001237 diag::note_constexpr_temporary_here);
1238}
1239
Richard Smith80815602011-11-07 05:07:52 +00001240/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001241/// value for an address or reference constant expression. Return true if we
1242/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001243static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1244 QualType Type, const LValue &LVal) {
1245 bool IsReferenceType = Type->isReferenceType();
1246
Richard Smith357362d2011-12-13 06:39:58 +00001247 APValue::LValueBase Base = LVal.getLValueBase();
1248 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1249
Richard Smith0dea49e2012-02-18 04:58:18 +00001250 // Check that the object is a global. Note that the fake 'this' object we
1251 // manufacture when checking potential constant expressions is conservatively
1252 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001253 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001254 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001255 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001256 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1257 << IsReferenceType << !Designator.Entries.empty()
1258 << !!VD << VD;
1259 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001260 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001261 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001262 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001263 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001264 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001265 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001266 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001267 LVal.getLValueCallIndex() == 0) &&
1268 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001269
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001270 // Check if this is a thread-local variable.
1271 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1272 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
Richard Smithfd3834f2013-04-13 02:43:54 +00001273 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001274 return false;
1275 }
1276 }
1277
Richard Smitha8105bc2012-01-06 16:39:00 +00001278 // Allow address constant expressions to be past-the-end pointers. This is
1279 // an extension: the standard requires them to point to an object.
1280 if (!IsReferenceType)
1281 return true;
1282
1283 // A reference constant expression must refer to an object.
1284 if (!Base) {
1285 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001286 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001287 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001288 }
1289
Richard Smith357362d2011-12-13 06:39:58 +00001290 // Does this refer one past the end of some object?
Richard Smitha8105bc2012-01-06 16:39:00 +00001291 if (Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001292 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001293 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001294 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001295 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001296 }
1297
Richard Smith80815602011-11-07 05:07:52 +00001298 return true;
1299}
1300
Richard Smithfddd3842011-12-30 21:15:51 +00001301/// Check that this core constant expression is of literal type, and if not,
1302/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001303static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1304 const LValue *This = 0) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001305 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001306 return true;
1307
Richard Smith7525ff62013-05-09 07:14:00 +00001308 // C++1y: A constant initializer for an object o [...] may also invoke
1309 // constexpr constructors for o and its subobjects even if those objects
1310 // are of non-literal class types.
1311 if (Info.getLangOpts().CPlusPlus1y && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001312 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001313 return true;
1314
Richard Smithfddd3842011-12-30 21:15:51 +00001315 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001316 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001317 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001318 << E->getType();
1319 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001320 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001321 return false;
1322}
1323
Richard Smith0b0a0b62011-10-29 20:57:55 +00001324/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001325/// constant expression. If not, report an appropriate diagnostic. Does not
1326/// check that the expression is of literal type.
1327static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1328 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001329 if (Value.isUninit()) {
Richard Smith51f03172013-06-20 03:00:05 +00001330 Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1331 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001332 return false;
1333 }
1334
Richard Smithb228a862012-02-15 02:18:13 +00001335 // Core issue 1454: For a literal constant expression of array or class type,
1336 // each subobject of its value shall have been initialized by a constant
1337 // expression.
1338 if (Value.isArray()) {
1339 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1340 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1341 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1342 Value.getArrayInitializedElt(I)))
1343 return false;
1344 }
1345 if (!Value.hasArrayFiller())
1346 return true;
1347 return CheckConstantExpression(Info, DiagLoc, EltTy,
1348 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001349 }
Richard Smithb228a862012-02-15 02:18:13 +00001350 if (Value.isUnion() && Value.getUnionField()) {
1351 return CheckConstantExpression(Info, DiagLoc,
1352 Value.getUnionField()->getType(),
1353 Value.getUnionValue());
1354 }
1355 if (Value.isStruct()) {
1356 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1357 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1358 unsigned BaseIndex = 0;
1359 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1360 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1361 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1362 Value.getStructBase(BaseIndex)))
1363 return false;
1364 }
1365 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001366 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001367 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1368 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001369 return false;
1370 }
1371 }
1372
1373 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001374 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001375 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001376 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1377 }
1378
1379 // Everything else is fine.
1380 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001381}
1382
Richard Smith83c68212011-10-31 05:11:32 +00001383const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001384 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001385}
1386
1387static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001388 if (Value.CallIndex)
1389 return false;
1390 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1391 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001392}
1393
Richard Smithcecf1842011-11-01 21:06:14 +00001394static bool IsWeakLValue(const LValue &Value) {
1395 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001396 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001397}
1398
Richard Smith2e312c82012-03-03 22:46:17 +00001399static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001400 // A null base expression indicates a null pointer. These are always
1401 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001402 if (!Value.getLValueBase()) {
1403 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001404 return true;
1405 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001406
Richard Smith027bf112011-11-17 22:56:20 +00001407 // We have a non-null base. These are generally known to be true, but if it's
1408 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001409 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001410 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001411 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001412}
1413
Richard Smith2e312c82012-03-03 22:46:17 +00001414static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001415 switch (Val.getKind()) {
1416 case APValue::Uninitialized:
1417 return false;
1418 case APValue::Int:
1419 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001420 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001421 case APValue::Float:
1422 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001423 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001424 case APValue::ComplexInt:
1425 Result = Val.getComplexIntReal().getBoolValue() ||
1426 Val.getComplexIntImag().getBoolValue();
1427 return true;
1428 case APValue::ComplexFloat:
1429 Result = !Val.getComplexFloatReal().isZero() ||
1430 !Val.getComplexFloatImag().isZero();
1431 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001432 case APValue::LValue:
1433 return EvalPointerValueAsBool(Val, Result);
1434 case APValue::MemberPointer:
1435 Result = Val.getMemberPointerDecl();
1436 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001437 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001438 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001439 case APValue::Struct:
1440 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001441 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001442 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001443 }
1444
Richard Smith11562c52011-10-28 17:51:58 +00001445 llvm_unreachable("unknown APValue kind");
1446}
1447
1448static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1449 EvalInfo &Info) {
1450 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001451 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001452 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001453 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001454 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001455}
1456
Richard Smith357362d2011-12-13 06:39:58 +00001457template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001458static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001459 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001460 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001461 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001462}
1463
1464static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1465 QualType SrcType, const APFloat &Value,
1466 QualType DestType, APSInt &Result) {
1467 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001468 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001469 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001470
Richard Smith357362d2011-12-13 06:39:58 +00001471 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001472 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001473 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1474 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001475 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001476 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001477}
1478
Richard Smith357362d2011-12-13 06:39:58 +00001479static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1480 QualType SrcType, QualType DestType,
1481 APFloat &Result) {
1482 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001483 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001484 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1485 APFloat::rmNearestTiesToEven, &ignored)
1486 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001487 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001488 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001489}
1490
Richard Smith911e1422012-01-30 22:27:01 +00001491static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1492 QualType DestType, QualType SrcType,
1493 APSInt &Value) {
1494 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001495 APSInt Result = Value;
1496 // Figure out if this is a truncate, extend or noop cast.
1497 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001498 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001499 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001500 return Result;
1501}
1502
Richard Smith357362d2011-12-13 06:39:58 +00001503static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1504 QualType SrcType, const APSInt &Value,
1505 QualType DestType, APFloat &Result) {
1506 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1507 if (Result.convertFromAPInt(Value, Value.isSigned(),
1508 APFloat::rmNearestTiesToEven)
1509 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001510 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001511 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001512}
1513
Richard Smith49ca8aa2013-08-06 07:09:20 +00001514static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1515 APValue &Value, const FieldDecl *FD) {
1516 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1517
1518 if (!Value.isInt()) {
1519 // Trying to store a pointer-cast-to-integer into a bitfield.
1520 // FIXME: In this case, we should provide the diagnostic for casting
1521 // a pointer to an integer.
1522 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1523 Info.Diag(E);
1524 return false;
1525 }
1526
1527 APSInt &Int = Value.getInt();
1528 unsigned OldBitWidth = Int.getBitWidth();
1529 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1530 if (NewBitWidth < OldBitWidth)
1531 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1532 return true;
1533}
1534
Eli Friedman803acb32011-12-22 03:51:45 +00001535static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1536 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001537 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001538 if (!Evaluate(SVal, Info, E))
1539 return false;
1540 if (SVal.isInt()) {
1541 Res = SVal.getInt();
1542 return true;
1543 }
1544 if (SVal.isFloat()) {
1545 Res = SVal.getFloat().bitcastToAPInt();
1546 return true;
1547 }
1548 if (SVal.isVector()) {
1549 QualType VecTy = E->getType();
1550 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1551 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1552 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1553 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1554 Res = llvm::APInt::getNullValue(VecSize);
1555 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1556 APValue &Elt = SVal.getVectorElt(i);
1557 llvm::APInt EltAsInt;
1558 if (Elt.isInt()) {
1559 EltAsInt = Elt.getInt();
1560 } else if (Elt.isFloat()) {
1561 EltAsInt = Elt.getFloat().bitcastToAPInt();
1562 } else {
1563 // Don't try to handle vectors of anything other than int or float
1564 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001565 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001566 return false;
1567 }
1568 unsigned BaseEltSize = EltAsInt.getBitWidth();
1569 if (BigEndian)
1570 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1571 else
1572 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1573 }
1574 return true;
1575 }
1576 // Give up if the input isn't an int, float, or vector. For example, we
1577 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001578 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001579 return false;
1580}
1581
Richard Smith43e77732013-05-07 04:50:00 +00001582/// Perform the given integer operation, which is known to need at most BitWidth
1583/// bits, and check for overflow in the original type (if that type was not an
1584/// unsigned type).
1585template<typename Operation>
1586static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1587 const APSInt &LHS, const APSInt &RHS,
1588 unsigned BitWidth, Operation Op) {
1589 if (LHS.isUnsigned())
1590 return Op(LHS, RHS);
1591
1592 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1593 APSInt Result = Value.trunc(LHS.getBitWidth());
1594 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001595 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001596 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1597 diag::warn_integer_constant_overflow)
1598 << Result.toString(10) << E->getType();
1599 else
1600 HandleOverflow(Info, E, Value, E->getType());
1601 }
1602 return Result;
1603}
1604
1605/// Perform the given binary integer operation.
1606static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1607 BinaryOperatorKind Opcode, APSInt RHS,
1608 APSInt &Result) {
1609 switch (Opcode) {
1610 default:
1611 Info.Diag(E);
1612 return false;
1613 case BO_Mul:
1614 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1615 std::multiplies<APSInt>());
1616 return true;
1617 case BO_Add:
1618 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1619 std::plus<APSInt>());
1620 return true;
1621 case BO_Sub:
1622 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1623 std::minus<APSInt>());
1624 return true;
1625 case BO_And: Result = LHS & RHS; return true;
1626 case BO_Xor: Result = LHS ^ RHS; return true;
1627 case BO_Or: Result = LHS | RHS; return true;
1628 case BO_Div:
1629 case BO_Rem:
1630 if (RHS == 0) {
1631 Info.Diag(E, diag::note_expr_divide_by_zero);
1632 return false;
1633 }
1634 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1635 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1636 LHS.isSigned() && LHS.isMinSignedValue())
1637 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1638 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1639 return true;
1640 case BO_Shl: {
1641 if (Info.getLangOpts().OpenCL)
1642 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1643 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1644 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1645 RHS.isUnsigned());
1646 else if (RHS.isSigned() && RHS.isNegative()) {
1647 // During constant-folding, a negative shift is an opposite shift. Such
1648 // a shift is not a constant expression.
1649 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1650 RHS = -RHS;
1651 goto shift_right;
1652 }
1653 shift_left:
1654 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1655 // the shifted type.
1656 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1657 if (SA != RHS) {
1658 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1659 << RHS << E->getType() << LHS.getBitWidth();
1660 } else if (LHS.isSigned()) {
1661 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1662 // operand, and must not overflow the corresponding unsigned type.
1663 if (LHS.isNegative())
1664 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1665 else if (LHS.countLeadingZeros() < SA)
1666 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1667 }
1668 Result = LHS << SA;
1669 return true;
1670 }
1671 case BO_Shr: {
1672 if (Info.getLangOpts().OpenCL)
1673 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1674 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1675 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1676 RHS.isUnsigned());
1677 else if (RHS.isSigned() && RHS.isNegative()) {
1678 // During constant-folding, a negative shift is an opposite shift. Such a
1679 // shift is not a constant expression.
1680 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1681 RHS = -RHS;
1682 goto shift_left;
1683 }
1684 shift_right:
1685 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1686 // shifted type.
1687 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1688 if (SA != RHS)
1689 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1690 << RHS << E->getType() << LHS.getBitWidth();
1691 Result = LHS >> SA;
1692 return true;
1693 }
1694
1695 case BO_LT: Result = LHS < RHS; return true;
1696 case BO_GT: Result = LHS > RHS; return true;
1697 case BO_LE: Result = LHS <= RHS; return true;
1698 case BO_GE: Result = LHS >= RHS; return true;
1699 case BO_EQ: Result = LHS == RHS; return true;
1700 case BO_NE: Result = LHS != RHS; return true;
1701 }
1702}
1703
Richard Smith861b5b52013-05-07 23:34:45 +00001704/// Perform the given binary floating-point operation, in-place, on LHS.
1705static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1706 APFloat &LHS, BinaryOperatorKind Opcode,
1707 const APFloat &RHS) {
1708 switch (Opcode) {
1709 default:
1710 Info.Diag(E);
1711 return false;
1712 case BO_Mul:
1713 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1714 break;
1715 case BO_Add:
1716 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1717 break;
1718 case BO_Sub:
1719 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1720 break;
1721 case BO_Div:
1722 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1723 break;
1724 }
1725
1726 if (LHS.isInfinity() || LHS.isNaN())
1727 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1728 return true;
1729}
1730
Richard Smitha8105bc2012-01-06 16:39:00 +00001731/// Cast an lvalue referring to a base subobject to a derived class, by
1732/// truncating the lvalue's path to the given length.
1733static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1734 const RecordDecl *TruncatedType,
1735 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001736 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001737
1738 // Check we actually point to a derived class object.
1739 if (TruncatedElements == D.Entries.size())
1740 return true;
1741 assert(TruncatedElements >= D.MostDerivedPathLength &&
1742 "not casting to a derived class");
1743 if (!Result.checkSubobject(Info, E, CSK_Derived))
1744 return false;
1745
1746 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001747 const RecordDecl *RD = TruncatedType;
1748 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001749 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001750 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1751 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001752 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001753 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001754 else
Richard Smithd62306a2011-11-10 06:34:14 +00001755 Result.Offset -= Layout.getBaseClassOffset(Base);
1756 RD = Base;
1757 }
Richard Smith027bf112011-11-17 22:56:20 +00001758 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001759 return true;
1760}
1761
John McCalld7bca762012-05-01 00:38:49 +00001762static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001763 const CXXRecordDecl *Derived,
1764 const CXXRecordDecl *Base,
1765 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001766 if (!RL) {
1767 if (Derived->isInvalidDecl()) return false;
1768 RL = &Info.Ctx.getASTRecordLayout(Derived);
1769 }
1770
Richard Smithd62306a2011-11-10 06:34:14 +00001771 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001772 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001773 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001774}
1775
Richard Smitha8105bc2012-01-06 16:39:00 +00001776static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001777 const CXXRecordDecl *DerivedDecl,
1778 const CXXBaseSpecifier *Base) {
1779 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1780
John McCalld7bca762012-05-01 00:38:49 +00001781 if (!Base->isVirtual())
1782 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001783
Richard Smitha8105bc2012-01-06 16:39:00 +00001784 SubobjectDesignator &D = Obj.Designator;
1785 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001786 return false;
1787
Richard Smitha8105bc2012-01-06 16:39:00 +00001788 // Extract most-derived object and corresponding type.
1789 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1790 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1791 return false;
1792
1793 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001794 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001795 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1796 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001797 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001798 return true;
1799}
1800
Richard Smith84401042013-06-03 05:03:02 +00001801static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1802 QualType Type, LValue &Result) {
1803 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1804 PathE = E->path_end();
1805 PathI != PathE; ++PathI) {
1806 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1807 *PathI))
1808 return false;
1809 Type = (*PathI)->getType();
1810 }
1811 return true;
1812}
1813
Richard Smithd62306a2011-11-10 06:34:14 +00001814/// Update LVal to refer to the given field, which must be a member of the type
1815/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001816static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001817 const FieldDecl *FD,
1818 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001819 if (!RL) {
1820 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001821 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001822 }
Richard Smithd62306a2011-11-10 06:34:14 +00001823
1824 unsigned I = FD->getFieldIndex();
1825 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001826 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001827 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001828}
1829
Richard Smith1b78b3d2012-01-25 22:15:11 +00001830/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001831static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001832 LValue &LVal,
1833 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00001834 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00001835 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00001836 return false;
1837 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001838}
1839
Richard Smithd62306a2011-11-10 06:34:14 +00001840/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001841static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1842 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001843 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1844 // extension.
1845 if (Type->isVoidType() || Type->isFunctionType()) {
1846 Size = CharUnits::One();
1847 return true;
1848 }
1849
1850 if (!Type->isConstantSizeType()) {
1851 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001852 // FIXME: Better diagnostic.
1853 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001854 return false;
1855 }
1856
1857 Size = Info.Ctx.getTypeSizeInChars(Type);
1858 return true;
1859}
1860
1861/// Update a pointer value to model pointer arithmetic.
1862/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001863/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001864/// \param LVal - The pointer value to be updated.
1865/// \param EltTy - The pointee type represented by LVal.
1866/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001867static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1868 LValue &LVal, QualType EltTy,
1869 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001870 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001871 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001872 return false;
1873
1874 // Compute the new offset in the appropriate width.
1875 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001876 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001877 return true;
1878}
1879
Richard Smith66c96992012-02-18 22:04:06 +00001880/// Update an lvalue to refer to a component of a complex number.
1881/// \param Info - Information about the ongoing evaluation.
1882/// \param LVal - The lvalue to be updated.
1883/// \param EltTy - The complex number's component type.
1884/// \param Imag - False for the real component, true for the imaginary.
1885static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1886 LValue &LVal, QualType EltTy,
1887 bool Imag) {
1888 if (Imag) {
1889 CharUnits SizeOfComponent;
1890 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1891 return false;
1892 LVal.Offset += SizeOfComponent;
1893 }
1894 LVal.addComplex(Info, E, EltTy, Imag);
1895 return true;
1896}
1897
Richard Smith27908702011-10-24 17:54:18 +00001898/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001899///
1900/// \param Info Information about the ongoing evaluation.
1901/// \param E An expression to be used when printing diagnostics.
1902/// \param VD The variable whose initializer should be obtained.
1903/// \param Frame The frame in which the variable was created. Must be null
1904/// if this variable is not local to the evaluation.
1905/// \param Result Filled in with a pointer to the value of the variable.
1906static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1907 const VarDecl *VD, CallStackFrame *Frame,
1908 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001909 // If this is a parameter to an active constexpr function call, perform
1910 // argument substitution.
1911 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001912 // Assume arguments of a potential constant expression are unknown
1913 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00001914 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00001915 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001916 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001917 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001918 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001919 }
Richard Smith3229b742013-05-05 21:17:10 +00001920 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00001921 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001922 }
Richard Smith27908702011-10-24 17:54:18 +00001923
Richard Smithd9f663b2013-04-22 15:31:51 +00001924 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00001925 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00001926 Result = Frame->getTemporary(VD);
1927 assert(Result && "missing value for local variable");
1928 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001929 }
1930
Richard Smithd0b4dd62011-12-19 06:19:21 +00001931 // Dig out the initializer, and use the declaration which it's attached to.
1932 const Expr *Init = VD->getAnyInitializer(VD);
1933 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001934 // If we're checking a potential constant expression, the variable could be
1935 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00001936 if (!Info.checkingPotentialConstantExpression())
Richard Smithce1ec5e2012-03-15 04:53:45 +00001937 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001938 return false;
1939 }
1940
Richard Smithd62306a2011-11-10 06:34:14 +00001941 // If we're currently evaluating the initializer of this declaration, use that
1942 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00001943 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00001944 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00001945 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001946 }
1947
Richard Smithcecf1842011-11-01 21:06:14 +00001948 // Never evaluate the initializer of a weak variable. We can't be sure that
1949 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001950 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001951 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001952 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001953 }
Richard Smithcecf1842011-11-01 21:06:14 +00001954
Richard Smithd0b4dd62011-12-19 06:19:21 +00001955 // Check that we can fold the initializer. In C++, we will have already done
1956 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001957 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001958 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001959 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001960 Notes.size() + 1) << VD;
1961 Info.Note(VD->getLocation(), diag::note_declared_at);
1962 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001963 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001964 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001965 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001966 Notes.size() + 1) << VD;
1967 Info.Note(VD->getLocation(), diag::note_declared_at);
1968 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001969 }
Richard Smith27908702011-10-24 17:54:18 +00001970
Richard Smith3229b742013-05-05 21:17:10 +00001971 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001972 return true;
Richard Smith27908702011-10-24 17:54:18 +00001973}
1974
Richard Smith11562c52011-10-28 17:51:58 +00001975static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001976 Qualifiers Quals = T.getQualifiers();
1977 return Quals.hasConst() && !Quals.hasVolatile();
1978}
1979
Richard Smithe97cbd72011-11-11 04:05:33 +00001980/// Get the base index of the given base class within an APValue representing
1981/// the given derived class.
1982static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1983 const CXXRecordDecl *Base) {
1984 Base = Base->getCanonicalDecl();
1985 unsigned Index = 0;
1986 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1987 E = Derived->bases_end(); I != E; ++I, ++Index) {
1988 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1989 return Index;
1990 }
1991
1992 llvm_unreachable("base class missing from derived class's bases list");
1993}
1994
Richard Smith3da88fa2013-04-26 14:36:30 +00001995/// Extract the value of a character from a string literal.
1996static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1997 uint64_t Index) {
Richard Smith14a94132012-02-17 03:35:37 +00001998 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith3da88fa2013-04-26 14:36:30 +00001999 const StringLiteral *S = cast<StringLiteral>(Lit);
2000 const ConstantArrayType *CAT =
2001 Info.Ctx.getAsConstantArrayType(S->getType());
2002 assert(CAT && "string literal isn't an array");
2003 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002004 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002005
2006 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002007 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002008 if (Index < S->getLength())
2009 Value = S->getCodeUnit(Index);
2010 return Value;
2011}
2012
Richard Smith3da88fa2013-04-26 14:36:30 +00002013// Expand a string literal into an array of characters.
2014static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2015 APValue &Result) {
2016 const StringLiteral *S = cast<StringLiteral>(Lit);
2017 const ConstantArrayType *CAT =
2018 Info.Ctx.getAsConstantArrayType(S->getType());
2019 assert(CAT && "string literal isn't an array");
2020 QualType CharType = CAT->getElementType();
2021 assert(CharType->isIntegerType() && "unexpected character type");
2022
2023 unsigned Elts = CAT->getSize().getZExtValue();
2024 Result = APValue(APValue::UninitArray(),
2025 std::min(S->getLength(), Elts), Elts);
2026 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2027 CharType->isUnsignedIntegerType());
2028 if (Result.hasArrayFiller())
2029 Result.getArrayFiller() = APValue(Value);
2030 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2031 Value = S->getCodeUnit(I);
2032 Result.getArrayInitializedElt(I) = APValue(Value);
2033 }
2034}
2035
2036// Expand an array so that it has more than Index filled elements.
2037static void expandArray(APValue &Array, unsigned Index) {
2038 unsigned Size = Array.getArraySize();
2039 assert(Index < Size);
2040
2041 // Always at least double the number of elements for which we store a value.
2042 unsigned OldElts = Array.getArrayInitializedElts();
2043 unsigned NewElts = std::max(Index+1, OldElts * 2);
2044 NewElts = std::min(Size, std::max(NewElts, 8u));
2045
2046 // Copy the data across.
2047 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2048 for (unsigned I = 0; I != OldElts; ++I)
2049 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2050 for (unsigned I = OldElts; I != NewElts; ++I)
2051 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2052 if (NewValue.hasArrayFiller())
2053 NewValue.getArrayFiller() = Array.getArrayFiller();
2054 Array.swap(NewValue);
2055}
2056
Richard Smith861b5b52013-05-07 23:34:45 +00002057/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002058enum AccessKinds {
2059 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002060 AK_Assign,
2061 AK_Increment,
2062 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002063};
2064
Richard Smith3229b742013-05-05 21:17:10 +00002065/// A handle to a complete object (an object that is not a subobject of
2066/// another object).
2067struct CompleteObject {
2068 /// The value of the complete object.
2069 APValue *Value;
2070 /// The type of the complete object.
2071 QualType Type;
2072
2073 CompleteObject() : Value(0) {}
2074 CompleteObject(APValue *Value, QualType Type)
2075 : Value(Value), Type(Type) {
2076 assert(Value && "missing value for complete object");
2077 }
2078
David Blaikie7d170102013-05-15 07:37:26 +00002079 LLVM_EXPLICIT operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002080};
2081
Richard Smith3da88fa2013-04-26 14:36:30 +00002082/// Find the designated sub-object of an rvalue.
2083template<typename SubobjectHandler>
2084typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002085findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002086 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002087 if (Sub.Invalid)
2088 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002089 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002090 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002091 if (Info.getLangOpts().CPlusPlus11)
2092 Info.Diag(E, diag::note_constexpr_access_past_end)
2093 << handler.AccessKind;
2094 else
2095 Info.Diag(E);
2096 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002097 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002098
Richard Smith3229b742013-05-05 21:17:10 +00002099 APValue *O = Obj.Value;
2100 QualType ObjType = Obj.Type;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002101 const FieldDecl *LastField = 0;
2102
Richard Smithd62306a2011-11-10 06:34:14 +00002103 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002104 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2105 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002106 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00002107 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2108 return handler.failed();
2109 }
2110
Richard Smith49ca8aa2013-08-06 07:09:20 +00002111 if (I == N) {
2112 if (!handler.found(*O, ObjType))
2113 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002114
Richard Smith49ca8aa2013-08-06 07:09:20 +00002115 // If we modified a bit-field, truncate it to the right width.
2116 if (handler.AccessKind != AK_Read &&
2117 LastField && LastField->isBitField() &&
2118 !truncateBitfieldValue(Info, E, *O, LastField))
2119 return false;
2120
2121 return true;
2122 }
2123
2124 LastField = 0;
Richard Smithf3e9e432011-11-07 09:22:26 +00002125 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002126 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002127 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002128 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002129 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002130 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002131 // Note, it should not be possible to form a pointer with a valid
2132 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002133 if (Info.getLangOpts().CPlusPlus11)
2134 Info.Diag(E, diag::note_constexpr_access_past_end)
2135 << handler.AccessKind;
2136 else
2137 Info.Diag(E);
2138 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002139 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002140
2141 ObjType = CAT->getElementType();
2142
Richard Smith14a94132012-02-17 03:35:37 +00002143 // An array object is represented as either an Array APValue or as an
2144 // LValue which refers to a string literal.
2145 if (O->isLValue()) {
2146 assert(I == N - 1 && "extracting subobject of character?");
2147 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002148 if (handler.AccessKind != AK_Read)
2149 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2150 *O);
2151 else
2152 return handler.foundString(*O, ObjType, Index);
2153 }
2154
2155 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002156 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002157 else if (handler.AccessKind != AK_Read) {
2158 expandArray(*O, Index);
2159 O = &O->getArrayInitializedElt(Index);
2160 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002161 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002162 } else if (ObjType->isAnyComplexType()) {
2163 // Next subobject is a complex number.
2164 uint64_t Index = Sub.Entries[I].ArrayIndex;
2165 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002166 if (Info.getLangOpts().CPlusPlus11)
2167 Info.Diag(E, diag::note_constexpr_access_past_end)
2168 << handler.AccessKind;
2169 else
2170 Info.Diag(E);
2171 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002172 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002173
2174 bool WasConstQualified = ObjType.isConstQualified();
2175 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2176 if (WasConstQualified)
2177 ObjType.addConst();
2178
Richard Smith66c96992012-02-18 22:04:06 +00002179 assert(I == N - 1 && "extracting subobject of scalar?");
2180 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002181 return handler.found(Index ? O->getComplexIntImag()
2182 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002183 } else {
2184 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002185 return handler.found(Index ? O->getComplexFloatImag()
2186 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002187 }
Richard Smithd62306a2011-11-10 06:34:14 +00002188 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002189 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002190 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002191 << Field;
2192 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002193 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002194 }
2195
Richard Smithd62306a2011-11-10 06:34:14 +00002196 // Next subobject is a class, struct or union field.
2197 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2198 if (RD->isUnion()) {
2199 const FieldDecl *UnionField = O->getUnionField();
2200 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002201 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002202 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2203 << handler.AccessKind << Field << !UnionField << UnionField;
2204 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002205 }
Richard Smithd62306a2011-11-10 06:34:14 +00002206 O = &O->getUnionValue();
2207 } else
2208 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002209
2210 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002211 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002212 if (WasConstQualified && !Field->isMutable())
2213 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002214
2215 if (ObjType.isVolatileQualified()) {
2216 if (Info.getLangOpts().CPlusPlus) {
2217 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00002218 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2219 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002220 Info.Note(Field->getLocation(), diag::note_declared_at);
2221 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002222 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002223 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002224 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002225 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002226
2227 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002228 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002229 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002230 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2231 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2232 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002233
2234 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002235 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002236 if (WasConstQualified)
2237 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002238 }
2239 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002240}
2241
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002242namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002243struct ExtractSubobjectHandler {
2244 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002245 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002246
2247 static const AccessKinds AccessKind = AK_Read;
2248
2249 typedef bool result_type;
2250 bool failed() { return false; }
2251 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002252 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002253 return true;
2254 }
2255 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002256 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002257 return true;
2258 }
2259 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002260 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002261 return true;
2262 }
2263 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002264 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002265 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2266 return true;
2267 }
2268};
Richard Smith3229b742013-05-05 21:17:10 +00002269} // end anonymous namespace
2270
Richard Smith3da88fa2013-04-26 14:36:30 +00002271const AccessKinds ExtractSubobjectHandler::AccessKind;
2272
2273/// Extract the designated sub-object of an rvalue.
2274static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002275 const CompleteObject &Obj,
2276 const SubobjectDesignator &Sub,
2277 APValue &Result) {
2278 ExtractSubobjectHandler Handler = { Info, Result };
2279 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002280}
2281
Richard Smith3229b742013-05-05 21:17:10 +00002282namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002283struct ModifySubobjectHandler {
2284 EvalInfo &Info;
2285 APValue &NewVal;
2286 const Expr *E;
2287
2288 typedef bool result_type;
2289 static const AccessKinds AccessKind = AK_Assign;
2290
2291 bool checkConst(QualType QT) {
2292 // Assigning to a const object has undefined behavior.
2293 if (QT.isConstQualified()) {
2294 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2295 return false;
2296 }
2297 return true;
2298 }
2299
2300 bool failed() { return false; }
2301 bool found(APValue &Subobj, QualType SubobjType) {
2302 if (!checkConst(SubobjType))
2303 return false;
2304 // We've been given ownership of NewVal, so just swap it in.
2305 Subobj.swap(NewVal);
2306 return true;
2307 }
2308 bool found(APSInt &Value, QualType SubobjType) {
2309 if (!checkConst(SubobjType))
2310 return false;
2311 if (!NewVal.isInt()) {
2312 // Maybe trying to write a cast pointer value into a complex?
2313 Info.Diag(E);
2314 return false;
2315 }
2316 Value = NewVal.getInt();
2317 return true;
2318 }
2319 bool found(APFloat &Value, QualType SubobjType) {
2320 if (!checkConst(SubobjType))
2321 return false;
2322 Value = NewVal.getFloat();
2323 return true;
2324 }
2325 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2326 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2327 }
2328};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002329} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002330
Richard Smith3229b742013-05-05 21:17:10 +00002331const AccessKinds ModifySubobjectHandler::AccessKind;
2332
Richard Smith3da88fa2013-04-26 14:36:30 +00002333/// Update the designated sub-object of an rvalue to the given value.
2334static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002335 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002336 const SubobjectDesignator &Sub,
2337 APValue &NewVal) {
2338 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002339 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002340}
2341
Richard Smith84f6dcf2012-02-02 01:16:57 +00002342/// Find the position where two subobject designators diverge, or equivalently
2343/// the length of the common initial subsequence.
2344static unsigned FindDesignatorMismatch(QualType ObjType,
2345 const SubobjectDesignator &A,
2346 const SubobjectDesignator &B,
2347 bool &WasArrayIndex) {
2348 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2349 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002350 if (!ObjType.isNull() &&
2351 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002352 // Next subobject is an array element.
2353 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2354 WasArrayIndex = true;
2355 return I;
2356 }
Richard Smith66c96992012-02-18 22:04:06 +00002357 if (ObjType->isAnyComplexType())
2358 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2359 else
2360 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002361 } else {
2362 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2363 WasArrayIndex = false;
2364 return I;
2365 }
2366 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2367 // Next subobject is a field.
2368 ObjType = FD->getType();
2369 else
2370 // Next subobject is a base class.
2371 ObjType = QualType();
2372 }
2373 }
2374 WasArrayIndex = false;
2375 return I;
2376}
2377
2378/// Determine whether the given subobject designators refer to elements of the
2379/// same array object.
2380static bool AreElementsOfSameArray(QualType ObjType,
2381 const SubobjectDesignator &A,
2382 const SubobjectDesignator &B) {
2383 if (A.Entries.size() != B.Entries.size())
2384 return false;
2385
2386 bool IsArray = A.MostDerivedArraySize != 0;
2387 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2388 // A is a subobject of the array element.
2389 return false;
2390
2391 // If A (and B) designates an array element, the last entry will be the array
2392 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2393 // of length 1' case, and the entire path must match.
2394 bool WasArrayIndex;
2395 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2396 return CommonLength >= A.Entries.size() - IsArray;
2397}
2398
Richard Smith3229b742013-05-05 21:17:10 +00002399/// Find the complete object to which an LValue refers.
2400CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
2401 const LValue &LVal, QualType LValType) {
2402 if (!LVal.Base) {
2403 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2404 return CompleteObject();
2405 }
2406
2407 CallStackFrame *Frame = 0;
2408 if (LVal.CallIndex) {
2409 Frame = Info.getCallFrame(LVal.CallIndex);
2410 if (!Frame) {
2411 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2412 << AK << LVal.Base.is<const ValueDecl*>();
2413 NoteLValueLocation(Info, LVal.Base);
2414 return CompleteObject();
2415 }
Richard Smith3229b742013-05-05 21:17:10 +00002416 }
2417
2418 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2419 // is not a constant expression (even if the object is non-volatile). We also
2420 // apply this rule to C++98, in order to conform to the expected 'volatile'
2421 // semantics.
2422 if (LValType.isVolatileQualified()) {
2423 if (Info.getLangOpts().CPlusPlus)
2424 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2425 << AK << LValType;
2426 else
2427 Info.Diag(E);
2428 return CompleteObject();
2429 }
2430
2431 // Compute value storage location and type of base object.
2432 APValue *BaseVal = 0;
Richard Smith84401042013-06-03 05:03:02 +00002433 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002434
2435 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2436 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2437 // In C++11, constexpr, non-volatile variables initialized with constant
2438 // expressions are constant expressions too. Inside constexpr functions,
2439 // parameters are constant expressions even if they're non-const.
2440 // In C++1y, objects local to a constant expression (those with a Frame) are
2441 // both readable and writable inside constant expressions.
2442 // In C, such things can also be folded, although they are not ICEs.
2443 const VarDecl *VD = dyn_cast<VarDecl>(D);
2444 if (VD) {
2445 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2446 VD = VDef;
2447 }
2448 if (!VD || VD->isInvalidDecl()) {
2449 Info.Diag(E);
2450 return CompleteObject();
2451 }
2452
2453 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002454 if (BaseType.isVolatileQualified()) {
2455 if (Info.getLangOpts().CPlusPlus) {
2456 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2457 << AK << 1 << VD;
2458 Info.Note(VD->getLocation(), diag::note_declared_at);
2459 } else {
2460 Info.Diag(E);
2461 }
2462 return CompleteObject();
2463 }
2464
2465 // Unless we're looking at a local variable or argument in a constexpr call,
2466 // the variable we're reading must be const.
2467 if (!Frame) {
Richard Smith7525ff62013-05-09 07:14:00 +00002468 if (Info.getLangOpts().CPlusPlus1y &&
2469 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2470 // OK, we can read and modify an object if we're in the process of
2471 // evaluating its initializer, because its lifetime began in this
2472 // evaluation.
2473 } else if (AK != AK_Read) {
2474 // All the remaining cases only permit reading.
2475 Info.Diag(E, diag::note_constexpr_modify_global);
2476 return CompleteObject();
2477 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002478 // OK, we can read this variable.
2479 } else if (BaseType->isIntegralOrEnumerationType()) {
2480 if (!BaseType.isConstQualified()) {
2481 if (Info.getLangOpts().CPlusPlus) {
2482 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2483 Info.Note(VD->getLocation(), diag::note_declared_at);
2484 } else {
2485 Info.Diag(E);
2486 }
2487 return CompleteObject();
2488 }
2489 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2490 // We support folding of const floating-point types, in order to make
2491 // static const data members of such types (supported as an extension)
2492 // more useful.
2493 if (Info.getLangOpts().CPlusPlus11) {
2494 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2495 Info.Note(VD->getLocation(), diag::note_declared_at);
2496 } else {
2497 Info.CCEDiag(E);
2498 }
2499 } else {
2500 // FIXME: Allow folding of values of any literal type in all languages.
2501 if (Info.getLangOpts().CPlusPlus11) {
2502 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2503 Info.Note(VD->getLocation(), diag::note_declared_at);
2504 } else {
2505 Info.Diag(E);
2506 }
2507 return CompleteObject();
2508 }
2509 }
2510
2511 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2512 return CompleteObject();
2513 } else {
2514 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2515
2516 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002517 if (const MaterializeTemporaryExpr *MTE =
2518 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2519 assert(MTE->getStorageDuration() == SD_Static &&
2520 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002521
Richard Smithe6c01442013-06-05 00:46:14 +00002522 // Per C++1y [expr.const]p2:
2523 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2524 // - a [...] glvalue of integral or enumeration type that refers to
2525 // a non-volatile const object [...]
2526 // [...]
2527 // - a [...] glvalue of literal type that refers to a non-volatile
2528 // object whose lifetime began within the evaluation of e.
2529 //
2530 // C++11 misses the 'began within the evaluation of e' check and
2531 // instead allows all temporaries, including things like:
2532 // int &&r = 1;
2533 // int x = ++r;
2534 // constexpr int k = r;
2535 // Therefore we use the C++1y rules in C++11 too.
2536 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2537 const ValueDecl *ED = MTE->getExtendingDecl();
2538 if (!(BaseType.isConstQualified() &&
2539 BaseType->isIntegralOrEnumerationType()) &&
2540 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2541 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2542 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2543 return CompleteObject();
2544 }
2545
2546 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2547 assert(BaseVal && "got reference to unevaluated temporary");
2548 } else {
2549 Info.Diag(E);
2550 return CompleteObject();
2551 }
2552 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002553 BaseVal = Frame->getTemporary(Base);
2554 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002555 }
Richard Smith3229b742013-05-05 21:17:10 +00002556
2557 // Volatile temporary objects cannot be accessed in constant expressions.
2558 if (BaseType.isVolatileQualified()) {
2559 if (Info.getLangOpts().CPlusPlus) {
2560 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2561 << AK << 0;
2562 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2563 } else {
2564 Info.Diag(E);
2565 }
2566 return CompleteObject();
2567 }
2568 }
2569
Richard Smith7525ff62013-05-09 07:14:00 +00002570 // During the construction of an object, it is not yet 'const'.
2571 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2572 // and this doesn't do quite the right thing for const subobjects of the
2573 // object under construction.
2574 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2575 BaseType = Info.Ctx.getCanonicalType(BaseType);
2576 BaseType.removeLocalConst();
2577 }
2578
Richard Smith6d4c6582013-11-05 22:18:15 +00002579 // In C++1y, we can't safely access any mutable state when we might be
2580 // evaluating after an unmodeled side effect or an evaluation failure.
2581 //
2582 // FIXME: Not all local state is mutable. Allow local constant subobjects
2583 // to be read here (but take care with 'mutable' fields).
Richard Smith3229b742013-05-05 21:17:10 +00002584 if (Frame && Info.getLangOpts().CPlusPlus1y &&
Richard Smith6d4c6582013-11-05 22:18:15 +00002585 (Info.EvalStatus.HasSideEffects || Info.keepEvaluatingAfterFailure()))
Richard Smith3229b742013-05-05 21:17:10 +00002586 return CompleteObject();
2587
2588 return CompleteObject(BaseVal, BaseType);
2589}
2590
Richard Smith243ef902013-05-05 23:31:59 +00002591/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2592/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2593/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002594///
2595/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002596/// \param Conv - The expression for which we are performing the conversion.
2597/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002598/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2599/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002600/// \param LVal - The glvalue on which we are attempting to perform this action.
2601/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002602static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002603 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002604 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002605 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002606 return false;
2607
Richard Smith3229b742013-05-05 21:17:10 +00002608 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002609 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith3229b742013-05-05 21:17:10 +00002610 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2611 !Type.isVolatileQualified()) {
2612 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2613 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2614 // initializer until now for such expressions. Such an expression can't be
2615 // an ICE in C, so this only matters for fold.
2616 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2617 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002618 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002619 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002620 }
Richard Smith3229b742013-05-05 21:17:10 +00002621 APValue Lit;
2622 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2623 return false;
2624 CompleteObject LitObj(&Lit, Base->getType());
2625 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2626 } else if (isa<StringLiteral>(Base)) {
2627 // We represent a string literal array as an lvalue pointing at the
2628 // corresponding expression, rather than building an array of chars.
2629 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2630 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2631 CompleteObject StrObj(&Str, Base->getType());
2632 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002633 }
Richard Smith11562c52011-10-28 17:51:58 +00002634 }
2635
Richard Smith3229b742013-05-05 21:17:10 +00002636 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2637 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002638}
2639
2640/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002641static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002642 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002643 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002644 return false;
2645
Richard Smith3229b742013-05-05 21:17:10 +00002646 if (!Info.getLangOpts().CPlusPlus1y) {
2647 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002648 return false;
2649 }
2650
Richard Smith3229b742013-05-05 21:17:10 +00002651 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2652 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002653}
2654
Richard Smith243ef902013-05-05 23:31:59 +00002655static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2656 return T->isSignedIntegerType() &&
2657 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2658}
2659
2660namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002661struct CompoundAssignSubobjectHandler {
2662 EvalInfo &Info;
2663 const Expr *E;
2664 QualType PromotedLHSType;
2665 BinaryOperatorKind Opcode;
2666 const APValue &RHS;
2667
2668 static const AccessKinds AccessKind = AK_Assign;
2669
2670 typedef bool result_type;
2671
2672 bool checkConst(QualType QT) {
2673 // Assigning to a const object has undefined behavior.
2674 if (QT.isConstQualified()) {
2675 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2676 return false;
2677 }
2678 return true;
2679 }
2680
2681 bool failed() { return false; }
2682 bool found(APValue &Subobj, QualType SubobjType) {
2683 switch (Subobj.getKind()) {
2684 case APValue::Int:
2685 return found(Subobj.getInt(), SubobjType);
2686 case APValue::Float:
2687 return found(Subobj.getFloat(), SubobjType);
2688 case APValue::ComplexInt:
2689 case APValue::ComplexFloat:
2690 // FIXME: Implement complex compound assignment.
2691 Info.Diag(E);
2692 return false;
2693 case APValue::LValue:
2694 return foundPointer(Subobj, SubobjType);
2695 default:
2696 // FIXME: can this happen?
2697 Info.Diag(E);
2698 return false;
2699 }
2700 }
2701 bool found(APSInt &Value, QualType SubobjType) {
2702 if (!checkConst(SubobjType))
2703 return false;
2704
2705 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2706 // We don't support compound assignment on integer-cast-to-pointer
2707 // values.
2708 Info.Diag(E);
2709 return false;
2710 }
2711
2712 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2713 SubobjType, Value);
2714 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2715 return false;
2716 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2717 return true;
2718 }
2719 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002720 return checkConst(SubobjType) &&
2721 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2722 Value) &&
2723 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2724 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00002725 }
2726 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2727 if (!checkConst(SubobjType))
2728 return false;
2729
2730 QualType PointeeType;
2731 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2732 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00002733
2734 if (PointeeType.isNull() || !RHS.isInt() ||
2735 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00002736 Info.Diag(E);
2737 return false;
2738 }
2739
Richard Smith861b5b52013-05-07 23:34:45 +00002740 int64_t Offset = getExtValue(RHS.getInt());
2741 if (Opcode == BO_Sub)
2742 Offset = -Offset;
2743
2744 LValue LVal;
2745 LVal.setFrom(Info.Ctx, Subobj);
2746 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2747 return false;
2748 LVal.moveInto(Subobj);
2749 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002750 }
2751 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2752 llvm_unreachable("shouldn't encounter string elements here");
2753 }
2754};
2755} // end anonymous namespace
2756
2757const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2758
2759/// Perform a compound assignment of LVal <op>= RVal.
2760static bool handleCompoundAssignment(
2761 EvalInfo &Info, const Expr *E,
2762 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2763 BinaryOperatorKind Opcode, const APValue &RVal) {
2764 if (LVal.Designator.Invalid)
2765 return false;
2766
2767 if (!Info.getLangOpts().CPlusPlus1y) {
2768 Info.Diag(E);
2769 return false;
2770 }
2771
2772 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2773 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2774 RVal };
2775 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2776}
2777
2778namespace {
Richard Smith243ef902013-05-05 23:31:59 +00002779struct IncDecSubobjectHandler {
2780 EvalInfo &Info;
2781 const Expr *E;
2782 AccessKinds AccessKind;
2783 APValue *Old;
2784
2785 typedef bool result_type;
2786
2787 bool checkConst(QualType QT) {
2788 // Assigning to a const object has undefined behavior.
2789 if (QT.isConstQualified()) {
2790 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2791 return false;
2792 }
2793 return true;
2794 }
2795
2796 bool failed() { return false; }
2797 bool found(APValue &Subobj, QualType SubobjType) {
2798 // Stash the old value. Also clear Old, so we don't clobber it later
2799 // if we're post-incrementing a complex.
2800 if (Old) {
2801 *Old = Subobj;
2802 Old = 0;
2803 }
2804
2805 switch (Subobj.getKind()) {
2806 case APValue::Int:
2807 return found(Subobj.getInt(), SubobjType);
2808 case APValue::Float:
2809 return found(Subobj.getFloat(), SubobjType);
2810 case APValue::ComplexInt:
2811 return found(Subobj.getComplexIntReal(),
2812 SubobjType->castAs<ComplexType>()->getElementType()
2813 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2814 case APValue::ComplexFloat:
2815 return found(Subobj.getComplexFloatReal(),
2816 SubobjType->castAs<ComplexType>()->getElementType()
2817 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2818 case APValue::LValue:
2819 return foundPointer(Subobj, SubobjType);
2820 default:
2821 // FIXME: can this happen?
2822 Info.Diag(E);
2823 return false;
2824 }
2825 }
2826 bool found(APSInt &Value, QualType SubobjType) {
2827 if (!checkConst(SubobjType))
2828 return false;
2829
2830 if (!SubobjType->isIntegerType()) {
2831 // We don't support increment / decrement on integer-cast-to-pointer
2832 // values.
2833 Info.Diag(E);
2834 return false;
2835 }
2836
2837 if (Old) *Old = APValue(Value);
2838
2839 // bool arithmetic promotes to int, and the conversion back to bool
2840 // doesn't reduce mod 2^n, so special-case it.
2841 if (SubobjType->isBooleanType()) {
2842 if (AccessKind == AK_Increment)
2843 Value = 1;
2844 else
2845 Value = !Value;
2846 return true;
2847 }
2848
2849 bool WasNegative = Value.isNegative();
2850 if (AccessKind == AK_Increment) {
2851 ++Value;
2852
2853 if (!WasNegative && Value.isNegative() &&
2854 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2855 APSInt ActualValue(Value, /*IsUnsigned*/true);
2856 HandleOverflow(Info, E, ActualValue, SubobjType);
2857 }
2858 } else {
2859 --Value;
2860
2861 if (WasNegative && !Value.isNegative() &&
2862 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2863 unsigned BitWidth = Value.getBitWidth();
2864 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2865 ActualValue.setBit(BitWidth);
2866 HandleOverflow(Info, E, ActualValue, SubobjType);
2867 }
2868 }
2869 return true;
2870 }
2871 bool found(APFloat &Value, QualType SubobjType) {
2872 if (!checkConst(SubobjType))
2873 return false;
2874
2875 if (Old) *Old = APValue(Value);
2876
2877 APFloat One(Value.getSemantics(), 1);
2878 if (AccessKind == AK_Increment)
2879 Value.add(One, APFloat::rmNearestTiesToEven);
2880 else
2881 Value.subtract(One, APFloat::rmNearestTiesToEven);
2882 return true;
2883 }
2884 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2885 if (!checkConst(SubobjType))
2886 return false;
2887
2888 QualType PointeeType;
2889 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2890 PointeeType = PT->getPointeeType();
2891 else {
2892 Info.Diag(E);
2893 return false;
2894 }
2895
2896 LValue LVal;
2897 LVal.setFrom(Info.Ctx, Subobj);
2898 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2899 AccessKind == AK_Increment ? 1 : -1))
2900 return false;
2901 LVal.moveInto(Subobj);
2902 return true;
2903 }
2904 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2905 llvm_unreachable("shouldn't encounter string elements here");
2906 }
2907};
2908} // end anonymous namespace
2909
2910/// Perform an increment or decrement on LVal.
2911static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
2912 QualType LValType, bool IsIncrement, APValue *Old) {
2913 if (LVal.Designator.Invalid)
2914 return false;
2915
2916 if (!Info.getLangOpts().CPlusPlus1y) {
2917 Info.Diag(E);
2918 return false;
2919 }
2920
2921 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
2922 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
2923 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
2924 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2925}
2926
Richard Smithe97cbd72011-11-11 04:05:33 +00002927/// Build an lvalue for the object argument of a member function call.
2928static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2929 LValue &This) {
2930 if (Object->getType()->isPointerType())
2931 return EvaluatePointer(Object, This, Info);
2932
2933 if (Object->isGLValue())
2934 return EvaluateLValue(Object, This, Info);
2935
Richard Smithd9f663b2013-04-22 15:31:51 +00002936 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00002937 return EvaluateTemporary(Object, This, Info);
2938
2939 return false;
2940}
2941
2942/// HandleMemberPointerAccess - Evaluate a member access operation and build an
2943/// lvalue referring to the result.
2944///
2945/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00002946/// \param LV - An lvalue referring to the base of the member pointer.
2947/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00002948/// \param IncludeMember - Specifies whether the member itself is included in
2949/// the resulting LValue subobject designator. This is not possible when
2950/// creating a bound member function.
2951/// \return The field or method declaration to which the member pointer refers,
2952/// or 0 if evaluation fails.
2953static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00002954 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00002955 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00002956 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00002957 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00002958 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00002959 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Richard Smith027bf112011-11-17 22:56:20 +00002960 return 0;
2961
2962 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2963 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00002964 if (!MemPtr.getDecl()) {
2965 // FIXME: Specific diagnostic.
2966 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002967 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002968 }
Richard Smith253c2a32012-01-27 01:14:48 +00002969
Richard Smith027bf112011-11-17 22:56:20 +00002970 if (MemPtr.isDerivedMember()) {
2971 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00002972 // The end of the derived-to-base path for the base object must match the
2973 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00002974 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00002975 LV.Designator.Entries.size()) {
2976 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002977 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002978 }
Richard Smith027bf112011-11-17 22:56:20 +00002979 unsigned PathLengthToMember =
2980 LV.Designator.Entries.size() - MemPtr.Path.size();
2981 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
2982 const CXXRecordDecl *LVDecl = getAsBaseClass(
2983 LV.Designator.Entries[PathLengthToMember + I]);
2984 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00002985 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
2986 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002987 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002988 }
Richard Smith027bf112011-11-17 22:56:20 +00002989 }
2990
2991 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00002992 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00002993 PathLengthToMember))
2994 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002995 } else if (!MemPtr.Path.empty()) {
2996 // Extend the LValue path with the member pointer's path.
2997 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
2998 MemPtr.Path.size() + IncludeMember);
2999
3000 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003001 if (const PointerType *PT = LVType->getAs<PointerType>())
3002 LVType = PT->getPointeeType();
3003 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3004 assert(RD && "member pointer access on non-class-type expression");
3005 // The first class in the path is that of the lvalue.
3006 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3007 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003008 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
John McCalld7bca762012-05-01 00:38:49 +00003009 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00003010 RD = Base;
3011 }
3012 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003013 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3014 MemPtr.getContainingRecord()))
John McCalld7bca762012-05-01 00:38:49 +00003015 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00003016 }
3017
3018 // Add the member. Note that we cannot build bound member functions here.
3019 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003020 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003021 if (!HandleLValueMember(Info, RHS, LV, FD))
John McCalld7bca762012-05-01 00:38:49 +00003022 return 0;
3023 } else if (const IndirectFieldDecl *IFD =
3024 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003025 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
John McCalld7bca762012-05-01 00:38:49 +00003026 return 0;
3027 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003028 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003029 }
Richard Smith027bf112011-11-17 22:56:20 +00003030 }
3031
3032 return MemPtr.getDecl();
3033}
3034
Richard Smith84401042013-06-03 05:03:02 +00003035static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3036 const BinaryOperator *BO,
3037 LValue &LV,
3038 bool IncludeMember = true) {
3039 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3040
3041 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3042 if (Info.keepEvaluatingAfterFailure()) {
3043 MemberPtr MemPtr;
3044 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3045 }
3046 return 0;
3047 }
3048
3049 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3050 BO->getRHS(), IncludeMember);
3051}
3052
Richard Smith027bf112011-11-17 22:56:20 +00003053/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3054/// the provided lvalue, which currently refers to the base object.
3055static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3056 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003057 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003058 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003059 return false;
3060
Richard Smitha8105bc2012-01-06 16:39:00 +00003061 QualType TargetQT = E->getType();
3062 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3063 TargetQT = PT->getPointeeType();
3064
3065 // Check this cast lands within the final derived-to-base subobject path.
3066 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003067 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003068 << D.MostDerivedType << TargetQT;
3069 return false;
3070 }
3071
Richard Smith027bf112011-11-17 22:56:20 +00003072 // Check the type of the final cast. We don't need to check the path,
3073 // since a cast can only be formed if the path is unique.
3074 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003075 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3076 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003077 if (NewEntriesSize == D.MostDerivedPathLength)
3078 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3079 else
Richard Smith027bf112011-11-17 22:56:20 +00003080 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003081 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003082 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003083 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003084 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003085 }
Richard Smith027bf112011-11-17 22:56:20 +00003086
3087 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003088 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003089}
3090
Mike Stump876387b2009-10-27 22:09:17 +00003091namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003092enum EvalStmtResult {
3093 /// Evaluation failed.
3094 ESR_Failed,
3095 /// Hit a 'return' statement.
3096 ESR_Returned,
3097 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003098 ESR_Succeeded,
3099 /// Hit a 'continue' statement.
3100 ESR_Continue,
3101 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003102 ESR_Break,
3103 /// Still scanning for 'case' or 'default' statement.
3104 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003105};
3106}
3107
Richard Smithd9f663b2013-04-22 15:31:51 +00003108static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3109 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3110 // We don't need to evaluate the initializer for a static local.
3111 if (!VD->hasLocalStorage())
3112 return true;
3113
3114 LValue Result;
3115 Result.set(VD, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003116 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003117
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003118 const Expr *InitE = VD->getInit();
3119 if (!InitE) {
Richard Smith51f03172013-06-20 03:00:05 +00003120 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3121 << false << VD->getType();
3122 Val = APValue();
3123 return false;
3124 }
3125
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003126 if (InitE->isValueDependent())
3127 return false;
3128
3129 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003130 // Wipe out any partially-computed value, to allow tracking that this
3131 // evaluation failed.
3132 Val = APValue();
3133 return false;
3134 }
3135 }
3136
3137 return true;
3138}
3139
Richard Smith4e18ca52013-05-06 05:56:11 +00003140/// Evaluate a condition (either a variable declaration or an expression).
3141static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3142 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003143 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003144 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3145 return false;
3146 return EvaluateAsBooleanCondition(Cond, Result, Info);
3147}
3148
3149static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003150 const Stmt *S, const SwitchCase *SC = 0);
Richard Smith4e18ca52013-05-06 05:56:11 +00003151
3152/// Evaluate the body of a loop, and translate the result as appropriate.
3153static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003154 const Stmt *Body,
3155 const SwitchCase *Case = 0) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003156 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003157 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003158 case ESR_Break:
3159 return ESR_Succeeded;
3160 case ESR_Succeeded:
3161 case ESR_Continue:
3162 return ESR_Continue;
3163 case ESR_Failed:
3164 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003165 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003166 return ESR;
3167 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003168 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003169}
3170
Richard Smith496ddcf2013-05-12 17:32:42 +00003171/// Evaluate a switch statement.
3172static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
3173 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003174 BlockScopeRAII Scope(Info);
3175
Richard Smith496ddcf2013-05-12 17:32:42 +00003176 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003177 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003178 {
3179 FullExpressionRAII Scope(Info);
3180 if (SS->getConditionVariable() &&
3181 !EvaluateDecl(Info, SS->getConditionVariable()))
3182 return ESR_Failed;
3183 if (!EvaluateInteger(SS->getCond(), Value, Info))
3184 return ESR_Failed;
3185 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003186
3187 // Find the switch case corresponding to the value of the condition.
3188 // FIXME: Cache this lookup.
3189 const SwitchCase *Found = 0;
3190 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3191 SC = SC->getNextSwitchCase()) {
3192 if (isa<DefaultStmt>(SC)) {
3193 Found = SC;
3194 continue;
3195 }
3196
3197 const CaseStmt *CS = cast<CaseStmt>(SC);
3198 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3199 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3200 : LHS;
3201 if (LHS <= Value && Value <= RHS) {
3202 Found = SC;
3203 break;
3204 }
3205 }
3206
3207 if (!Found)
3208 return ESR_Succeeded;
3209
3210 // Search the switch body for the switch case and evaluate it from there.
3211 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3212 case ESR_Break:
3213 return ESR_Succeeded;
3214 case ESR_Succeeded:
3215 case ESR_Continue:
3216 case ESR_Failed:
3217 case ESR_Returned:
3218 return ESR;
3219 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003220 // This can only happen if the switch case is nested within a statement
3221 // expression. We have no intention of supporting that.
3222 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3223 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003224 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003225 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003226}
3227
Richard Smith254a73d2011-10-28 22:34:42 +00003228// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00003229static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003230 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003231 if (!Info.nextStep(S))
3232 return ESR_Failed;
3233
Richard Smith496ddcf2013-05-12 17:32:42 +00003234 // If we're hunting down a 'case' or 'default' label, recurse through
3235 // substatements until we hit the label.
3236 if (Case) {
3237 // FIXME: We don't start the lifetime of objects whose initialization we
3238 // jump over. However, such objects must be of class type with a trivial
3239 // default constructor that initialize all subobjects, so must be empty,
3240 // so this almost never matters.
3241 switch (S->getStmtClass()) {
3242 case Stmt::CompoundStmtClass:
3243 // FIXME: Precompute which substatement of a compound statement we
3244 // would jump to, and go straight there rather than performing a
3245 // linear scan each time.
3246 case Stmt::LabelStmtClass:
3247 case Stmt::AttributedStmtClass:
3248 case Stmt::DoStmtClass:
3249 break;
3250
3251 case Stmt::CaseStmtClass:
3252 case Stmt::DefaultStmtClass:
3253 if (Case == S)
3254 Case = 0;
3255 break;
3256
3257 case Stmt::IfStmtClass: {
3258 // FIXME: Precompute which side of an 'if' we would jump to, and go
3259 // straight there rather than scanning both sides.
3260 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003261
3262 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3263 // preceded by our switch label.
3264 BlockScopeRAII Scope(Info);
3265
Richard Smith496ddcf2013-05-12 17:32:42 +00003266 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3267 if (ESR != ESR_CaseNotFound || !IS->getElse())
3268 return ESR;
3269 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3270 }
3271
3272 case Stmt::WhileStmtClass: {
3273 EvalStmtResult ESR =
3274 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3275 if (ESR != ESR_Continue)
3276 return ESR;
3277 break;
3278 }
3279
3280 case Stmt::ForStmtClass: {
3281 const ForStmt *FS = cast<ForStmt>(S);
3282 EvalStmtResult ESR =
3283 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3284 if (ESR != ESR_Continue)
3285 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003286 if (FS->getInc()) {
3287 FullExpressionRAII IncScope(Info);
3288 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3289 return ESR_Failed;
3290 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003291 break;
3292 }
3293
3294 case Stmt::DeclStmtClass:
3295 // FIXME: If the variable has initialization that can't be jumped over,
3296 // bail out of any immediately-surrounding compound-statement too.
3297 default:
3298 return ESR_CaseNotFound;
3299 }
3300 }
3301
Richard Smith254a73d2011-10-28 22:34:42 +00003302 switch (S->getStmtClass()) {
3303 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003304 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003305 // Don't bother evaluating beyond an expression-statement which couldn't
3306 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003307 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003308 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003309 return ESR_Failed;
3310 return ESR_Succeeded;
3311 }
3312
3313 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003314 return ESR_Failed;
3315
3316 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003317 return ESR_Succeeded;
3318
Richard Smithd9f663b2013-04-22 15:31:51 +00003319 case Stmt::DeclStmtClass: {
3320 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003321 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003322 // Each declaration initialization is its own full-expression.
3323 // FIXME: This isn't quite right; if we're performing aggregate
3324 // initialization, each braced subexpression is its own full-expression.
3325 FullExpressionRAII Scope(Info);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003326 if (!EvaluateDecl(Info, DclIt) && !Info.keepEvaluatingAfterFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003327 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003328 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003329 return ESR_Succeeded;
3330 }
3331
Richard Smith357362d2011-12-13 06:39:58 +00003332 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003333 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003334 FullExpressionRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003335 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00003336 return ESR_Failed;
3337 return ESR_Returned;
3338 }
Richard Smith254a73d2011-10-28 22:34:42 +00003339
3340 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003341 BlockScopeRAII Scope(Info);
3342
Richard Smith254a73d2011-10-28 22:34:42 +00003343 const CompoundStmt *CS = cast<CompoundStmt>(S);
3344 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
3345 BE = CS->body_end(); BI != BE; ++BI) {
Richard Smith496ddcf2013-05-12 17:32:42 +00003346 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI, Case);
3347 if (ESR == ESR_Succeeded)
3348 Case = 0;
3349 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003350 return ESR;
3351 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003352 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003353 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003354
3355 case Stmt::IfStmtClass: {
3356 const IfStmt *IS = cast<IfStmt>(S);
3357
3358 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003359 BlockScopeRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003360 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003361 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003362 return ESR_Failed;
3363
3364 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3365 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3366 if (ESR != ESR_Succeeded)
3367 return ESR;
3368 }
3369 return ESR_Succeeded;
3370 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003371
3372 case Stmt::WhileStmtClass: {
3373 const WhileStmt *WS = cast<WhileStmt>(S);
3374 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003375 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003376 bool Continue;
3377 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3378 Continue))
3379 return ESR_Failed;
3380 if (!Continue)
3381 break;
3382
3383 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3384 if (ESR != ESR_Continue)
3385 return ESR;
3386 }
3387 return ESR_Succeeded;
3388 }
3389
3390 case Stmt::DoStmtClass: {
3391 const DoStmt *DS = cast<DoStmt>(S);
3392 bool Continue;
3393 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003394 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003395 if (ESR != ESR_Continue)
3396 return ESR;
Richard Smith496ddcf2013-05-12 17:32:42 +00003397 Case = 0;
Richard Smith4e18ca52013-05-06 05:56:11 +00003398
Richard Smith08d6a2c2013-07-24 07:11:57 +00003399 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003400 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3401 return ESR_Failed;
3402 } while (Continue);
3403 return ESR_Succeeded;
3404 }
3405
3406 case Stmt::ForStmtClass: {
3407 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003408 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003409 if (FS->getInit()) {
3410 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3411 if (ESR != ESR_Succeeded)
3412 return ESR;
3413 }
3414 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003415 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003416 bool Continue = true;
3417 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3418 FS->getCond(), Continue))
3419 return ESR_Failed;
3420 if (!Continue)
3421 break;
3422
3423 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3424 if (ESR != ESR_Continue)
3425 return ESR;
3426
Richard Smith08d6a2c2013-07-24 07:11:57 +00003427 if (FS->getInc()) {
3428 FullExpressionRAII IncScope(Info);
3429 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3430 return ESR_Failed;
3431 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003432 }
3433 return ESR_Succeeded;
3434 }
3435
Richard Smith896e0d72013-05-06 06:51:17 +00003436 case Stmt::CXXForRangeStmtClass: {
3437 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003438 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003439
3440 // Initialize the __range variable.
3441 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3442 if (ESR != ESR_Succeeded)
3443 return ESR;
3444
3445 // Create the __begin and __end iterators.
3446 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3447 if (ESR != ESR_Succeeded)
3448 return ESR;
3449
3450 while (true) {
3451 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003452 {
3453 bool Continue = true;
3454 FullExpressionRAII CondExpr(Info);
3455 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3456 return ESR_Failed;
3457 if (!Continue)
3458 break;
3459 }
Richard Smith896e0d72013-05-06 06:51:17 +00003460
3461 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003462 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003463 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3464 if (ESR != ESR_Succeeded)
3465 return ESR;
3466
3467 // Loop body.
3468 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3469 if (ESR != ESR_Continue)
3470 return ESR;
3471
3472 // Increment: ++__begin
3473 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3474 return ESR_Failed;
3475 }
3476
3477 return ESR_Succeeded;
3478 }
3479
Richard Smith496ddcf2013-05-12 17:32:42 +00003480 case Stmt::SwitchStmtClass:
3481 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3482
Richard Smith4e18ca52013-05-06 05:56:11 +00003483 case Stmt::ContinueStmtClass:
3484 return ESR_Continue;
3485
3486 case Stmt::BreakStmtClass:
3487 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003488
3489 case Stmt::LabelStmtClass:
3490 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3491
3492 case Stmt::AttributedStmtClass:
3493 // As a general principle, C++11 attributes can be ignored without
3494 // any semantic impact.
3495 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3496 Case);
3497
3498 case Stmt::CaseStmtClass:
3499 case Stmt::DefaultStmtClass:
3500 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003501 }
3502}
3503
Richard Smithcc36f692011-12-22 02:22:31 +00003504/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3505/// default constructor. If so, we'll fold it whether or not it's marked as
3506/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3507/// so we need special handling.
3508static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003509 const CXXConstructorDecl *CD,
3510 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003511 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3512 return false;
3513
Richard Smith66e05fe2012-01-18 05:21:49 +00003514 // Value-initialization does not call a trivial default constructor, so such a
3515 // call is a core constant expression whether or not the constructor is
3516 // constexpr.
3517 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003518 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003519 // FIXME: If DiagDecl is an implicitly-declared special member function,
3520 // we should be much more explicit about why it's not constexpr.
3521 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3522 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3523 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003524 } else {
3525 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3526 }
3527 }
3528 return true;
3529}
3530
Richard Smith357362d2011-12-13 06:39:58 +00003531/// CheckConstexprFunction - Check that a function can be called in a constant
3532/// expression.
3533static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3534 const FunctionDecl *Declaration,
3535 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00003536 // Potential constant expressions can contain calls to declared, but not yet
3537 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00003538 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00003539 Declaration->isConstexpr())
3540 return false;
3541
Richard Smith0838f3a2013-05-14 05:18:44 +00003542 // Bail out with no diagnostic if the function declaration itself is invalid.
3543 // We will have produced a relevant diagnostic while parsing it.
3544 if (Declaration->isInvalidDecl())
3545 return false;
3546
Richard Smith357362d2011-12-13 06:39:58 +00003547 // Can we evaluate this function call?
3548 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3549 return true;
3550
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003551 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003552 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003553 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3554 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003555 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3556 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3557 << DiagDecl;
3558 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3559 } else {
3560 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3561 }
3562 return false;
3563}
3564
Richard Smithd62306a2011-11-10 06:34:14 +00003565namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003566typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003567}
3568
3569/// EvaluateArgs - Evaluate the arguments to a function call.
3570static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3571 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003572 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003573 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003574 I != E; ++I) {
3575 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3576 // If we're checking for a potential constant expression, evaluate all
3577 // initializers even if some of them fail.
3578 if (!Info.keepEvaluatingAfterFailure())
3579 return false;
3580 Success = false;
3581 }
3582 }
3583 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003584}
3585
Richard Smith254a73d2011-10-28 22:34:42 +00003586/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003587static bool HandleFunctionCall(SourceLocation CallLoc,
3588 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003589 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00003590 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003591 ArgVector ArgValues(Args.size());
3592 if (!EvaluateArgs(Args, ArgValues, Info))
3593 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003594
Richard Smith253c2a32012-01-27 01:14:48 +00003595 if (!Info.CheckCallLimit(CallLoc))
3596 return false;
3597
3598 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003599
3600 // For a trivial copy or move assignment, perform an APValue copy. This is
3601 // essential for unions, where the operations performed by the assignment
3602 // operator cannot be represented as statements.
3603 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3604 if (MD && MD->isDefaulted() && MD->isTrivial()) {
3605 assert(This &&
3606 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3607 LValue RHS;
3608 RHS.setFrom(Info.Ctx, ArgValues[0]);
3609 APValue RHSValue;
3610 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3611 RHS, RHSValue))
3612 return false;
3613 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3614 RHSValue))
3615 return false;
3616 This->moveInto(Result);
3617 return true;
3618 }
3619
Richard Smithd9f663b2013-04-22 15:31:51 +00003620 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003621 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00003622 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00003623 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003624 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003625 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003626 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003627}
3628
Richard Smithd62306a2011-11-10 06:34:14 +00003629/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003630static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003631 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003632 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003633 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003634 ArgVector ArgValues(Args.size());
3635 if (!EvaluateArgs(Args, ArgValues, Info))
3636 return false;
3637
Richard Smith253c2a32012-01-27 01:14:48 +00003638 if (!Info.CheckCallLimit(CallLoc))
3639 return false;
3640
Richard Smith3607ffe2012-02-13 03:54:03 +00003641 const CXXRecordDecl *RD = Definition->getParent();
3642 if (RD->getNumVBases()) {
3643 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3644 return false;
3645 }
3646
Richard Smith253c2a32012-01-27 01:14:48 +00003647 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003648
3649 // If it's a delegating constructor, just delegate.
3650 if (Definition->isDelegatingConstructor()) {
3651 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00003652 {
3653 FullExpressionRAII InitScope(Info);
3654 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3655 return false;
3656 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003657 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003658 }
3659
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003660 // For a trivial copy or move constructor, perform an APValue copy. This is
3661 // essential for unions, where the operations performed by the constructor
3662 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003663 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00003664 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3665 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003666 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003667 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003668 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003669 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003670 }
3671
3672 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003673 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003674 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00003675 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00003676
John McCalld7bca762012-05-01 00:38:49 +00003677 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003678 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3679
Richard Smith08d6a2c2013-07-24 07:11:57 +00003680 // A scope for temporaries lifetime-extended by reference members.
3681 BlockScopeRAII LifetimeExtendedScope(Info);
3682
Richard Smith253c2a32012-01-27 01:14:48 +00003683 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003684 unsigned BasesSeen = 0;
3685#ifndef NDEBUG
3686 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3687#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00003688 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00003689 LValue Subobject = This;
3690 APValue *Value = &Result;
3691
3692 // Determine the subobject to initialize.
Richard Smith49ca8aa2013-08-06 07:09:20 +00003693 FieldDecl *FD = 0;
Aaron Ballman0ad78302014-03-13 17:34:31 +00003694 if (I->isBaseInitializer()) {
3695 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00003696#ifndef NDEBUG
3697 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003698 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003699 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3700 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3701 "base class initializers not in expected order");
3702 ++BaseIt;
3703#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00003704 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00003705 BaseType->getAsCXXRecordDecl(), &Layout))
3706 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003707 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00003708 } else if ((FD = I->getMember())) {
3709 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00003710 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003711 if (RD->isUnion()) {
3712 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003713 Value = &Result.getUnionValue();
3714 } else {
3715 Value = &Result.getStructField(FD->getFieldIndex());
3716 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00003717 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003718 // Walk the indirect field decl's chain to find the object to initialize,
3719 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00003720 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003721 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00003722 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3723 // Switch the union field if it differs. This happens if we had
3724 // preceding zero-initialization, and we're now initializing a union
3725 // subobject other than the first.
3726 // FIXME: In this case, the values of the other subobjects are
3727 // specified, since zero-initialization sets all padding bits to zero.
3728 if (Value->isUninit() ||
3729 (Value->isUnion() && Value->getUnionField() != FD)) {
3730 if (CD->isUnion())
3731 *Value = APValue(FD);
3732 else
3733 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00003734 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00003735 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00003736 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00003737 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003738 if (CD->isUnion())
3739 Value = &Value->getUnionValue();
3740 else
3741 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00003742 }
Richard Smithd62306a2011-11-10 06:34:14 +00003743 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003744 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00003745 }
Richard Smith253c2a32012-01-27 01:14:48 +00003746
Richard Smith08d6a2c2013-07-24 07:11:57 +00003747 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00003748 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
3749 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00003750 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00003751 // If we're checking for a potential constant expression, evaluate all
3752 // initializers even if some of them fail.
3753 if (!Info.keepEvaluatingAfterFailure())
3754 return false;
3755 Success = false;
3756 }
Richard Smithd62306a2011-11-10 06:34:14 +00003757 }
3758
Richard Smithd9f663b2013-04-22 15:31:51 +00003759 return Success &&
3760 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003761}
3762
Eli Friedman9a156e52008-11-12 09:44:48 +00003763//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00003764// Generic Evaluation
3765//===----------------------------------------------------------------------===//
3766namespace {
3767
Aaron Ballman68af21c2014-01-03 19:26:43 +00003768template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00003769class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00003770 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00003771private:
Aaron Ballman68af21c2014-01-03 19:26:43 +00003772 bool DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003773 return static_cast<Derived*>(this)->Success(V, E);
3774 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003775 bool DerivedZeroInitialization(const Expr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003776 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003777 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003778
Richard Smith17100ba2012-02-16 02:46:34 +00003779 // Check whether a conditional operator with a non-constant condition is a
3780 // potential constant expression. If neither arm is a potential constant
3781 // expression, then the conditional operator is not either.
3782 template<typename ConditionalOperator>
3783 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003784 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00003785
3786 // Speculatively evaluate both arms.
3787 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003788 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00003789 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3790
3791 StmtVisitorTy::Visit(E->getFalseExpr());
3792 if (Diag.empty())
3793 return;
3794
3795 Diag.clear();
3796 StmtVisitorTy::Visit(E->getTrueExpr());
3797 if (Diag.empty())
3798 return;
3799 }
3800
3801 Error(E, diag::note_constexpr_conditional_never_const);
3802 }
3803
3804
3805 template<typename ConditionalOperator>
3806 bool HandleConditionalOperator(const ConditionalOperator *E) {
3807 bool BoolResult;
3808 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003809 if (Info.checkingPotentialConstantExpression())
Richard Smith17100ba2012-02-16 02:46:34 +00003810 CheckPotentialConstantConditional(E);
3811 return false;
3812 }
3813
3814 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3815 return StmtVisitorTy::Visit(EvalExpr);
3816 }
3817
Peter Collingbournee9200682011-05-13 03:29:01 +00003818protected:
3819 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00003820 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00003821 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3822
Richard Smith92b1ce02011-12-12 09:28:41 +00003823 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003824 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003825 }
3826
Aaron Ballman68af21c2014-01-03 19:26:43 +00003827 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003828
3829public:
3830 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3831
3832 EvalInfo &getEvalInfo() { return Info; }
3833
Richard Smithf57d8cb2011-12-09 22:58:01 +00003834 /// Report an evaluation error. This should only be called when an error is
3835 /// first discovered. When propagating an error, just return false.
3836 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003837 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003838 return false;
3839 }
3840 bool Error(const Expr *E) {
3841 return Error(E, diag::note_invalid_subexpr_in_const_expr);
3842 }
3843
Aaron Ballman68af21c2014-01-03 19:26:43 +00003844 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00003845 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00003846 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003847 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003848 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003849 }
3850
Aaron Ballman68af21c2014-01-03 19:26:43 +00003851 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003852 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003853 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003854 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003855 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003856 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003857 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00003858 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003859 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003860 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003861 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00003862 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003863 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00003864 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003865 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00003866 // The initializer may not have been parsed yet, or might be erroneous.
3867 if (!E->getExpr())
3868 return Error(E);
3869 return StmtVisitorTy::Visit(E->getExpr());
3870 }
Richard Smith5894a912011-12-19 22:12:41 +00003871 // We cannot create any objects for which cleanups are required, so there is
3872 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00003873 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00003874 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003875
Aaron Ballman68af21c2014-01-03 19:26:43 +00003876 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00003877 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3878 return static_cast<Derived*>(this)->VisitCastExpr(E);
3879 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003880 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00003881 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3882 return static_cast<Derived*>(this)->VisitCastExpr(E);
3883 }
3884
Aaron Ballman68af21c2014-01-03 19:26:43 +00003885 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003886 switch (E->getOpcode()) {
3887 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003888 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003889
3890 case BO_Comma:
3891 VisitIgnoredValue(E->getLHS());
3892 return StmtVisitorTy::Visit(E->getRHS());
3893
3894 case BO_PtrMemD:
3895 case BO_PtrMemI: {
3896 LValue Obj;
3897 if (!HandleMemberPointerAccess(Info, E, Obj))
3898 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003899 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00003900 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00003901 return false;
3902 return DerivedSuccess(Result, E);
3903 }
3904 }
3905 }
3906
Aaron Ballman68af21c2014-01-03 19:26:43 +00003907 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003908 // Evaluate and cache the common expression. We treat it as a temporary,
3909 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003910 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00003911 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003912 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00003913
Richard Smith17100ba2012-02-16 02:46:34 +00003914 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003915 }
3916
Aaron Ballman68af21c2014-01-03 19:26:43 +00003917 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003918 bool IsBcpCall = false;
3919 // If the condition (ignoring parens) is a __builtin_constant_p call,
3920 // the result is a constant expression if it can be folded without
3921 // side-effects. This is an important GNU extension. See GCC PR38377
3922 // for discussion.
3923 if (const CallExpr *CallCE =
3924 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00003925 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00003926 IsBcpCall = true;
3927
3928 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3929 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00003930 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00003931 return false;
3932
Richard Smith6d4c6582013-11-05 22:18:15 +00003933 FoldConstant Fold(Info, IsBcpCall);
3934 if (!HandleConditionalOperator(E)) {
3935 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003936 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00003937 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00003938
3939 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00003940 }
3941
Aaron Ballman68af21c2014-01-03 19:26:43 +00003942 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003943 if (APValue *Value = Info.CurrentCall->getTemporary(E))
3944 return DerivedSuccess(*Value, E);
3945
3946 const Expr *Source = E->getSourceExpr();
3947 if (!Source)
3948 return Error(E);
3949 if (Source == E) { // sanity checking.
3950 assert(0 && "OpaqueValueExpr recursively refers to itself");
3951 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003952 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003953 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00003954 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003955
Aaron Ballman68af21c2014-01-03 19:26:43 +00003956 bool VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003957 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00003958 QualType CalleeType = Callee->getType();
3959
Richard Smith254a73d2011-10-28 22:34:42 +00003960 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00003961 LValue *This = 0, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003962 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00003963 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00003964
Richard Smithe97cbd72011-11-11 04:05:33 +00003965 // Extract function decl and 'this' pointer from the callee.
3966 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003967 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00003968 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3969 // Explicit bound member calls, such as x.f() or p->g();
3970 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003971 return false;
3972 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00003973 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00003974 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00003975 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
3976 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00003977 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
3978 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00003979 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00003980 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003981 return Error(Callee);
3982
3983 FD = dyn_cast<FunctionDecl>(Member);
3984 if (!FD)
3985 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003986 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003987 LValue Call;
3988 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003989 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00003990
Richard Smitha8105bc2012-01-06 16:39:00 +00003991 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003992 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00003993 FD = dyn_cast_or_null<FunctionDecl>(
3994 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00003995 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003996 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003997
3998 // Overloaded operator calls to member functions are represented as normal
3999 // calls with '*this' as the first argument.
4000 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4001 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004002 // FIXME: When selecting an implicit conversion for an overloaded
4003 // operator delete, we sometimes try to evaluate calls to conversion
4004 // operators without a 'this' parameter!
4005 if (Args.empty())
4006 return Error(E);
4007
Richard Smithe97cbd72011-11-11 04:05:33 +00004008 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4009 return false;
4010 This = &ThisVal;
4011 Args = Args.slice(1);
4012 }
4013
4014 // Don't call function pointers which have been cast to some other type.
4015 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004016 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00004017 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004018 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004019
Richard Smith47b34932012-02-01 02:39:43 +00004020 if (This && !This->checkSubobject(Info, E, CSK_This))
4021 return false;
4022
Richard Smith3607ffe2012-02-13 03:54:03 +00004023 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4024 // calls to such functions in constant expressions.
4025 if (This && !HasQualifier &&
4026 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4027 return Error(E, diag::note_constexpr_virtual_call);
4028
Richard Smith357362d2011-12-13 06:39:58 +00004029 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00004030 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00004031 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00004032
Richard Smith357362d2011-12-13 06:39:58 +00004033 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00004034 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
4035 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004036 return false;
4037
Richard Smithb228a862012-02-15 02:18:13 +00004038 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00004039 }
4040
Aaron Ballman68af21c2014-01-03 19:26:43 +00004041 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004042 return StmtVisitorTy::Visit(E->getInitializer());
4043 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004044 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004045 if (E->getNumInits() == 0)
4046 return DerivedZeroInitialization(E);
4047 if (E->getNumInits() == 1)
4048 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004049 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004050 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004051 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004052 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004053 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004054 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004055 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004056 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004057 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004058 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004059 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004060
Richard Smithd62306a2011-11-10 06:34:14 +00004061 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004062 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004063 assert(!E->isArrow() && "missing call to bound member function?");
4064
Richard Smith2e312c82012-03-03 22:46:17 +00004065 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004066 if (!Evaluate(Val, Info, E->getBase()))
4067 return false;
4068
4069 QualType BaseTy = E->getBase()->getType();
4070
4071 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004072 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004073 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004074 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004075 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4076
Richard Smith3229b742013-05-05 21:17:10 +00004077 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004078 SubobjectDesignator Designator(BaseTy);
4079 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004080
Richard Smith3229b742013-05-05 21:17:10 +00004081 APValue Result;
4082 return extractSubobject(Info, E, Obj, Designator, Result) &&
4083 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004084 }
4085
Aaron Ballman68af21c2014-01-03 19:26:43 +00004086 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004087 switch (E->getCastKind()) {
4088 default:
4089 break;
4090
Richard Smitha23ab512013-05-23 00:30:41 +00004091 case CK_AtomicToNonAtomic: {
4092 APValue AtomicVal;
4093 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4094 return false;
4095 return DerivedSuccess(AtomicVal, E);
4096 }
4097
Richard Smith11562c52011-10-28 17:51:58 +00004098 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004099 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004100 return StmtVisitorTy::Visit(E->getSubExpr());
4101
4102 case CK_LValueToRValue: {
4103 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004104 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4105 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004106 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004107 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004108 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004109 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004110 return false;
4111 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004112 }
4113 }
4114
Richard Smithf57d8cb2011-12-09 22:58:01 +00004115 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004116 }
4117
Aaron Ballman68af21c2014-01-03 19:26:43 +00004118 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004119 return VisitUnaryPostIncDec(UO);
4120 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004121 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004122 return VisitUnaryPostIncDec(UO);
4123 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004124 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004125 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4126 return Error(UO);
4127
4128 LValue LVal;
4129 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4130 return false;
4131 APValue RVal;
4132 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4133 UO->isIncrementOp(), &RVal))
4134 return false;
4135 return DerivedSuccess(RVal, UO);
4136 }
4137
Aaron Ballman68af21c2014-01-03 19:26:43 +00004138 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004139 // We will have checked the full-expressions inside the statement expression
4140 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004141 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004142 return Error(E);
4143
Richard Smith08d6a2c2013-07-24 07:11:57 +00004144 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004145 const CompoundStmt *CS = E->getSubStmt();
4146 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4147 BE = CS->body_end();
4148 /**/; ++BI) {
4149 if (BI + 1 == BE) {
4150 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4151 if (!FinalExpr) {
4152 Info.Diag((*BI)->getLocStart(),
4153 diag::note_constexpr_stmt_expr_unsupported);
4154 return false;
4155 }
4156 return this->Visit(FinalExpr);
4157 }
4158
4159 APValue ReturnValue;
4160 EvalStmtResult ESR = EvaluateStmt(ReturnValue, Info, *BI);
4161 if (ESR != ESR_Succeeded) {
4162 // FIXME: If the statement-expression terminated due to 'return',
4163 // 'break', or 'continue', it would be nice to propagate that to
4164 // the outer statement evaluation rather than bailing out.
4165 if (ESR != ESR_Failed)
4166 Info.Diag((*BI)->getLocStart(),
4167 diag::note_constexpr_stmt_expr_unsupported);
4168 return false;
4169 }
4170 }
4171 }
4172
Richard Smith4a678122011-10-24 18:44:57 +00004173 /// Visit a value which is evaluated, but whose value is ignored.
4174 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004175 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004176 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004177};
4178
4179}
4180
4181//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004182// Common base class for lvalue and temporary evaluation.
4183//===----------------------------------------------------------------------===//
4184namespace {
4185template<class Derived>
4186class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004187 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004188protected:
4189 LValue &Result;
4190 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004191 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004192
4193 bool Success(APValue::LValueBase B) {
4194 Result.set(B);
4195 return true;
4196 }
4197
4198public:
4199 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4200 ExprEvaluatorBaseTy(Info), Result(Result) {}
4201
Richard Smith2e312c82012-03-03 22:46:17 +00004202 bool Success(const APValue &V, const Expr *E) {
4203 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004204 return true;
4205 }
Richard Smith027bf112011-11-17 22:56:20 +00004206
Richard Smith027bf112011-11-17 22:56:20 +00004207 bool VisitMemberExpr(const MemberExpr *E) {
4208 // Handle non-static data members.
4209 QualType BaseTy;
4210 if (E->isArrow()) {
4211 if (!EvaluatePointer(E->getBase(), Result, this->Info))
4212 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00004213 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004214 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004215 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00004216 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
4217 return false;
4218 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004219 } else {
4220 if (!this->Visit(E->getBase()))
4221 return false;
4222 BaseTy = E->getBase()->getType();
4223 }
Richard Smith027bf112011-11-17 22:56:20 +00004224
Richard Smith1b78b3d2012-01-25 22:15:11 +00004225 const ValueDecl *MD = E->getMemberDecl();
4226 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4227 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4228 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4229 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004230 if (!HandleLValueMember(this->Info, E, Result, FD))
4231 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004232 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004233 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4234 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004235 } else
4236 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004237
Richard Smith1b78b3d2012-01-25 22:15:11 +00004238 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004239 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004240 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004241 RefValue))
4242 return false;
4243 return Success(RefValue, E);
4244 }
4245 return true;
4246 }
4247
4248 bool VisitBinaryOperator(const BinaryOperator *E) {
4249 switch (E->getOpcode()) {
4250 default:
4251 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4252
4253 case BO_PtrMemD:
4254 case BO_PtrMemI:
4255 return HandleMemberPointerAccess(this->Info, E, Result);
4256 }
4257 }
4258
4259 bool VisitCastExpr(const CastExpr *E) {
4260 switch (E->getCastKind()) {
4261 default:
4262 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4263
4264 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004265 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004266 if (!this->Visit(E->getSubExpr()))
4267 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004268
4269 // Now figure out the necessary offset to add to the base LV to get from
4270 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004271 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4272 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004273 }
4274 }
4275};
4276}
4277
4278//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004279// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004280//
4281// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4282// function designators (in C), decl references to void objects (in C), and
4283// temporaries (if building with -Wno-address-of-temporary).
4284//
4285// LValue evaluation produces values comprising a base expression of one of the
4286// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004287// - Declarations
4288// * VarDecl
4289// * FunctionDecl
4290// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00004291// * CompoundLiteralExpr in C
4292// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004293// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004294// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004295// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004296// * ObjCEncodeExpr
4297// * AddrLabelExpr
4298// * BlockExpr
4299// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004300// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004301// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004302// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004303// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4304// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004305// * A MaterializeTemporaryExpr that has static storage duration, with no
4306// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004307// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004308//===----------------------------------------------------------------------===//
4309namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004310class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004311 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004312public:
Richard Smith027bf112011-11-17 22:56:20 +00004313 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4314 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004315
Richard Smith11562c52011-10-28 17:51:58 +00004316 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004317 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004318
Peter Collingbournee9200682011-05-13 03:29:01 +00004319 bool VisitDeclRefExpr(const DeclRefExpr *E);
4320 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004321 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004322 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4323 bool VisitMemberExpr(const MemberExpr *E);
4324 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4325 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004326 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004327 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004328 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4329 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004330 bool VisitUnaryReal(const UnaryOperator *E);
4331 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004332 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4333 return VisitUnaryPreIncDec(UO);
4334 }
4335 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4336 return VisitUnaryPreIncDec(UO);
4337 }
Richard Smith3229b742013-05-05 21:17:10 +00004338 bool VisitBinAssign(const BinaryOperator *BO);
4339 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004340
Peter Collingbournee9200682011-05-13 03:29:01 +00004341 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004342 switch (E->getCastKind()) {
4343 default:
Richard Smith027bf112011-11-17 22:56:20 +00004344 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004345
Eli Friedmance3e02a2011-10-11 00:13:24 +00004346 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004347 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004348 if (!Visit(E->getSubExpr()))
4349 return false;
4350 Result.Designator.setInvalid();
4351 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004352
Richard Smith027bf112011-11-17 22:56:20 +00004353 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004354 if (!Visit(E->getSubExpr()))
4355 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004356 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004357 }
4358 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004359};
4360} // end anonymous namespace
4361
Richard Smith11562c52011-10-28 17:51:58 +00004362/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smith9f8400e2013-05-01 19:00:39 +00004363/// expressions which are not glvalues, in two cases:
4364/// * function designators in C, and
4365/// * "extern void" objects
4366static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4367 assert(E->isGLValue() || E->getType()->isFunctionType() ||
4368 E->getType()->isVoidType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004369 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004370}
4371
Peter Collingbournee9200682011-05-13 03:29:01 +00004372bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004373 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
4374 return Success(FD);
4375 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004376 return VisitVarDecl(E, VD);
4377 return Error(E);
4378}
Richard Smith733237d2011-10-24 23:14:33 +00004379
Richard Smith11562c52011-10-28 17:51:58 +00004380bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith3229b742013-05-05 21:17:10 +00004381 CallStackFrame *Frame = 0;
4382 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4383 Frame = Info.CurrentCall;
4384
Richard Smithfec09922011-11-01 16:57:24 +00004385 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004386 if (Frame) {
4387 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004388 return true;
4389 }
Richard Smithce40ad62011-11-12 22:28:03 +00004390 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004391 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004392
Richard Smith3229b742013-05-05 21:17:10 +00004393 APValue *V;
4394 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004395 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004396 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004397 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004398 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4399 return false;
4400 }
Richard Smith3229b742013-05-05 21:17:10 +00004401 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004402}
4403
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004404bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4405 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004406 // Walk through the expression to find the materialized temporary itself.
4407 SmallVector<const Expr *, 2> CommaLHSs;
4408 SmallVector<SubobjectAdjustment, 2> Adjustments;
4409 const Expr *Inner = E->GetTemporaryExpr()->
4410 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004411
Richard Smith84401042013-06-03 05:03:02 +00004412 // If we passed any comma operators, evaluate their LHSs.
4413 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4414 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4415 return false;
4416
Richard Smithe6c01442013-06-05 00:46:14 +00004417 // A materialized temporary with static storage duration can appear within the
4418 // result of a constant expression evaluation, so we need to preserve its
4419 // value for use outside this evaluation.
4420 APValue *Value;
4421 if (E->getStorageDuration() == SD_Static) {
4422 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004423 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004424 Result.set(E);
4425 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004426 Value = &Info.CurrentCall->
4427 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00004428 Result.set(E, Info.CurrentCall->Index);
4429 }
4430
Richard Smithea4ad5d2013-06-06 08:19:16 +00004431 QualType Type = Inner->getType();
4432
Richard Smith84401042013-06-03 05:03:02 +00004433 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004434 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4435 (E->getStorageDuration() == SD_Static &&
4436 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4437 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004438 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004439 }
Richard Smith84401042013-06-03 05:03:02 +00004440
4441 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004442 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4443 --I;
4444 switch (Adjustments[I].Kind) {
4445 case SubobjectAdjustment::DerivedToBaseAdjustment:
4446 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4447 Type, Result))
4448 return false;
4449 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4450 break;
4451
4452 case SubobjectAdjustment::FieldAdjustment:
4453 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4454 return false;
4455 Type = Adjustments[I].Field->getType();
4456 break;
4457
4458 case SubobjectAdjustment::MemberPointerAdjustment:
4459 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4460 Adjustments[I].Ptr.RHS))
4461 return false;
4462 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4463 break;
4464 }
4465 }
4466
4467 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004468}
4469
Peter Collingbournee9200682011-05-13 03:29:01 +00004470bool
4471LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004472 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4473 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4474 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004475 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004476}
4477
Richard Smith6e525142011-12-27 12:18:28 +00004478bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004479 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004480 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004481
4482 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4483 << E->getExprOperand()->getType()
4484 << E->getExprOperand()->getSourceRange();
4485 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004486}
4487
Francois Pichet0066db92012-04-16 04:08:35 +00004488bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4489 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004490}
Francois Pichet0066db92012-04-16 04:08:35 +00004491
Peter Collingbournee9200682011-05-13 03:29:01 +00004492bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004493 // Handle static data members.
4494 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4495 VisitIgnoredValue(E->getBase());
4496 return VisitVarDecl(E, VD);
4497 }
4498
Richard Smith254a73d2011-10-28 22:34:42 +00004499 // Handle static member functions.
4500 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4501 if (MD->isStatic()) {
4502 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004503 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004504 }
4505 }
4506
Richard Smithd62306a2011-11-10 06:34:14 +00004507 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004508 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004509}
4510
Peter Collingbournee9200682011-05-13 03:29:01 +00004511bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004512 // FIXME: Deal with vectors as array subscript bases.
4513 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004514 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004515
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004516 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004517 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004518
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004519 APSInt Index;
4520 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004521 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004522
Richard Smith861b5b52013-05-07 23:34:45 +00004523 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4524 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004525}
Eli Friedman9a156e52008-11-12 09:44:48 +00004526
Peter Collingbournee9200682011-05-13 03:29:01 +00004527bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004528 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004529}
4530
Richard Smith66c96992012-02-18 22:04:06 +00004531bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4532 if (!Visit(E->getSubExpr()))
4533 return false;
4534 // __real is a no-op on scalar lvalues.
4535 if (E->getSubExpr()->getType()->isAnyComplexType())
4536 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4537 return true;
4538}
4539
4540bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4541 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4542 "lvalue __imag__ on scalar?");
4543 if (!Visit(E->getSubExpr()))
4544 return false;
4545 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4546 return true;
4547}
4548
Richard Smith243ef902013-05-05 23:31:59 +00004549bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4550 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004551 return Error(UO);
4552
4553 if (!this->Visit(UO->getSubExpr()))
4554 return false;
4555
Richard Smith243ef902013-05-05 23:31:59 +00004556 return handleIncDec(
4557 this->Info, UO, Result, UO->getSubExpr()->getType(),
4558 UO->isIncrementOp(), 0);
Richard Smith3229b742013-05-05 21:17:10 +00004559}
4560
4561bool LValueExprEvaluator::VisitCompoundAssignOperator(
4562 const CompoundAssignOperator *CAO) {
Richard Smith243ef902013-05-05 23:31:59 +00004563 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004564 return Error(CAO);
4565
Richard Smith3229b742013-05-05 21:17:10 +00004566 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004567
4568 // The overall lvalue result is the result of evaluating the LHS.
4569 if (!this->Visit(CAO->getLHS())) {
4570 if (Info.keepEvaluatingAfterFailure())
4571 Evaluate(RHS, this->Info, CAO->getRHS());
4572 return false;
4573 }
4574
Richard Smith3229b742013-05-05 21:17:10 +00004575 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4576 return false;
4577
Richard Smith43e77732013-05-07 04:50:00 +00004578 return handleCompoundAssignment(
4579 this->Info, CAO,
4580 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4581 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004582}
4583
4584bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Richard Smith243ef902013-05-05 23:31:59 +00004585 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4586 return Error(E);
4587
Richard Smith3229b742013-05-05 21:17:10 +00004588 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004589
4590 if (!this->Visit(E->getLHS())) {
4591 if (Info.keepEvaluatingAfterFailure())
4592 Evaluate(NewVal, this->Info, E->getRHS());
4593 return false;
4594 }
4595
Richard Smith3229b742013-05-05 21:17:10 +00004596 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4597 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004598
4599 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004600 NewVal);
4601}
4602
Eli Friedman9a156e52008-11-12 09:44:48 +00004603//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004604// Pointer Evaluation
4605//===----------------------------------------------------------------------===//
4606
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004607namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004608class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004609 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00004610 LValue &Result;
4611
Peter Collingbournee9200682011-05-13 03:29:01 +00004612 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004613 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004614 return true;
4615 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004616public:
Mike Stump11289f42009-09-09 15:08:12 +00004617
John McCall45d55e42010-05-07 21:00:08 +00004618 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004619 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004620
Richard Smith2e312c82012-03-03 22:46:17 +00004621 bool Success(const APValue &V, const Expr *E) {
4622 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004623 return true;
4624 }
Richard Smithfddd3842011-12-30 21:15:51 +00004625 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00004626 return Success((Expr*)0);
4627 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004628
John McCall45d55e42010-05-07 21:00:08 +00004629 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004630 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004631 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004632 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004633 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004634 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00004635 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004636 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004637 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004638 bool VisitCallExpr(const CallExpr *E);
4639 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004640 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004641 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004642 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004643 }
Richard Smithd62306a2011-11-10 06:34:14 +00004644 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004645 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00004646 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00004647 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004648 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004649 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004650 Result = *Info.CurrentCall->This;
4651 return true;
4652 }
John McCallc07a0c72011-02-17 10:25:35 +00004653
Eli Friedman449fe542009-03-23 04:56:01 +00004654 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004655};
Chris Lattner05706e882008-07-11 18:11:29 +00004656} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004657
John McCall45d55e42010-05-07 21:00:08 +00004658static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004659 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004660 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004661}
4662
John McCall45d55e42010-05-07 21:00:08 +00004663bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004664 if (E->getOpcode() != BO_Add &&
4665 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004666 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004667
Chris Lattner05706e882008-07-11 18:11:29 +00004668 const Expr *PExp = E->getLHS();
4669 const Expr *IExp = E->getRHS();
4670 if (IExp->getType()->isPointerType())
4671 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004672
Richard Smith253c2a32012-01-27 01:14:48 +00004673 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4674 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004675 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004676
John McCall45d55e42010-05-07 21:00:08 +00004677 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004678 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004679 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004680
4681 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004682 if (E->getOpcode() == BO_Sub)
4683 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004684
Ted Kremenek28831752012-08-23 20:46:57 +00004685 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004686 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4687 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004688}
Eli Friedman9a156e52008-11-12 09:44:48 +00004689
John McCall45d55e42010-05-07 21:00:08 +00004690bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4691 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004692}
Mike Stump11289f42009-09-09 15:08:12 +00004693
Peter Collingbournee9200682011-05-13 03:29:01 +00004694bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4695 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004696
Eli Friedman847a2bc2009-12-27 05:43:15 +00004697 switch (E->getCastKind()) {
4698 default:
4699 break;
4700
John McCalle3027922010-08-25 11:45:40 +00004701 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004702 case CK_CPointerToObjCPointerCast:
4703 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004704 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004705 if (!Visit(SubExpr))
4706 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004707 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4708 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4709 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004710 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004711 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004712 if (SubExpr->getType()->isVoidPointerType())
4713 CCEDiag(E, diag::note_constexpr_invalid_cast)
4714 << 3 << SubExpr->getType();
4715 else
4716 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4717 }
Richard Smith96e0c102011-11-04 02:25:55 +00004718 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004719
Anders Carlsson18275092010-10-31 20:41:46 +00004720 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004721 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00004722 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004723 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004724 if (!Result.Base && Result.Offset.isZero())
4725 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00004726
Richard Smithd62306a2011-11-10 06:34:14 +00004727 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00004728 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004729 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4730 castAs<PointerType>()->getPointeeType(),
4731 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00004732
Richard Smith027bf112011-11-17 22:56:20 +00004733 case CK_BaseToDerived:
4734 if (!Visit(E->getSubExpr()))
4735 return false;
4736 if (!Result.Base && Result.Offset.isZero())
4737 return true;
4738 return HandleBaseToDerivedCast(Info, E, Result);
4739
Richard Smith0b0a0b62011-10-29 20:57:55 +00004740 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004741 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004742 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00004743
John McCalle3027922010-08-25 11:45:40 +00004744 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004745 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4746
Richard Smith2e312c82012-03-03 22:46:17 +00004747 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00004748 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00004749 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00004750
John McCall45d55e42010-05-07 21:00:08 +00004751 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004752 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4753 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00004754 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004755 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00004756 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00004757 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004758 return true;
4759 } else {
4760 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00004761 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00004762 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00004763 }
4764 }
John McCalle3027922010-08-25 11:45:40 +00004765 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00004766 if (SubExpr->isGLValue()) {
4767 if (!EvaluateLValue(SubExpr, Result, Info))
4768 return false;
4769 } else {
Richard Smithb228a862012-02-15 02:18:13 +00004770 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004771 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00004772 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00004773 return false;
4774 }
Richard Smith96e0c102011-11-04 02:25:55 +00004775 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00004776 if (const ConstantArrayType *CAT
4777 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4778 Result.addArray(Info, E, CAT);
4779 else
4780 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00004781 return true;
Richard Smithdd785442011-10-31 20:57:44 +00004782
John McCalle3027922010-08-25 11:45:40 +00004783 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00004784 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004785 }
4786
Richard Smith11562c52011-10-28 17:51:58 +00004787 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00004788}
Chris Lattner05706e882008-07-11 18:11:29 +00004789
Peter Collingbournee9200682011-05-13 03:29:01 +00004790bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004791 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00004792 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00004793
Alp Tokera724cff2013-12-28 21:59:02 +00004794 switch (E->getBuiltinCallee()) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00004795 case Builtin::BI__builtin_addressof:
4796 return EvaluateLValue(E->getArg(0), Result, Info);
4797
4798 default:
4799 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4800 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004801}
Chris Lattner05706e882008-07-11 18:11:29 +00004802
4803//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004804// Member Pointer Evaluation
4805//===----------------------------------------------------------------------===//
4806
4807namespace {
4808class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004809 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00004810 MemberPtr &Result;
4811
4812 bool Success(const ValueDecl *D) {
4813 Result = MemberPtr(D);
4814 return true;
4815 }
4816public:
4817
4818 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
4819 : ExprEvaluatorBaseTy(Info), Result(Result) {}
4820
Richard Smith2e312c82012-03-03 22:46:17 +00004821 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004822 Result.setFrom(V);
4823 return true;
4824 }
Richard Smithfddd3842011-12-30 21:15:51 +00004825 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004826 return Success((const ValueDecl*)0);
4827 }
4828
4829 bool VisitCastExpr(const CastExpr *E);
4830 bool VisitUnaryAddrOf(const UnaryOperator *E);
4831};
4832} // end anonymous namespace
4833
4834static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
4835 EvalInfo &Info) {
4836 assert(E->isRValue() && E->getType()->isMemberPointerType());
4837 return MemberPointerExprEvaluator(Info, Result).Visit(E);
4838}
4839
4840bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
4841 switch (E->getCastKind()) {
4842 default:
4843 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4844
4845 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004846 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004847 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004848
4849 case CK_BaseToDerivedMemberPointer: {
4850 if (!Visit(E->getSubExpr()))
4851 return false;
4852 if (E->path_empty())
4853 return true;
4854 // Base-to-derived member pointer casts store the path in derived-to-base
4855 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
4856 // the wrong end of the derived->base arc, so stagger the path by one class.
4857 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
4858 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
4859 PathI != PathE; ++PathI) {
4860 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4861 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
4862 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004863 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004864 }
4865 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
4866 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004867 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004868 return true;
4869 }
4870
4871 case CK_DerivedToBaseMemberPointer:
4872 if (!Visit(E->getSubExpr()))
4873 return false;
4874 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4875 PathE = E->path_end(); PathI != PathE; ++PathI) {
4876 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4877 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4878 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004879 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004880 }
4881 return true;
4882 }
4883}
4884
4885bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4886 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
4887 // member can be formed.
4888 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
4889}
4890
4891//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00004892// Record Evaluation
4893//===----------------------------------------------------------------------===//
4894
4895namespace {
4896 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004897 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00004898 const LValue &This;
4899 APValue &Result;
4900 public:
4901
4902 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
4903 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
4904
Richard Smith2e312c82012-03-03 22:46:17 +00004905 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004906 Result = V;
4907 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00004908 }
Richard Smithfddd3842011-12-30 21:15:51 +00004909 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004910
Richard Smithe97cbd72011-11-11 04:05:33 +00004911 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004912 bool VisitInitListExpr(const InitListExpr *E);
4913 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc1b96d2013-06-12 22:31:48 +00004914 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004915 };
4916}
4917
Richard Smithfddd3842011-12-30 21:15:51 +00004918/// Perform zero-initialization on an object of non-union class type.
4919/// C++11 [dcl.init]p5:
4920/// To zero-initialize an object or reference of type T means:
4921/// [...]
4922/// -- if T is a (possibly cv-qualified) non-union class type,
4923/// each non-static data member and each base-class subobject is
4924/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00004925static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
4926 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00004927 const LValue &This, APValue &Result) {
4928 assert(!RD->isUnion() && "Expected non-union class type");
4929 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
4930 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00004931 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00004932
John McCalld7bca762012-05-01 00:38:49 +00004933 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004934 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4935
4936 if (CD) {
4937 unsigned Index = 0;
4938 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00004939 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00004940 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4941 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004942 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4943 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004944 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00004945 Result.getStructBase(Index)))
4946 return false;
4947 }
4948 }
4949
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004950 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00004951 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004952 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00004953 continue;
4954
4955 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004956 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004957 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004958
David Blaikie2d7c57e2012-04-30 02:36:29 +00004959 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004960 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00004961 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004962 return false;
4963 }
4964
4965 return true;
4966}
4967
4968bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
4969 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004970 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004971 if (RD->isUnion()) {
4972 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4973 // object's first non-static named data member is zero-initialized
4974 RecordDecl::field_iterator I = RD->field_begin();
4975 if (I == RD->field_end()) {
4976 Result = APValue((const FieldDecl*)0);
4977 return true;
4978 }
4979
4980 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004981 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00004982 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00004983 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00004984 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004985 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004986 }
4987
Richard Smith5d108602012-02-17 00:44:16 +00004988 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004989 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00004990 return false;
4991 }
4992
Richard Smitha8105bc2012-01-06 16:39:00 +00004993 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00004994}
4995
Richard Smithe97cbd72011-11-11 04:05:33 +00004996bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
4997 switch (E->getCastKind()) {
4998 default:
4999 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5000
5001 case CK_ConstructorConversion:
5002 return Visit(E->getSubExpr());
5003
5004 case CK_DerivedToBase:
5005 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00005006 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005007 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00005008 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005009 if (!DerivedObject.isStruct())
5010 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00005011
5012 // Derived-to-base rvalue conversion: just slice off the derived part.
5013 APValue *Value = &DerivedObject;
5014 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5015 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5016 PathE = E->path_end(); PathI != PathE; ++PathI) {
5017 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5018 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5019 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5020 RD = Base;
5021 }
5022 Result = *Value;
5023 return true;
5024 }
5025 }
5026}
5027
Richard Smithd62306a2011-11-10 06:34:14 +00005028bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5029 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005030 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005031 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5032
5033 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005034 const FieldDecl *Field = E->getInitializedFieldInUnion();
5035 Result = APValue(Field);
5036 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005037 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005038
5039 // If the initializer list for a union does not contain any elements, the
5040 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005041 // FIXME: The element should be initialized from an initializer list.
5042 // Is this difference ever observable for initializer lists which
5043 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005044 ImplicitValueInitExpr VIE(Field->getType());
5045 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5046
Richard Smithd62306a2011-11-10 06:34:14 +00005047 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005048 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5049 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005050
5051 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5052 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5053 isa<CXXDefaultInitExpr>(InitExpr));
5054
Richard Smithb228a862012-02-15 02:18:13 +00005055 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005056 }
5057
5058 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
5059 "initializer list for class with base classes");
Aaron Ballman62e47c42014-03-10 13:43:55 +00005060 Result = APValue(APValue::UninitStruct(), 0,
5061 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005062 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005063 bool Success = true;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005064 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005065 // Anonymous bit-fields are not considered members of the class for
5066 // purposes of aggregate initialization.
5067 if (Field->isUnnamedBitfield())
5068 continue;
5069
5070 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00005071
Richard Smith253c2a32012-01-27 01:14:48 +00005072 bool HaveInit = ElementNo < E->getNumInits();
5073
5074 // FIXME: Diagnostics here should point to the end of the initializer
5075 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00005076 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005077 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005078 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005079
5080 // Perform an implicit value-initialization for members beyond the end of
5081 // the initializer list.
5082 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00005083 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00005084
Richard Smith852c9db2013-04-20 22:23:05 +00005085 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5086 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5087 isa<CXXDefaultInitExpr>(Init));
5088
Richard Smith49ca8aa2013-08-06 07:09:20 +00005089 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5090 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5091 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005092 FieldVal, Field))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005093 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00005094 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005095 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00005096 }
5097 }
5098
Richard Smith253c2a32012-01-27 01:14:48 +00005099 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005100}
5101
5102bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5103 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00005104 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5105
Richard Smithfddd3842011-12-30 21:15:51 +00005106 bool ZeroInit = E->requiresZeroInitialization();
5107 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005108 // If we've already performed zero-initialization, we're already done.
5109 if (!Result.isUninit())
5110 return true;
5111
Richard Smithda3f4fd2014-03-05 23:32:50 +00005112 // We can get here in two different ways:
5113 // 1) We're performing value-initialization, and should zero-initialize
5114 // the object, or
5115 // 2) We're performing default-initialization of an object with a trivial
5116 // constexpr default constructor, in which case we should start the
5117 // lifetimes of all the base subobjects (there can be no data member
5118 // subobjects in this case) per [basic.life]p1.
5119 // Either way, ZeroInitialization is appropriate.
5120 return ZeroInitialization(E);
Richard Smithcc36f692011-12-22 02:22:31 +00005121 }
5122
Richard Smithd62306a2011-11-10 06:34:14 +00005123 const FunctionDecl *Definition = 0;
5124 FD->getBody(Definition);
5125
Richard Smith357362d2011-12-13 06:39:58 +00005126 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5127 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005128
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005129 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00005130 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00005131 if (const MaterializeTemporaryExpr *ME
5132 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5133 return Visit(ME->GetTemporaryExpr());
5134
Richard Smithfddd3842011-12-30 21:15:51 +00005135 if (ZeroInit && !ZeroInitialization(E))
5136 return false;
5137
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005138 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005139 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005140 cast<CXXConstructorDecl>(Definition), Info,
5141 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00005142}
5143
Richard Smithcc1b96d2013-06-12 22:31:48 +00005144bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5145 const CXXStdInitializerListExpr *E) {
5146 const ConstantArrayType *ArrayType =
5147 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5148
5149 LValue Array;
5150 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5151 return false;
5152
5153 // Get a pointer to the first element of the array.
5154 Array.addArray(Info, E, ArrayType);
5155
5156 // FIXME: Perform the checks on the field types in SemaInit.
5157 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5158 RecordDecl::field_iterator Field = Record->field_begin();
5159 if (Field == Record->field_end())
5160 return Error(E);
5161
5162 // Start pointer.
5163 if (!Field->getType()->isPointerType() ||
5164 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5165 ArrayType->getElementType()))
5166 return Error(E);
5167
5168 // FIXME: What if the initializer_list type has base classes, etc?
5169 Result = APValue(APValue::UninitStruct(), 0, 2);
5170 Array.moveInto(Result.getStructField(0));
5171
5172 if (++Field == Record->field_end())
5173 return Error(E);
5174
5175 if (Field->getType()->isPointerType() &&
5176 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5177 ArrayType->getElementType())) {
5178 // End pointer.
5179 if (!HandleLValueArrayAdjustment(Info, E, Array,
5180 ArrayType->getElementType(),
5181 ArrayType->getSize().getZExtValue()))
5182 return false;
5183 Array.moveInto(Result.getStructField(1));
5184 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5185 // Length.
5186 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5187 else
5188 return Error(E);
5189
5190 if (++Field != Record->field_end())
5191 return Error(E);
5192
5193 return true;
5194}
5195
Richard Smithd62306a2011-11-10 06:34:14 +00005196static bool EvaluateRecord(const Expr *E, const LValue &This,
5197 APValue &Result, EvalInfo &Info) {
5198 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005199 "can't evaluate expression as a record rvalue");
5200 return RecordExprEvaluator(Info, This, Result).Visit(E);
5201}
5202
5203//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005204// Temporary Evaluation
5205//
5206// Temporaries are represented in the AST as rvalues, but generally behave like
5207// lvalues. The full-object of which the temporary is a subobject is implicitly
5208// materialized so that a reference can bind to it.
5209//===----------------------------------------------------------------------===//
5210namespace {
5211class TemporaryExprEvaluator
5212 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5213public:
5214 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5215 LValueExprEvaluatorBaseTy(Info, Result) {}
5216
5217 /// Visit an expression which constructs the value of this temporary.
5218 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005219 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005220 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5221 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005222 }
5223
5224 bool VisitCastExpr(const CastExpr *E) {
5225 switch (E->getCastKind()) {
5226 default:
5227 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5228
5229 case CK_ConstructorConversion:
5230 return VisitConstructExpr(E->getSubExpr());
5231 }
5232 }
5233 bool VisitInitListExpr(const InitListExpr *E) {
5234 return VisitConstructExpr(E);
5235 }
5236 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5237 return VisitConstructExpr(E);
5238 }
5239 bool VisitCallExpr(const CallExpr *E) {
5240 return VisitConstructExpr(E);
5241 }
5242};
5243} // end anonymous namespace
5244
5245/// Evaluate an expression of record type as a temporary.
5246static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005247 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005248 return TemporaryExprEvaluator(Info, Result).Visit(E);
5249}
5250
5251//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005252// Vector Evaluation
5253//===----------------------------------------------------------------------===//
5254
5255namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005256 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005257 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00005258 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005259 public:
Mike Stump11289f42009-09-09 15:08:12 +00005260
Richard Smith2d406342011-10-22 21:10:00 +00005261 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5262 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00005263
Richard Smith2d406342011-10-22 21:10:00 +00005264 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
5265 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5266 // FIXME: remove this APValue copy.
5267 Result = APValue(V.data(), V.size());
5268 return true;
5269 }
Richard Smith2e312c82012-03-03 22:46:17 +00005270 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00005271 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00005272 Result = V;
5273 return true;
5274 }
Richard Smithfddd3842011-12-30 21:15:51 +00005275 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00005276
Richard Smith2d406342011-10-22 21:10:00 +00005277 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00005278 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00005279 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00005280 bool VisitInitListExpr(const InitListExpr *E);
5281 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005282 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00005283 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00005284 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005285 };
5286} // end anonymous namespace
5287
5288static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005289 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00005290 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005291}
5292
Richard Smith2d406342011-10-22 21:10:00 +00005293bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5294 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005295 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005296
Richard Smith161f09a2011-12-06 22:44:34 +00005297 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00005298 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005299
Eli Friedmanc757de22011-03-25 00:43:55 +00005300 switch (E->getCastKind()) {
5301 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00005302 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00005303 if (SETy->isIntegerType()) {
5304 APSInt IntResult;
5305 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005306 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005307 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00005308 } else if (SETy->isRealFloatingType()) {
5309 APFloat F(0.0);
5310 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005311 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005312 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00005313 } else {
Richard Smith2d406342011-10-22 21:10:00 +00005314 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005315 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005316
5317 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00005318 SmallVector<APValue, 4> Elts(NElts, Val);
5319 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00005320 }
Eli Friedman803acb32011-12-22 03:51:45 +00005321 case CK_BitCast: {
5322 // Evaluate the operand into an APInt we can extract from.
5323 llvm::APInt SValInt;
5324 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5325 return false;
5326 // Extract the elements
5327 QualType EltTy = VTy->getElementType();
5328 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5329 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5330 SmallVector<APValue, 4> Elts;
5331 if (EltTy->isRealFloatingType()) {
5332 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00005333 unsigned FloatEltSize = EltSize;
5334 if (&Sem == &APFloat::x87DoubleExtended)
5335 FloatEltSize = 80;
5336 for (unsigned i = 0; i < NElts; i++) {
5337 llvm::APInt Elt;
5338 if (BigEndian)
5339 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5340 else
5341 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00005342 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00005343 }
5344 } else if (EltTy->isIntegerType()) {
5345 for (unsigned i = 0; i < NElts; i++) {
5346 llvm::APInt Elt;
5347 if (BigEndian)
5348 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5349 else
5350 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5351 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5352 }
5353 } else {
5354 return Error(E);
5355 }
5356 return Success(Elts, E);
5357 }
Eli Friedmanc757de22011-03-25 00:43:55 +00005358 default:
Richard Smith11562c52011-10-28 17:51:58 +00005359 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005360 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005361}
5362
Richard Smith2d406342011-10-22 21:10:00 +00005363bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005364VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005365 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005366 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00005367 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005368
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005369 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005370 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005371
Eli Friedmanb9c71292012-01-03 23:24:20 +00005372 // The number of initializers can be less than the number of
5373 // vector elements. For OpenCL, this can be due to nested vector
5374 // initialization. For GCC compatibility, missing trailing elements
5375 // should be initialized with zeroes.
5376 unsigned CountInits = 0, CountElts = 0;
5377 while (CountElts < NumElements) {
5378 // Handle nested vector initialization.
5379 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00005380 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00005381 APValue v;
5382 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5383 return Error(E);
5384 unsigned vlen = v.getVectorLength();
5385 for (unsigned j = 0; j < vlen; j++)
5386 Elements.push_back(v.getVectorElt(j));
5387 CountElts += vlen;
5388 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005389 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005390 if (CountInits < NumInits) {
5391 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005392 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005393 } else // trailing integer zero.
5394 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5395 Elements.push_back(APValue(sInt));
5396 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005397 } else {
5398 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005399 if (CountInits < NumInits) {
5400 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005401 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005402 } else // trailing float zero.
5403 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5404 Elements.push_back(APValue(f));
5405 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00005406 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00005407 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005408 }
Richard Smith2d406342011-10-22 21:10:00 +00005409 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005410}
5411
Richard Smith2d406342011-10-22 21:10:00 +00005412bool
Richard Smithfddd3842011-12-30 21:15:51 +00005413VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005414 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00005415 QualType EltTy = VT->getElementType();
5416 APValue ZeroElement;
5417 if (EltTy->isIntegerType())
5418 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5419 else
5420 ZeroElement =
5421 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5422
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005423 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00005424 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005425}
5426
Richard Smith2d406342011-10-22 21:10:00 +00005427bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00005428 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005429 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005430}
5431
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005432//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00005433// Array Evaluation
5434//===----------------------------------------------------------------------===//
5435
5436namespace {
5437 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005438 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005439 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00005440 APValue &Result;
5441 public:
5442
Richard Smithd62306a2011-11-10 06:34:14 +00005443 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5444 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00005445
5446 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00005447 assert((V.isArray() || V.isLValue()) &&
5448 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00005449 Result = V;
5450 return true;
5451 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005452
Richard Smithfddd3842011-12-30 21:15:51 +00005453 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005454 const ConstantArrayType *CAT =
5455 Info.Ctx.getAsConstantArrayType(E->getType());
5456 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005457 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005458
5459 Result = APValue(APValue::UninitArray(), 0,
5460 CAT->getSize().getZExtValue());
5461 if (!Result.hasArrayFiller()) return true;
5462
Richard Smithfddd3842011-12-30 21:15:51 +00005463 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00005464 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005465 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00005466 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00005467 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00005468 }
5469
Richard Smithf3e9e432011-11-07 09:22:26 +00005470 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00005471 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00005472 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5473 const LValue &Subobject,
5474 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00005475 };
5476} // end anonymous namespace
5477
Richard Smithd62306a2011-11-10 06:34:14 +00005478static bool EvaluateArray(const Expr *E, const LValue &This,
5479 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00005480 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00005481 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005482}
5483
5484bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5485 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5486 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005487 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005488
Richard Smithca2cfbf2011-12-22 01:07:19 +00005489 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5490 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00005491 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00005492 LValue LV;
5493 if (!EvaluateLValue(E->getInit(0), LV, Info))
5494 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005495 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00005496 LV.moveInto(Val);
5497 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00005498 }
5499
Richard Smith253c2a32012-01-27 01:14:48 +00005500 bool Success = true;
5501
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005502 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5503 "zero-initialized array shouldn't have any initialized elts");
5504 APValue Filler;
5505 if (Result.isArray() && Result.hasArrayFiller())
5506 Filler = Result.getArrayFiller();
5507
Richard Smith9543c5e2013-04-22 14:44:29 +00005508 unsigned NumEltsToInit = E->getNumInits();
5509 unsigned NumElts = CAT->getSize().getZExtValue();
5510 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
5511
5512 // If the initializer might depend on the array index, run it for each
5513 // array element. For now, just whitelist non-class value-initialization.
5514 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5515 NumEltsToInit = NumElts;
5516
5517 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005518
5519 // If the array was previously zero-initialized, preserve the
5520 // zero-initialized values.
5521 if (!Filler.isUninit()) {
5522 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5523 Result.getArrayInitializedElt(I) = Filler;
5524 if (Result.hasArrayFiller())
5525 Result.getArrayFiller() = Filler;
5526 }
5527
Richard Smithd62306a2011-11-10 06:34:14 +00005528 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005529 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00005530 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5531 const Expr *Init =
5532 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00005533 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00005534 Info, Subobject, Init) ||
5535 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00005536 CAT->getElementType(), 1)) {
5537 if (!Info.keepEvaluatingAfterFailure())
5538 return false;
5539 Success = false;
5540 }
Richard Smithd62306a2011-11-10 06:34:14 +00005541 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005542
Richard Smith9543c5e2013-04-22 14:44:29 +00005543 if (!Result.hasArrayFiller())
5544 return Success;
5545
5546 // If we get here, we have a trivial filler, which we can just evaluate
5547 // once and splat over the rest of the array elements.
5548 assert(FillerExpr && "no array filler for incomplete init list");
5549 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5550 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00005551}
5552
Richard Smith027bf112011-11-17 22:56:20 +00005553bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005554 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5555}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005556
Richard Smith9543c5e2013-04-22 14:44:29 +00005557bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5558 const LValue &Subobject,
5559 APValue *Value,
5560 QualType Type) {
5561 bool HadZeroInit = !Value->isUninit();
5562
5563 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5564 unsigned N = CAT->getSize().getZExtValue();
5565
5566 // Preserve the array filler if we had prior zero-initialization.
5567 APValue Filler =
5568 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5569 : APValue();
5570
5571 *Value = APValue(APValue::UninitArray(), N, N);
5572
5573 if (HadZeroInit)
5574 for (unsigned I = 0; I != N; ++I)
5575 Value->getArrayInitializedElt(I) = Filler;
5576
5577 // Initialize the elements.
5578 LValue ArrayElt = Subobject;
5579 ArrayElt.addArray(Info, E, CAT);
5580 for (unsigned I = 0; I != N; ++I)
5581 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5582 CAT->getElementType()) ||
5583 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5584 CAT->getElementType(), 1))
5585 return false;
5586
5587 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005588 }
Richard Smith027bf112011-11-17 22:56:20 +00005589
Richard Smith9543c5e2013-04-22 14:44:29 +00005590 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00005591 return Error(E);
5592
Richard Smith027bf112011-11-17 22:56:20 +00005593 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00005594
Richard Smithfddd3842011-12-30 21:15:51 +00005595 bool ZeroInit = E->requiresZeroInitialization();
5596 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005597 if (HadZeroInit)
5598 return true;
5599
Richard Smithda3f4fd2014-03-05 23:32:50 +00005600 // See RecordExprEvaluator::VisitCXXConstructExpr for explanation.
5601 ImplicitValueInitExpr VIE(Type);
5602 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithcc36f692011-12-22 02:22:31 +00005603 }
5604
Richard Smith027bf112011-11-17 22:56:20 +00005605 const FunctionDecl *Definition = 0;
5606 FD->getBody(Definition);
5607
Richard Smith357362d2011-12-13 06:39:58 +00005608 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5609 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005610
Richard Smith9eae7232012-01-12 18:54:33 +00005611 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005612 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005613 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005614 return false;
5615 }
5616
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005617 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005618 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00005619 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005620 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00005621}
5622
Richard Smithf3e9e432011-11-07 09:22:26 +00005623//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005624// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005625//
5626// As a GNU extension, we support casting pointers to sufficiently-wide integer
5627// types and back in constant folding. Integer values are thus represented
5628// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00005629//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005630
5631namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005632class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005633 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00005634 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005635public:
Richard Smith2e312c82012-03-03 22:46:17 +00005636 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005637 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005638
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005639 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005640 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005641 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005642 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005643 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005644 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005645 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005646 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005647 return true;
5648 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005649 bool Success(const llvm::APSInt &SI, const Expr *E) {
5650 return Success(SI, E, Result);
5651 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005652
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005653 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005654 assert(E->getType()->isIntegralOrEnumerationType() &&
5655 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005656 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005657 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005658 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005659 Result.getInt().setIsUnsigned(
5660 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005661 return true;
5662 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005663 bool Success(const llvm::APInt &I, const Expr *E) {
5664 return Success(I, E, Result);
5665 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005666
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005667 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005668 assert(E->getType()->isIntegralOrEnumerationType() &&
5669 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005670 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005671 return true;
5672 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005673 bool Success(uint64_t Value, const Expr *E) {
5674 return Success(Value, E, Result);
5675 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005676
Ken Dyckdbc01912011-03-11 02:13:43 +00005677 bool Success(CharUnits Size, const Expr *E) {
5678 return Success(Size.getQuantity(), E);
5679 }
5680
Richard Smith2e312c82012-03-03 22:46:17 +00005681 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005682 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00005683 Result = V;
5684 return true;
5685 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005686 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00005687 }
Mike Stump11289f42009-09-09 15:08:12 +00005688
Richard Smithfddd3842011-12-30 21:15:51 +00005689 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00005690
Peter Collingbournee9200682011-05-13 03:29:01 +00005691 //===--------------------------------------------------------------------===//
5692 // Visitor Methods
5693 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005694
Chris Lattner7174bf32008-07-12 00:38:25 +00005695 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005696 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005697 }
5698 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005699 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005700 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005701
5702 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5703 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005704 if (CheckReferencedDecl(E, E->getDecl()))
5705 return true;
5706
5707 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005708 }
5709 bool VisitMemberExpr(const MemberExpr *E) {
5710 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00005711 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005712 return true;
5713 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005714
5715 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005716 }
5717
Peter Collingbournee9200682011-05-13 03:29:01 +00005718 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005719 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00005720 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005721 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00005722
Peter Collingbournee9200682011-05-13 03:29:01 +00005723 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005724 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00005725
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005726 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005727 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005728 }
Mike Stump11289f42009-09-09 15:08:12 +00005729
Ted Kremeneke65b0862012-03-06 20:05:56 +00005730 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5731 return Success(E->getValue(), E);
5732 }
5733
Richard Smith4ce706a2011-10-11 21:43:33 +00005734 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00005735 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005736 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005737 }
5738
Douglas Gregor29c42f22012-02-24 07:38:34 +00005739 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5740 return Success(E->getValue(), E);
5741 }
5742
John Wiegley6242b6a2011-04-28 00:16:57 +00005743 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5744 return Success(E->getValue(), E);
5745 }
5746
John Wiegleyf9f65842011-04-25 06:54:41 +00005747 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5748 return Success(E->getValue(), E);
5749 }
5750
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005751 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005752 bool VisitUnaryImag(const UnaryOperator *E);
5753
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005754 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005755 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00005756
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005757private:
Ken Dyck160146e2010-01-27 17:10:57 +00005758 CharUnits GetAlignOfExpr(const Expr *E);
5759 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00005760 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00005761 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005762 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00005763};
Chris Lattner05706e882008-07-11 18:11:29 +00005764} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005765
Richard Smith11562c52011-10-28 17:51:58 +00005766/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
5767/// produce either the integer value or a pointer.
5768///
5769/// GCC has a heinous extension which folds casts between pointer types and
5770/// pointer-sized integral types. We support this by allowing the evaluation of
5771/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
5772/// Some simple arithmetic on such values is supported (they are treated much
5773/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00005774static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00005775 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005776 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005777 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00005778}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005779
Richard Smithf57d8cb2011-12-09 22:58:01 +00005780static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00005781 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005782 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00005783 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005784 if (!Val.isInt()) {
5785 // FIXME: It would be better to produce the diagnostic for casting
5786 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00005787 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005788 return false;
5789 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005790 Result = Val.getInt();
5791 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005792}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005793
Richard Smithf57d8cb2011-12-09 22:58:01 +00005794/// Check whether the given declaration can be directly converted to an integral
5795/// rvalue. If not, no diagnostic is produced; there are other things we can
5796/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005797bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00005798 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005799 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005800 // Check for signedness/width mismatches between E type and ECD value.
5801 bool SameSign = (ECD->getInitVal().isSigned()
5802 == E->getType()->isSignedIntegerOrEnumerationType());
5803 bool SameWidth = (ECD->getInitVal().getBitWidth()
5804 == Info.Ctx.getIntWidth(E->getType()));
5805 if (SameSign && SameWidth)
5806 return Success(ECD->getInitVal(), E);
5807 else {
5808 // Get rid of mismatch (otherwise Success assertions will fail)
5809 // by computing a new value matching the type of E.
5810 llvm::APSInt Val = ECD->getInitVal();
5811 if (!SameSign)
5812 Val.setIsSigned(!ECD->getInitVal().isSigned());
5813 if (!SameWidth)
5814 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
5815 return Success(Val, E);
5816 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005817 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005818 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00005819}
5820
Chris Lattner86ee2862008-10-06 06:40:35 +00005821/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
5822/// as GCC.
5823static int EvaluateBuiltinClassifyType(const CallExpr *E) {
5824 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005825 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00005826 enum gcc_type_class {
5827 no_type_class = -1,
5828 void_type_class, integer_type_class, char_type_class,
5829 enumeral_type_class, boolean_type_class,
5830 pointer_type_class, reference_type_class, offset_type_class,
5831 real_type_class, complex_type_class,
5832 function_type_class, method_type_class,
5833 record_type_class, union_type_class,
5834 array_type_class, string_type_class,
5835 lang_type_class
5836 };
Mike Stump11289f42009-09-09 15:08:12 +00005837
5838 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00005839 // ideal, however it is what gcc does.
5840 if (E->getNumArgs() == 0)
5841 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00005842
Chris Lattner86ee2862008-10-06 06:40:35 +00005843 QualType ArgTy = E->getArg(0)->getType();
5844 if (ArgTy->isVoidType())
5845 return void_type_class;
5846 else if (ArgTy->isEnumeralType())
5847 return enumeral_type_class;
5848 else if (ArgTy->isBooleanType())
5849 return boolean_type_class;
5850 else if (ArgTy->isCharType())
5851 return string_type_class; // gcc doesn't appear to use char_type_class
5852 else if (ArgTy->isIntegerType())
5853 return integer_type_class;
5854 else if (ArgTy->isPointerType())
5855 return pointer_type_class;
5856 else if (ArgTy->isReferenceType())
5857 return reference_type_class;
5858 else if (ArgTy->isRealType())
5859 return real_type_class;
5860 else if (ArgTy->isComplexType())
5861 return complex_type_class;
5862 else if (ArgTy->isFunctionType())
5863 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00005864 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00005865 return record_type_class;
5866 else if (ArgTy->isUnionType())
5867 return union_type_class;
5868 else if (ArgTy->isArrayType())
5869 return array_type_class;
5870 else if (ArgTy->isUnionType())
5871 return union_type_class;
5872 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00005873 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00005874}
5875
Richard Smith5fab0c92011-12-28 19:48:30 +00005876/// EvaluateBuiltinConstantPForLValue - Determine the result of
5877/// __builtin_constant_p when applied to the given lvalue.
5878///
5879/// An lvalue is only "constant" if it is a pointer or reference to the first
5880/// character of a string literal.
5881template<typename LValue>
5882static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00005883 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00005884 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
5885}
5886
5887/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
5888/// GCC as we can manage.
5889static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
5890 QualType ArgType = Arg->getType();
5891
5892 // __builtin_constant_p always has one operand. The rules which gcc follows
5893 // are not precisely documented, but are as follows:
5894 //
5895 // - If the operand is of integral, floating, complex or enumeration type,
5896 // and can be folded to a known value of that type, it returns 1.
5897 // - If the operand and can be folded to a pointer to the first character
5898 // of a string literal (or such a pointer cast to an integral type), it
5899 // returns 1.
5900 //
5901 // Otherwise, it returns 0.
5902 //
5903 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
5904 // its support for this does not currently work.
5905 if (ArgType->isIntegralOrEnumerationType()) {
5906 Expr::EvalResult Result;
5907 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
5908 return false;
5909
5910 APValue &V = Result.Val;
5911 if (V.getKind() == APValue::Int)
5912 return true;
5913
5914 return EvaluateBuiltinConstantPForLValue(V);
5915 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
5916 return Arg->isEvaluatable(Ctx);
5917 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
5918 LValue LV;
5919 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00005920 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00005921 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
5922 : EvaluatePointer(Arg, LV, Info)) &&
5923 !Status.HasSideEffects)
5924 return EvaluateBuiltinConstantPForLValue(LV);
5925 }
5926
5927 // Anything else isn't considered to be sufficiently constant.
5928 return false;
5929}
5930
John McCall95007602010-05-10 23:27:23 +00005931/// Retrieves the "underlying object type" of the given expression,
5932/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00005933QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
5934 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
5935 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00005936 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00005937 } else if (const Expr *E = B.get<const Expr*>()) {
5938 if (isa<CompoundLiteralExpr>(E))
5939 return E->getType();
John McCall95007602010-05-10 23:27:23 +00005940 }
5941
5942 return QualType();
5943}
5944
Peter Collingbournee9200682011-05-13 03:29:01 +00005945bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00005946 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00005947
5948 {
5949 // The operand of __builtin_object_size is never evaluated for side-effects.
5950 // If there are any, but we can determine the pointed-to object anyway, then
5951 // ignore the side-effects.
5952 SpeculativeEvaluationRAII SpeculativeEval(Info);
5953 if (!EvaluatePointer(E->getArg(0), Base, Info))
5954 return false;
5955 }
John McCall95007602010-05-10 23:27:23 +00005956
5957 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00005958 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00005959
Richard Smithce40ad62011-11-12 22:28:03 +00005960 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00005961 if (T.isNull() ||
5962 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00005963 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00005964 T->isVariablyModifiedType() ||
5965 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005966 return Error(E);
John McCall95007602010-05-10 23:27:23 +00005967
5968 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
5969 CharUnits Offset = Base.getLValueOffset();
5970
5971 if (!Offset.isNegative() && Offset <= Size)
5972 Size -= Offset;
5973 else
5974 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00005975 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00005976}
5977
Peter Collingbournee9200682011-05-13 03:29:01 +00005978bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00005979 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005980 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00005981 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005982
5983 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00005984 if (TryEvaluateBuiltinObjectSize(E))
5985 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00005986
Richard Smith0421ce72012-08-07 04:16:51 +00005987 // If evaluating the argument has side-effects, we can't determine the size
5988 // of the object, and so we lower it to unknown now. CodeGen relies on us to
5989 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005990 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00005991 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00005992 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00005993 return Success(0, E);
5994 }
Mike Stump876387b2009-10-27 22:09:17 +00005995
Richard Smith01ade172012-05-23 04:13:20 +00005996 // Expression had no side effects, but we couldn't statically determine the
5997 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005998 switch (Info.EvalMode) {
5999 case EvalInfo::EM_ConstantExpression:
6000 case EvalInfo::EM_PotentialConstantExpression:
6001 case EvalInfo::EM_ConstantFold:
6002 case EvalInfo::EM_EvaluateForOverflow:
6003 case EvalInfo::EM_IgnoreSideEffects:
6004 return Error(E);
6005 case EvalInfo::EM_ConstantExpressionUnevaluated:
6006 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
6007 return Success(-1ULL, E);
6008 }
Mike Stump722cedf2009-10-26 18:35:08 +00006009 }
6010
Benjamin Kramera801f4a2012-10-06 14:42:22 +00006011 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00006012 case Builtin::BI__builtin_bswap32:
6013 case Builtin::BI__builtin_bswap64: {
6014 APSInt Val;
6015 if (!EvaluateInteger(E->getArg(0), Val, Info))
6016 return false;
6017
6018 return Success(Val.byteSwap(), E);
6019 }
6020
Richard Smith8889a3d2013-06-13 06:26:32 +00006021 case Builtin::BI__builtin_classify_type:
6022 return Success(EvaluateBuiltinClassifyType(E), E);
6023
6024 // FIXME: BI__builtin_clrsb
6025 // FIXME: BI__builtin_clrsbl
6026 // FIXME: BI__builtin_clrsbll
6027
Richard Smith80b3c8e2013-06-13 05:04:16 +00006028 case Builtin::BI__builtin_clz:
6029 case Builtin::BI__builtin_clzl:
6030 case Builtin::BI__builtin_clzll: {
6031 APSInt Val;
6032 if (!EvaluateInteger(E->getArg(0), Val, Info))
6033 return false;
6034 if (!Val)
6035 return Error(E);
6036
6037 return Success(Val.countLeadingZeros(), E);
6038 }
6039
Richard Smith8889a3d2013-06-13 06:26:32 +00006040 case Builtin::BI__builtin_constant_p:
6041 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6042
Richard Smith80b3c8e2013-06-13 05:04:16 +00006043 case Builtin::BI__builtin_ctz:
6044 case Builtin::BI__builtin_ctzl:
6045 case Builtin::BI__builtin_ctzll: {
6046 APSInt Val;
6047 if (!EvaluateInteger(E->getArg(0), Val, Info))
6048 return false;
6049 if (!Val)
6050 return Error(E);
6051
6052 return Success(Val.countTrailingZeros(), E);
6053 }
6054
Richard Smith8889a3d2013-06-13 06:26:32 +00006055 case Builtin::BI__builtin_eh_return_data_regno: {
6056 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6057 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6058 return Success(Operand, E);
6059 }
6060
6061 case Builtin::BI__builtin_expect:
6062 return Visit(E->getArg(0));
6063
6064 case Builtin::BI__builtin_ffs:
6065 case Builtin::BI__builtin_ffsl:
6066 case Builtin::BI__builtin_ffsll: {
6067 APSInt Val;
6068 if (!EvaluateInteger(E->getArg(0), Val, Info))
6069 return false;
6070
6071 unsigned N = Val.countTrailingZeros();
6072 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6073 }
6074
6075 case Builtin::BI__builtin_fpclassify: {
6076 APFloat Val(0.0);
6077 if (!EvaluateFloat(E->getArg(5), Val, Info))
6078 return false;
6079 unsigned Arg;
6080 switch (Val.getCategory()) {
6081 case APFloat::fcNaN: Arg = 0; break;
6082 case APFloat::fcInfinity: Arg = 1; break;
6083 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6084 case APFloat::fcZero: Arg = 4; break;
6085 }
6086 return Visit(E->getArg(Arg));
6087 }
6088
6089 case Builtin::BI__builtin_isinf_sign: {
6090 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00006091 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00006092 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6093 }
6094
Richard Smithea3019d2013-10-15 19:07:14 +00006095 case Builtin::BI__builtin_isinf: {
6096 APFloat Val(0.0);
6097 return EvaluateFloat(E->getArg(0), Val, Info) &&
6098 Success(Val.isInfinity() ? 1 : 0, E);
6099 }
6100
6101 case Builtin::BI__builtin_isfinite: {
6102 APFloat Val(0.0);
6103 return EvaluateFloat(E->getArg(0), Val, Info) &&
6104 Success(Val.isFinite() ? 1 : 0, E);
6105 }
6106
6107 case Builtin::BI__builtin_isnan: {
6108 APFloat Val(0.0);
6109 return EvaluateFloat(E->getArg(0), Val, Info) &&
6110 Success(Val.isNaN() ? 1 : 0, E);
6111 }
6112
6113 case Builtin::BI__builtin_isnormal: {
6114 APFloat Val(0.0);
6115 return EvaluateFloat(E->getArg(0), Val, Info) &&
6116 Success(Val.isNormal() ? 1 : 0, E);
6117 }
6118
Richard Smith8889a3d2013-06-13 06:26:32 +00006119 case Builtin::BI__builtin_parity:
6120 case Builtin::BI__builtin_parityl:
6121 case Builtin::BI__builtin_parityll: {
6122 APSInt Val;
6123 if (!EvaluateInteger(E->getArg(0), Val, Info))
6124 return false;
6125
6126 return Success(Val.countPopulation() % 2, E);
6127 }
6128
Richard Smith80b3c8e2013-06-13 05:04:16 +00006129 case Builtin::BI__builtin_popcount:
6130 case Builtin::BI__builtin_popcountl:
6131 case Builtin::BI__builtin_popcountll: {
6132 APSInt Val;
6133 if (!EvaluateInteger(E->getArg(0), Val, Info))
6134 return false;
6135
6136 return Success(Val.countPopulation(), E);
6137 }
6138
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006139 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00006140 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006141 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006142 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00006143 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6144 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00006145 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00006146 // Fall through.
Richard Smithe6c19f22013-11-15 02:10:04 +00006147 case Builtin::BI__builtin_strlen: {
6148 // As an extension, we support __builtin_strlen() as a constant expression,
6149 // and support folding strlen() to a constant.
6150 LValue String;
6151 if (!EvaluatePointer(E->getArg(0), String, Info))
6152 return false;
6153
6154 // Fast path: if it's a string literal, search the string value.
6155 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
6156 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006157 // The string literal may have embedded null characters. Find the first
6158 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00006159 StringRef Str = S->getBytes();
6160 int64_t Off = String.Offset.getQuantity();
6161 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
6162 S->getCharByteWidth() == 1) {
6163 Str = Str.substr(Off);
6164
6165 StringRef::size_type Pos = Str.find(0);
6166 if (Pos != StringRef::npos)
6167 Str = Str.substr(0, Pos);
6168
6169 return Success(Str.size(), E);
6170 }
6171
6172 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006173 }
Richard Smithe6c19f22013-11-15 02:10:04 +00006174
6175 // Slow path: scan the bytes of the string looking for the terminating 0.
6176 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
6177 for (uint64_t Strlen = 0; /**/; ++Strlen) {
6178 APValue Char;
6179 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
6180 !Char.isInt())
6181 return false;
6182 if (!Char.getInt())
6183 return Success(Strlen, E);
6184 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
6185 return false;
6186 }
6187 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006188
Richard Smith01ba47d2012-04-13 00:45:38 +00006189 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00006190 case Builtin::BI__atomic_is_lock_free:
6191 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00006192 APSInt SizeVal;
6193 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6194 return false;
6195
6196 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6197 // of two less than the maximum inline atomic width, we know it is
6198 // lock-free. If the size isn't a power of two, or greater than the
6199 // maximum alignment where we promote atomics, we know it is not lock-free
6200 // (at least not in the sense of atomic_is_lock_free). Otherwise,
6201 // the answer can only be determined at runtime; for example, 16-byte
6202 // atomics have lock-free implementations on some, but not all,
6203 // x86-64 processors.
6204
6205 // Check power-of-two.
6206 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00006207 if (Size.isPowerOfTwo()) {
6208 // Check against inlining width.
6209 unsigned InlineWidthBits =
6210 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6211 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6212 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6213 Size == CharUnits::One() ||
6214 E->getArg(1)->isNullPointerConstant(Info.Ctx,
6215 Expr::NPC_NeverValueDependent))
6216 // OK, we will inline appropriately-aligned operations of this size,
6217 // and _Atomic(T) is appropriately-aligned.
6218 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006219
Richard Smith01ba47d2012-04-13 00:45:38 +00006220 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6221 castAs<PointerType>()->getPointeeType();
6222 if (!PointeeType->isIncompleteType() &&
6223 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6224 // OK, we will inline operations on this object.
6225 return Success(1, E);
6226 }
6227 }
6228 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006229
Richard Smith01ba47d2012-04-13 00:45:38 +00006230 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6231 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006232 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006233 }
Chris Lattner7174bf32008-07-12 00:38:25 +00006234}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006235
Richard Smith8b3497e2011-10-31 01:37:14 +00006236static bool HasSameBase(const LValue &A, const LValue &B) {
6237 if (!A.getLValueBase())
6238 return !B.getLValueBase();
6239 if (!B.getLValueBase())
6240 return false;
6241
Richard Smithce40ad62011-11-12 22:28:03 +00006242 if (A.getLValueBase().getOpaqueValue() !=
6243 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006244 const Decl *ADecl = GetLValueBaseDecl(A);
6245 if (!ADecl)
6246 return false;
6247 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00006248 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00006249 return false;
6250 }
6251
6252 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00006253 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00006254}
6255
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006256namespace {
Richard Smith11562c52011-10-28 17:51:58 +00006257
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006258/// \brief Data recursive integer evaluator of certain binary operators.
6259///
6260/// We use a data recursive algorithm for binary operators so that we are able
6261/// to handle extreme cases of chained binary operators without causing stack
6262/// overflow.
6263class DataRecursiveIntBinOpEvaluator {
6264 struct EvalResult {
6265 APValue Val;
6266 bool Failed;
6267
6268 EvalResult() : Failed(false) { }
6269
6270 void swap(EvalResult &RHS) {
6271 Val.swap(RHS.Val);
6272 Failed = RHS.Failed;
6273 RHS.Failed = false;
6274 }
6275 };
6276
6277 struct Job {
6278 const Expr *E;
6279 EvalResult LHSResult; // meaningful only for binary operator expression.
6280 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
6281
6282 Job() : StoredInfo(0) { }
6283 void startSpeculativeEval(EvalInfo &Info) {
6284 OldEvalStatus = Info.EvalStatus;
6285 Info.EvalStatus.Diag = 0;
6286 StoredInfo = &Info;
6287 }
6288 ~Job() {
6289 if (StoredInfo) {
6290 StoredInfo->EvalStatus = OldEvalStatus;
6291 }
6292 }
6293 private:
6294 EvalInfo *StoredInfo; // non-null if status changed.
6295 Expr::EvalStatus OldEvalStatus;
6296 };
6297
6298 SmallVector<Job, 16> Queue;
6299
6300 IntExprEvaluator &IntEval;
6301 EvalInfo &Info;
6302 APValue &FinalResult;
6303
6304public:
6305 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
6306 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
6307
6308 /// \brief True if \param E is a binary operator that we are going to handle
6309 /// data recursively.
6310 /// We handle binary operators that are comma, logical, or that have operands
6311 /// with integral or enumeration type.
6312 static bool shouldEnqueue(const BinaryOperator *E) {
6313 return E->getOpcode() == BO_Comma ||
6314 E->isLogicalOp() ||
6315 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6316 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00006317 }
6318
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006319 bool Traverse(const BinaryOperator *E) {
6320 enqueue(E);
6321 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00006322 while (!Queue.empty())
6323 process(PrevResult);
6324
6325 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006326
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006327 FinalResult.swap(PrevResult.Val);
6328 return true;
6329 }
6330
6331private:
6332 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6333 return IntEval.Success(Value, E, Result);
6334 }
6335 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6336 return IntEval.Success(Value, E, Result);
6337 }
6338 bool Error(const Expr *E) {
6339 return IntEval.Error(E);
6340 }
6341 bool Error(const Expr *E, diag::kind D) {
6342 return IntEval.Error(E, D);
6343 }
6344
6345 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6346 return Info.CCEDiag(E, D);
6347 }
6348
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006349 // \brief Returns true if visiting the RHS is necessary, false otherwise.
6350 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006351 bool &SuppressRHSDiags);
6352
6353 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6354 const BinaryOperator *E, APValue &Result);
6355
6356 void EvaluateExpr(const Expr *E, EvalResult &Result) {
6357 Result.Failed = !Evaluate(Result.Val, Info, E);
6358 if (Result.Failed)
6359 Result.Val = APValue();
6360 }
6361
Richard Trieuba4d0872012-03-21 23:30:30 +00006362 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006363
6364 void enqueue(const Expr *E) {
6365 E = E->IgnoreParens();
6366 Queue.resize(Queue.size()+1);
6367 Queue.back().E = E;
6368 Queue.back().Kind = Job::AnyExprKind;
6369 }
6370};
6371
6372}
6373
6374bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006375 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006376 bool &SuppressRHSDiags) {
6377 if (E->getOpcode() == BO_Comma) {
6378 // Ignore LHS but note if we could not evaluate it.
6379 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00006380 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006381 return true;
6382 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006383
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006384 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006385 bool LHSAsBool;
6386 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006387 // We were able to evaluate the LHS, see if we can get away with not
6388 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00006389 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
6390 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006391 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006392 }
6393 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006394 LHSResult.Failed = true;
6395
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006396 // Since we weren't able to evaluate the left hand side, it
6397 // must have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00006398 if (!Info.noteSideEffect())
6399 return false;
6400
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006401 // We can't evaluate the LHS; however, sometimes the result
6402 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6403 // Don't ignore RHS and suppress diagnostics from this arm.
6404 SuppressRHSDiags = true;
6405 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006406
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006407 return true;
6408 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006409
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006410 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6411 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00006412
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006413 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006414 return false; // Ignore RHS;
6415
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006416 return true;
6417}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006418
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006419bool DataRecursiveIntBinOpEvaluator::
6420 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6421 const BinaryOperator *E, APValue &Result) {
6422 if (E->getOpcode() == BO_Comma) {
6423 if (RHSResult.Failed)
6424 return false;
6425 Result = RHSResult.Val;
6426 return true;
6427 }
6428
6429 if (E->isLogicalOp()) {
6430 bool lhsResult, rhsResult;
6431 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
6432 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
6433
6434 if (LHSIsOK) {
6435 if (RHSIsOK) {
6436 if (E->getOpcode() == BO_LOr)
6437 return Success(lhsResult || rhsResult, E, Result);
6438 else
6439 return Success(lhsResult && rhsResult, E, Result);
6440 }
6441 } else {
6442 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006443 // We can't evaluate the LHS; however, sometimes the result
6444 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6445 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006446 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006447 }
6448 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006449
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006450 return false;
6451 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006452
6453 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6454 E->getRHS()->getType()->isIntegralOrEnumerationType());
6455
6456 if (LHSResult.Failed || RHSResult.Failed)
6457 return false;
6458
6459 const APValue &LHSVal = LHSResult.Val;
6460 const APValue &RHSVal = RHSResult.Val;
6461
6462 // Handle cases like (unsigned long)&a + 4.
6463 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
6464 Result = LHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00006465 CharUnits AdditionalOffset =
6466 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006467 if (E->getOpcode() == BO_Add)
6468 Result.getLValueOffset() += AdditionalOffset;
6469 else
6470 Result.getLValueOffset() -= AdditionalOffset;
6471 return true;
6472 }
6473
6474 // Handle cases like 4 + (unsigned long)&a
6475 if (E->getOpcode() == BO_Add &&
6476 RHSVal.isLValue() && LHSVal.isInt()) {
6477 Result = RHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00006478 Result.getLValueOffset() +=
6479 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006480 return true;
6481 }
6482
6483 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
6484 // Handle (intptr_t)&&A - (intptr_t)&&B.
6485 if (!LHSVal.getLValueOffset().isZero() ||
6486 !RHSVal.getLValueOffset().isZero())
6487 return false;
6488 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
6489 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
6490 if (!LHSExpr || !RHSExpr)
6491 return false;
6492 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6493 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6494 if (!LHSAddrExpr || !RHSAddrExpr)
6495 return false;
6496 // Make sure both labels come from the same function.
6497 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6498 RHSAddrExpr->getLabel()->getDeclContext())
6499 return false;
6500 Result = APValue(LHSAddrExpr, RHSAddrExpr);
6501 return true;
6502 }
Richard Smith43e77732013-05-07 04:50:00 +00006503
6504 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006505 if (!LHSVal.isInt() || !RHSVal.isInt())
6506 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00006507
6508 // Set up the width and signedness manually, in case it can't be deduced
6509 // from the operation we're performing.
6510 // FIXME: Don't do this in the cases where we can deduce it.
6511 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
6512 E->getType()->isUnsignedIntegerOrEnumerationType());
6513 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
6514 RHSVal.getInt(), Value))
6515 return false;
6516 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006517}
6518
Richard Trieuba4d0872012-03-21 23:30:30 +00006519void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006520 Job &job = Queue.back();
6521
6522 switch (job.Kind) {
6523 case Job::AnyExprKind: {
6524 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
6525 if (shouldEnqueue(Bop)) {
6526 job.Kind = Job::BinOpKind;
6527 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006528 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006529 }
6530 }
6531
6532 EvaluateExpr(job.E, Result);
6533 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006534 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006535 }
6536
6537 case Job::BinOpKind: {
6538 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006539 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006540 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006541 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006542 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006543 }
6544 if (SuppressRHSDiags)
6545 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006546 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006547 job.Kind = Job::BinOpVisitedLHSKind;
6548 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006549 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006550 }
6551
6552 case Job::BinOpVisitedLHSKind: {
6553 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6554 EvalResult RHS;
6555 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00006556 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006557 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006558 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006559 }
6560 }
6561
6562 llvm_unreachable("Invalid Job::Kind!");
6563}
6564
6565bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6566 if (E->isAssignmentOp())
6567 return Error(E);
6568
6569 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
6570 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006571
Anders Carlssonacc79812008-11-16 07:17:21 +00006572 QualType LHSTy = E->getLHS()->getType();
6573 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006574
6575 if (LHSTy->isAnyComplexType()) {
6576 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00006577 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006578
Richard Smith253c2a32012-01-27 01:14:48 +00006579 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
6580 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006581 return false;
6582
Richard Smith253c2a32012-01-27 01:14:48 +00006583 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006584 return false;
6585
6586 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00006587 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006588 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00006589 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006590 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
6591
John McCalle3027922010-08-25 11:45:40 +00006592 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006593 return Success((CR_r == APFloat::cmpEqual &&
6594 CR_i == APFloat::cmpEqual), E);
6595 else {
John McCalle3027922010-08-25 11:45:40 +00006596 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006597 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00006598 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006599 CR_r == APFloat::cmpLessThan ||
6600 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00006601 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006602 CR_i == APFloat::cmpLessThan ||
6603 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006604 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006605 } else {
John McCalle3027922010-08-25 11:45:40 +00006606 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006607 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
6608 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
6609 else {
John McCalle3027922010-08-25 11:45:40 +00006610 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006611 "Invalid compex comparison.");
6612 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
6613 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
6614 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006615 }
6616 }
Mike Stump11289f42009-09-09 15:08:12 +00006617
Anders Carlssonacc79812008-11-16 07:17:21 +00006618 if (LHSTy->isRealFloatingType() &&
6619 RHSTy->isRealFloatingType()) {
6620 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00006621
Richard Smith253c2a32012-01-27 01:14:48 +00006622 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
6623 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00006624 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006625
Richard Smith253c2a32012-01-27 01:14:48 +00006626 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00006627 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006628
Anders Carlssonacc79812008-11-16 07:17:21 +00006629 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00006630
Anders Carlssonacc79812008-11-16 07:17:21 +00006631 switch (E->getOpcode()) {
6632 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006633 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00006634 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006635 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00006636 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006637 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00006638 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006639 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006640 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00006641 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006642 E);
John McCalle3027922010-08-25 11:45:40 +00006643 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006644 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006645 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00006646 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00006647 || CR == APFloat::cmpLessThan
6648 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00006649 }
Anders Carlssonacc79812008-11-16 07:17:21 +00006650 }
Mike Stump11289f42009-09-09 15:08:12 +00006651
Eli Friedmana38da572009-04-28 19:17:36 +00006652 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006653 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00006654 LValue LHSValue, RHSValue;
6655
6656 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6657 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006658 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006659
Richard Smith253c2a32012-01-27 01:14:48 +00006660 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006661 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006662
Richard Smith8b3497e2011-10-31 01:37:14 +00006663 // Reject differing bases from the normal codepath; we special-case
6664 // comparisons to null.
6665 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006666 if (E->getOpcode() == BO_Sub) {
6667 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006668 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6669 return false;
6670 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00006671 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006672 if (!LHSExpr || !RHSExpr)
6673 return false;
6674 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6675 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6676 if (!LHSAddrExpr || !RHSAddrExpr)
6677 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006678 // Make sure both labels come from the same function.
6679 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6680 RHSAddrExpr->getLabel()->getDeclContext())
6681 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006682 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006683 return true;
6684 }
Richard Smith83c68212011-10-31 05:11:32 +00006685 // Inequalities and subtractions between unrelated pointers have
6686 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00006687 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006688 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006689 // A constant address may compare equal to the address of a symbol.
6690 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00006691 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006692 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6693 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006694 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006695 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00006696 // distinct addresses. In clang, the result of such a comparison is
6697 // unspecified, so it is not a constant expression. However, we do know
6698 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00006699 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6700 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006701 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006702 // We can't tell whether weak symbols will end up pointing to the same
6703 // object.
6704 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006705 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006706 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00006707 // (Note that clang defaults to -fmerge-all-constants, which can
6708 // lead to inconsistent results for comparisons involving the address
6709 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00006710 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00006711 }
Eli Friedman64004332009-03-23 04:38:34 +00006712
Richard Smith1b470412012-02-01 08:10:20 +00006713 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
6714 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
6715
Richard Smith84f6dcf2012-02-02 01:16:57 +00006716 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
6717 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
6718
John McCalle3027922010-08-25 11:45:40 +00006719 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00006720 // C++11 [expr.add]p6:
6721 // Unless both pointers point to elements of the same array object, or
6722 // one past the last element of the array object, the behavior is
6723 // undefined.
6724 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6725 !AreElementsOfSameArray(getType(LHSValue.Base),
6726 LHSDesignator, RHSDesignator))
6727 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
6728
Chris Lattner882bdf22010-04-20 17:13:14 +00006729 QualType Type = E->getLHS()->getType();
6730 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006731
Richard Smithd62306a2011-11-10 06:34:14 +00006732 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00006733 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00006734 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006735
Richard Smith84c6b3d2013-09-10 21:34:14 +00006736 // As an extension, a type may have zero size (empty struct or union in
6737 // C, array of zero length). Pointer subtraction in such cases has
6738 // undefined behavior, so is not constant.
6739 if (ElementSize.isZero()) {
6740 Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
6741 << ElementType;
6742 return false;
6743 }
6744
Richard Smith1b470412012-02-01 08:10:20 +00006745 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
6746 // and produce incorrect results when it overflows. Such behavior
6747 // appears to be non-conforming, but is common, so perhaps we should
6748 // assume the standard intended for such cases to be undefined behavior
6749 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00006750
Richard Smith1b470412012-02-01 08:10:20 +00006751 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
6752 // overflow in the final conversion to ptrdiff_t.
6753 APSInt LHS(
6754 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
6755 APSInt RHS(
6756 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
6757 APSInt ElemSize(
6758 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
6759 APSInt TrueResult = (LHS - RHS) / ElemSize;
6760 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
6761
6762 if (Result.extend(65) != TrueResult)
6763 HandleOverflow(Info, E, TrueResult, E->getType());
6764 return Success(Result, E);
6765 }
Richard Smithde21b242012-01-31 06:41:30 +00006766
6767 // C++11 [expr.rel]p3:
6768 // Pointers to void (after pointer conversions) can be compared, with a
6769 // result defined as follows: If both pointers represent the same
6770 // address or are both the null pointer value, the result is true if the
6771 // operator is <= or >= and false otherwise; otherwise the result is
6772 // unspecified.
6773 // We interpret this as applying to pointers to *cv* void.
6774 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00006775 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00006776 CCEDiag(E, diag::note_constexpr_void_comparison);
6777
Richard Smith84f6dcf2012-02-02 01:16:57 +00006778 // C++11 [expr.rel]p2:
6779 // - If two pointers point to non-static data members of the same object,
6780 // or to subobjects or array elements fo such members, recursively, the
6781 // pointer to the later declared member compares greater provided the
6782 // two members have the same access control and provided their class is
6783 // not a union.
6784 // [...]
6785 // - Otherwise pointer comparisons are unspecified.
6786 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6787 E->isRelationalOp()) {
6788 bool WasArrayIndex;
6789 unsigned Mismatch =
6790 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
6791 RHSDesignator, WasArrayIndex);
6792 // At the point where the designators diverge, the comparison has a
6793 // specified value if:
6794 // - we are comparing array indices
6795 // - we are comparing fields of a union, or fields with the same access
6796 // Otherwise, the result is unspecified and thus the comparison is not a
6797 // constant expression.
6798 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
6799 Mismatch < RHSDesignator.Entries.size()) {
6800 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
6801 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
6802 if (!LF && !RF)
6803 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
6804 else if (!LF)
6805 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6806 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
6807 << RF->getParent() << RF;
6808 else if (!RF)
6809 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6810 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
6811 << LF->getParent() << LF;
6812 else if (!LF->getParent()->isUnion() &&
6813 LF->getAccess() != RF->getAccess())
6814 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
6815 << LF << LF->getAccess() << RF << RF->getAccess()
6816 << LF->getParent();
6817 }
6818 }
6819
Eli Friedman6c31cb42012-04-16 04:30:08 +00006820 // The comparison here must be unsigned, and performed with the same
6821 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00006822 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
6823 uint64_t CompareLHS = LHSOffset.getQuantity();
6824 uint64_t CompareRHS = RHSOffset.getQuantity();
6825 assert(PtrSize <= 64 && "Unexpected pointer width");
6826 uint64_t Mask = ~0ULL >> (64 - PtrSize);
6827 CompareLHS &= Mask;
6828 CompareRHS &= Mask;
6829
Eli Friedman2f5b7c52012-04-16 19:23:57 +00006830 // If there is a base and this is a relational operator, we can only
6831 // compare pointers within the object in question; otherwise, the result
6832 // depends on where the object is located in memory.
6833 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
6834 QualType BaseTy = getType(LHSValue.Base);
6835 if (BaseTy->isIncompleteType())
6836 return Error(E);
6837 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
6838 uint64_t OffsetLimit = Size.getQuantity();
6839 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
6840 return Error(E);
6841 }
6842
Richard Smith8b3497e2011-10-31 01:37:14 +00006843 switch (E->getOpcode()) {
6844 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00006845 case BO_LT: return Success(CompareLHS < CompareRHS, E);
6846 case BO_GT: return Success(CompareLHS > CompareRHS, E);
6847 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
6848 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
6849 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
6850 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00006851 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006852 }
6853 }
Richard Smith7bb00672012-02-01 01:42:44 +00006854
6855 if (LHSTy->isMemberPointerType()) {
6856 assert(E->isEqualityOp() && "unexpected member pointer operation");
6857 assert(RHSTy->isMemberPointerType() && "invalid comparison");
6858
6859 MemberPtr LHSValue, RHSValue;
6860
6861 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
6862 if (!LHSOK && Info.keepEvaluatingAfterFailure())
6863 return false;
6864
6865 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6866 return false;
6867
6868 // C++11 [expr.eq]p2:
6869 // If both operands are null, they compare equal. Otherwise if only one is
6870 // null, they compare unequal.
6871 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
6872 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
6873 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6874 }
6875
6876 // Otherwise if either is a pointer to a virtual member function, the
6877 // result is unspecified.
6878 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
6879 if (MD->isVirtual())
6880 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6881 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
6882 if (MD->isVirtual())
6883 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6884
6885 // Otherwise they compare equal if and only if they would refer to the
6886 // same member of the same most derived object or the same subobject if
6887 // they were dereferenced with a hypothetical object of the associated
6888 // class type.
6889 bool Equal = LHSValue == RHSValue;
6890 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6891 }
6892
Richard Smithab44d9b2012-02-14 22:35:28 +00006893 if (LHSTy->isNullPtrType()) {
6894 assert(E->isComparisonOp() && "unexpected nullptr operation");
6895 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
6896 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
6897 // are compared, the result is true of the operator is <=, >= or ==, and
6898 // false otherwise.
6899 BinaryOperator::Opcode Opcode = E->getOpcode();
6900 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
6901 }
6902
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006903 assert((!LHSTy->isIntegralOrEnumerationType() ||
6904 !RHSTy->isIntegralOrEnumerationType()) &&
6905 "DataRecursiveIntBinOpEvaluator should have handled integral types");
6906 // We can't continue from here for non-integral types.
6907 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00006908}
6909
Ken Dyck160146e2010-01-27 17:10:57 +00006910CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00006911 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
6912 // result shall be the alignment of the referenced type."
6913 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6914 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00006915
6916 // __alignof is defined to return the preferred alignment.
6917 return Info.Ctx.toCharUnitsFromBits(
6918 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00006919}
6920
Ken Dyck160146e2010-01-27 17:10:57 +00006921CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00006922 E = E->IgnoreParens();
6923
John McCall768439e2013-05-06 07:40:34 +00006924 // The kinds of expressions that we have special-case logic here for
6925 // should be kept up to date with the special checks for those
6926 // expressions in Sema.
6927
Chris Lattner68061312009-01-24 21:53:27 +00006928 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00006929 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00006930 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006931 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6932 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00006933
Chris Lattner68061312009-01-24 21:53:27 +00006934 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006935 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6936 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00006937
Chris Lattner24aeeab2009-01-24 21:09:06 +00006938 return GetAlignOfType(E->getType());
6939}
6940
6941
Peter Collingbournee190dee2011-03-11 19:24:49 +00006942/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
6943/// a result as the expression's type.
6944bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
6945 const UnaryExprOrTypeTraitExpr *E) {
6946 switch(E->getKind()) {
6947 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00006948 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00006949 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006950 else
Ken Dyckdbc01912011-03-11 02:13:43 +00006951 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006952 }
Eli Friedman64004332009-03-23 04:38:34 +00006953
Peter Collingbournee190dee2011-03-11 19:24:49 +00006954 case UETT_VecStep: {
6955 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00006956
Peter Collingbournee190dee2011-03-11 19:24:49 +00006957 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00006958 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00006959
Peter Collingbournee190dee2011-03-11 19:24:49 +00006960 // The vec_step built-in functions that take a 3-component
6961 // vector return 4. (OpenCL 1.1 spec 6.11.12)
6962 if (n == 3)
6963 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00006964
Peter Collingbournee190dee2011-03-11 19:24:49 +00006965 return Success(n, E);
6966 } else
6967 return Success(1, E);
6968 }
6969
6970 case UETT_SizeOf: {
6971 QualType SrcTy = E->getTypeOfArgument();
6972 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
6973 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00006974 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
6975 SrcTy = Ref->getPointeeType();
6976
Richard Smithd62306a2011-11-10 06:34:14 +00006977 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00006978 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00006979 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006980 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006981 }
6982 }
6983
6984 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006985}
6986
Peter Collingbournee9200682011-05-13 03:29:01 +00006987bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00006988 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00006989 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00006990 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006991 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00006992 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00006993 for (unsigned i = 0; i != n; ++i) {
6994 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
6995 switch (ON.getKind()) {
6996 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00006997 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00006998 APSInt IdxResult;
6999 if (!EvaluateInteger(Idx, IdxResult, Info))
7000 return false;
7001 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
7002 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007003 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007004 CurrentType = AT->getElementType();
7005 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
7006 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00007007 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00007008 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007009
Douglas Gregor882211c2010-04-28 22:16:22 +00007010 case OffsetOfExpr::OffsetOfNode::Field: {
7011 FieldDecl *MemberDecl = ON.getField();
7012 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007013 if (!RT)
7014 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007015 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007016 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00007017 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00007018 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00007019 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00007020 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00007021 CurrentType = MemberDecl->getType().getNonReferenceType();
7022 break;
7023 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007024
Douglas Gregor882211c2010-04-28 22:16:22 +00007025 case OffsetOfExpr::OffsetOfNode::Identifier:
7026 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00007027
Douglas Gregord1702062010-04-29 00:18:15 +00007028 case OffsetOfExpr::OffsetOfNode::Base: {
7029 CXXBaseSpecifier *BaseSpec = ON.getBase();
7030 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007031 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007032
7033 // Find the layout of the class whose base we are looking into.
7034 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007035 if (!RT)
7036 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007037 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007038 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00007039 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7040
7041 // Find the base class itself.
7042 CurrentType = BaseSpec->getType();
7043 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7044 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007045 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007046
7047 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00007048 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00007049 break;
7050 }
Douglas Gregor882211c2010-04-28 22:16:22 +00007051 }
7052 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007053 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007054}
7055
Chris Lattnere13042c2008-07-11 19:10:17 +00007056bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007057 switch (E->getOpcode()) {
7058 default:
7059 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7060 // See C99 6.6p3.
7061 return Error(E);
7062 case UO_Extension:
7063 // FIXME: Should extension allow i-c-e extension expressions in its scope?
7064 // If so, we could clear the diagnostic ID.
7065 return Visit(E->getSubExpr());
7066 case UO_Plus:
7067 // The result is just the value.
7068 return Visit(E->getSubExpr());
7069 case UO_Minus: {
7070 if (!Visit(E->getSubExpr()))
7071 return false;
7072 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00007073 const APSInt &Value = Result.getInt();
7074 if (Value.isSigned() && Value.isMinSignedValue())
7075 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7076 E->getType());
7077 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007078 }
7079 case UO_Not: {
7080 if (!Visit(E->getSubExpr()))
7081 return false;
7082 if (!Result.isInt()) return Error(E);
7083 return Success(~Result.getInt(), E);
7084 }
7085 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00007086 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00007087 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00007088 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007089 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007090 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007091 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007092}
Mike Stump11289f42009-09-09 15:08:12 +00007093
Chris Lattner477c4be2008-07-12 01:15:53 +00007094/// HandleCast - This is used to evaluate implicit or explicit casts where the
7095/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00007096bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
7097 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007098 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00007099 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007100
Eli Friedmanc757de22011-03-25 00:43:55 +00007101 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00007102 case CK_BaseToDerived:
7103 case CK_DerivedToBase:
7104 case CK_UncheckedDerivedToBase:
7105 case CK_Dynamic:
7106 case CK_ToUnion:
7107 case CK_ArrayToPointerDecay:
7108 case CK_FunctionToPointerDecay:
7109 case CK_NullToPointer:
7110 case CK_NullToMemberPointer:
7111 case CK_BaseToDerivedMemberPointer:
7112 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00007113 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00007114 case CK_ConstructorConversion:
7115 case CK_IntegralToPointer:
7116 case CK_ToVoid:
7117 case CK_VectorSplat:
7118 case CK_IntegralToFloating:
7119 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007120 case CK_CPointerToObjCPointerCast:
7121 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007122 case CK_AnyPointerToBlockPointerCast:
7123 case CK_ObjCObjectLValueCast:
7124 case CK_FloatingRealToComplex:
7125 case CK_FloatingComplexToReal:
7126 case CK_FloatingComplexCast:
7127 case CK_FloatingComplexToIntegralComplex:
7128 case CK_IntegralRealToComplex:
7129 case CK_IntegralComplexCast:
7130 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00007131 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007132 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007133 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00007134 case CK_AddressSpaceConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007135 llvm_unreachable("invalid cast kind for integral value");
7136
Eli Friedman9faf2f92011-03-25 19:07:11 +00007137 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007138 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007139 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00007140 case CK_ARCProduceObject:
7141 case CK_ARCConsumeObject:
7142 case CK_ARCReclaimReturnedObject:
7143 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007144 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007145 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007146
Richard Smith4ef685b2012-01-17 21:17:26 +00007147 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007148 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007149 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00007150 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007151 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007152
7153 case CK_MemberPointerToBoolean:
7154 case CK_PointerToBoolean:
7155 case CK_IntegralToBoolean:
7156 case CK_FloatingToBoolean:
7157 case CK_FloatingComplexToBoolean:
7158 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007159 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00007160 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00007161 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007162 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007163 }
7164
Eli Friedmanc757de22011-03-25 00:43:55 +00007165 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00007166 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00007167 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00007168
Eli Friedman742421e2009-02-20 01:15:07 +00007169 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007170 // Allow casts of address-of-label differences if they are no-ops
7171 // or narrowing. (The narrowing case isn't actually guaranteed to
7172 // be constant-evaluatable except in some narrow cases which are hard
7173 // to detect here. We let it through on the assumption the user knows
7174 // what they are doing.)
7175 if (Result.isAddrLabelDiff())
7176 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00007177 // Only allow casts of lvalues if they are lossless.
7178 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
7179 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007180
Richard Smith911e1422012-01-30 22:27:01 +00007181 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
7182 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00007183 }
Mike Stump11289f42009-09-09 15:08:12 +00007184
Eli Friedmanc757de22011-03-25 00:43:55 +00007185 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00007186 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7187
John McCall45d55e42010-05-07 21:00:08 +00007188 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00007189 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00007190 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00007191
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007192 if (LV.getLValueBase()) {
7193 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00007194 // FIXME: Allow a larger integer size than the pointer size, and allow
7195 // narrowing back down to pointer width in subsequent integral casts.
7196 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007197 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007198 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007199
Richard Smithcf74da72011-11-16 07:18:12 +00007200 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00007201 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007202 return true;
7203 }
7204
Ken Dyck02990832010-01-15 12:37:54 +00007205 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
7206 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00007207 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007208 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007209
Eli Friedmanc757de22011-03-25 00:43:55 +00007210 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00007211 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007212 if (!EvaluateComplex(SubExpr, C, Info))
7213 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00007214 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007215 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00007216
Eli Friedmanc757de22011-03-25 00:43:55 +00007217 case CK_FloatingToIntegral: {
7218 APFloat F(0.0);
7219 if (!EvaluateFloat(SubExpr, F, Info))
7220 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00007221
Richard Smith357362d2011-12-13 06:39:58 +00007222 APSInt Value;
7223 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7224 return false;
7225 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007226 }
7227 }
Mike Stump11289f42009-09-09 15:08:12 +00007228
Eli Friedmanc757de22011-03-25 00:43:55 +00007229 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00007230}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007231
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007232bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7233 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007234 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007235 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7236 return false;
7237 if (!LV.isComplexInt())
7238 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007239 return Success(LV.getComplexIntReal(), E);
7240 }
7241
7242 return Visit(E->getSubExpr());
7243}
7244
Eli Friedman4e7a2412009-02-27 04:45:43 +00007245bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007246 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007247 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007248 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7249 return false;
7250 if (!LV.isComplexInt())
7251 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007252 return Success(LV.getComplexIntImag(), E);
7253 }
7254
Richard Smith4a678122011-10-24 18:44:57 +00007255 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00007256 return Success(0, E);
7257}
7258
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007259bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
7260 return Success(E->getPackLength(), E);
7261}
7262
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007263bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
7264 return Success(E->getValue(), E);
7265}
7266
Chris Lattner05706e882008-07-11 18:11:29 +00007267//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00007268// Float Evaluation
7269//===----------------------------------------------------------------------===//
7270
7271namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007272class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007273 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00007274 APFloat &Result;
7275public:
7276 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007277 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00007278
Richard Smith2e312c82012-03-03 22:46:17 +00007279 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007280 Result = V.getFloat();
7281 return true;
7282 }
Eli Friedman24c01542008-08-22 00:06:13 +00007283
Richard Smithfddd3842011-12-30 21:15:51 +00007284 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00007285 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
7286 return true;
7287 }
7288
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007289 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007290
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007291 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007292 bool VisitBinaryOperator(const BinaryOperator *E);
7293 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007294 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00007295
John McCallb1fb0d32010-05-07 22:08:54 +00007296 bool VisitUnaryReal(const UnaryOperator *E);
7297 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00007298
Richard Smithfddd3842011-12-30 21:15:51 +00007299 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00007300};
7301} // end anonymous namespace
7302
7303static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007304 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007305 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00007306}
7307
Jay Foad39c79802011-01-12 09:06:06 +00007308static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00007309 QualType ResultTy,
7310 const Expr *Arg,
7311 bool SNaN,
7312 llvm::APFloat &Result) {
7313 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
7314 if (!S) return false;
7315
7316 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
7317
7318 llvm::APInt fill;
7319
7320 // Treat empty strings as if they were zero.
7321 if (S->getString().empty())
7322 fill = llvm::APInt(32, 0);
7323 else if (S->getString().getAsInteger(0, fill))
7324 return false;
7325
7326 if (SNaN)
7327 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7328 else
7329 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7330 return true;
7331}
7332
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007333bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00007334 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007335 default:
7336 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7337
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007338 case Builtin::BI__builtin_huge_val:
7339 case Builtin::BI__builtin_huge_valf:
7340 case Builtin::BI__builtin_huge_vall:
7341 case Builtin::BI__builtin_inf:
7342 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007343 case Builtin::BI__builtin_infl: {
7344 const llvm::fltSemantics &Sem =
7345 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00007346 Result = llvm::APFloat::getInf(Sem);
7347 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007348 }
Mike Stump11289f42009-09-09 15:08:12 +00007349
John McCall16291492010-02-28 13:00:19 +00007350 case Builtin::BI__builtin_nans:
7351 case Builtin::BI__builtin_nansf:
7352 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007353 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7354 true, Result))
7355 return Error(E);
7356 return true;
John McCall16291492010-02-28 13:00:19 +00007357
Chris Lattner0b7282e2008-10-06 06:31:58 +00007358 case Builtin::BI__builtin_nan:
7359 case Builtin::BI__builtin_nanf:
7360 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00007361 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00007362 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00007363 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7364 false, Result))
7365 return Error(E);
7366 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007367
7368 case Builtin::BI__builtin_fabs:
7369 case Builtin::BI__builtin_fabsf:
7370 case Builtin::BI__builtin_fabsl:
7371 if (!EvaluateFloat(E->getArg(0), Result, Info))
7372 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007373
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007374 if (Result.isNegative())
7375 Result.changeSign();
7376 return true;
7377
Richard Smith8889a3d2013-06-13 06:26:32 +00007378 // FIXME: Builtin::BI__builtin_powi
7379 // FIXME: Builtin::BI__builtin_powif
7380 // FIXME: Builtin::BI__builtin_powil
7381
Mike Stump11289f42009-09-09 15:08:12 +00007382 case Builtin::BI__builtin_copysign:
7383 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007384 case Builtin::BI__builtin_copysignl: {
7385 APFloat RHS(0.);
7386 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
7387 !EvaluateFloat(E->getArg(1), RHS, Info))
7388 return false;
7389 Result.copySign(RHS);
7390 return true;
7391 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007392 }
7393}
7394
John McCallb1fb0d32010-05-07 22:08:54 +00007395bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007396 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7397 ComplexValue CV;
7398 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7399 return false;
7400 Result = CV.FloatReal;
7401 return true;
7402 }
7403
7404 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00007405}
7406
7407bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007408 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7409 ComplexValue CV;
7410 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7411 return false;
7412 Result = CV.FloatImag;
7413 return true;
7414 }
7415
Richard Smith4a678122011-10-24 18:44:57 +00007416 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00007417 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
7418 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00007419 return true;
7420}
7421
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007422bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007423 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007424 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007425 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00007426 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00007427 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00007428 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
7429 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007430 Result.changeSign();
7431 return true;
7432 }
7433}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007434
Eli Friedman24c01542008-08-22 00:06:13 +00007435bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007436 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7437 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00007438
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007439 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00007440 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
7441 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00007442 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00007443 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
7444 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00007445}
7446
7447bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
7448 Result = E->getValue();
7449 return true;
7450}
7451
Peter Collingbournee9200682011-05-13 03:29:01 +00007452bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
7453 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00007454
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007455 switch (E->getCastKind()) {
7456 default:
Richard Smith11562c52011-10-28 17:51:58 +00007457 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007458
7459 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007460 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00007461 return EvaluateInteger(SubExpr, IntResult, Info) &&
7462 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
7463 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007464 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007465
7466 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007467 if (!Visit(SubExpr))
7468 return false;
Richard Smith357362d2011-12-13 06:39:58 +00007469 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
7470 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007471 }
John McCalld7646252010-11-14 08:17:51 +00007472
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007473 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00007474 ComplexValue V;
7475 if (!EvaluateComplex(SubExpr, V, Info))
7476 return false;
7477 Result = V.getComplexFloatReal();
7478 return true;
7479 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007480 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007481}
7482
Eli Friedman24c01542008-08-22 00:06:13 +00007483//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007484// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00007485//===----------------------------------------------------------------------===//
7486
7487namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007488class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007489 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00007490 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00007491
Anders Carlsson537969c2008-11-16 20:27:53 +00007492public:
John McCall93d91dc2010-05-07 17:22:02 +00007493 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007494 : ExprEvaluatorBaseTy(info), Result(Result) {}
7495
Richard Smith2e312c82012-03-03 22:46:17 +00007496 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007497 Result.setFrom(V);
7498 return true;
7499 }
Mike Stump11289f42009-09-09 15:08:12 +00007500
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007501 bool ZeroInitialization(const Expr *E);
7502
Anders Carlsson537969c2008-11-16 20:27:53 +00007503 //===--------------------------------------------------------------------===//
7504 // Visitor Methods
7505 //===--------------------------------------------------------------------===//
7506
Peter Collingbournee9200682011-05-13 03:29:01 +00007507 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007508 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00007509 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007510 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007511 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007512};
7513} // end anonymous namespace
7514
John McCall93d91dc2010-05-07 17:22:02 +00007515static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
7516 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007517 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007518 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007519}
7520
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007521bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00007522 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007523 if (ElemTy->isRealFloatingType()) {
7524 Result.makeComplexFloat();
7525 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
7526 Result.FloatReal = Zero;
7527 Result.FloatImag = Zero;
7528 } else {
7529 Result.makeComplexInt();
7530 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
7531 Result.IntReal = Zero;
7532 Result.IntImag = Zero;
7533 }
7534 return true;
7535}
7536
Peter Collingbournee9200682011-05-13 03:29:01 +00007537bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
7538 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007539
7540 if (SubExpr->getType()->isRealFloatingType()) {
7541 Result.makeComplexFloat();
7542 APFloat &Imag = Result.FloatImag;
7543 if (!EvaluateFloat(SubExpr, Imag, Info))
7544 return false;
7545
7546 Result.FloatReal = APFloat(Imag.getSemantics());
7547 return true;
7548 } else {
7549 assert(SubExpr->getType()->isIntegerType() &&
7550 "Unexpected imaginary literal.");
7551
7552 Result.makeComplexInt();
7553 APSInt &Imag = Result.IntImag;
7554 if (!EvaluateInteger(SubExpr, Imag, Info))
7555 return false;
7556
7557 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
7558 return true;
7559 }
7560}
7561
Peter Collingbournee9200682011-05-13 03:29:01 +00007562bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007563
John McCallfcef3cf2010-12-14 17:51:41 +00007564 switch (E->getCastKind()) {
7565 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007566 case CK_BaseToDerived:
7567 case CK_DerivedToBase:
7568 case CK_UncheckedDerivedToBase:
7569 case CK_Dynamic:
7570 case CK_ToUnion:
7571 case CK_ArrayToPointerDecay:
7572 case CK_FunctionToPointerDecay:
7573 case CK_NullToPointer:
7574 case CK_NullToMemberPointer:
7575 case CK_BaseToDerivedMemberPointer:
7576 case CK_DerivedToBaseMemberPointer:
7577 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00007578 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00007579 case CK_ConstructorConversion:
7580 case CK_IntegralToPointer:
7581 case CK_PointerToIntegral:
7582 case CK_PointerToBoolean:
7583 case CK_ToVoid:
7584 case CK_VectorSplat:
7585 case CK_IntegralCast:
7586 case CK_IntegralToBoolean:
7587 case CK_IntegralToFloating:
7588 case CK_FloatingToIntegral:
7589 case CK_FloatingToBoolean:
7590 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007591 case CK_CPointerToObjCPointerCast:
7592 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007593 case CK_AnyPointerToBlockPointerCast:
7594 case CK_ObjCObjectLValueCast:
7595 case CK_FloatingComplexToReal:
7596 case CK_FloatingComplexToBoolean:
7597 case CK_IntegralComplexToReal:
7598 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00007599 case CK_ARCProduceObject:
7600 case CK_ARCConsumeObject:
7601 case CK_ARCReclaimReturnedObject:
7602 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007603 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00007604 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007605 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007606 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00007607 case CK_AddressSpaceConversion:
John McCallfcef3cf2010-12-14 17:51:41 +00007608 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00007609
John McCallfcef3cf2010-12-14 17:51:41 +00007610 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007611 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00007612 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007613 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007614
7615 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007616 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007617 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007618 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007619
7620 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007621 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00007622 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007623 return false;
7624
John McCallfcef3cf2010-12-14 17:51:41 +00007625 Result.makeComplexFloat();
7626 Result.FloatImag = APFloat(Real.getSemantics());
7627 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007628 }
7629
John McCallfcef3cf2010-12-14 17:51:41 +00007630 case CK_FloatingComplexCast: {
7631 if (!Visit(E->getSubExpr()))
7632 return false;
7633
7634 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7635 QualType From
7636 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7637
Richard Smith357362d2011-12-13 06:39:58 +00007638 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
7639 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007640 }
7641
7642 case CK_FloatingComplexToIntegralComplex: {
7643 if (!Visit(E->getSubExpr()))
7644 return false;
7645
7646 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7647 QualType From
7648 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7649 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00007650 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
7651 To, Result.IntReal) &&
7652 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
7653 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007654 }
7655
7656 case CK_IntegralRealToComplex: {
7657 APSInt &Real = Result.IntReal;
7658 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
7659 return false;
7660
7661 Result.makeComplexInt();
7662 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
7663 return true;
7664 }
7665
7666 case CK_IntegralComplexCast: {
7667 if (!Visit(E->getSubExpr()))
7668 return false;
7669
7670 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7671 QualType From
7672 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7673
Richard Smith911e1422012-01-30 22:27:01 +00007674 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7675 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007676 return true;
7677 }
7678
7679 case CK_IntegralComplexToFloatingComplex: {
7680 if (!Visit(E->getSubExpr()))
7681 return false;
7682
Ted Kremenek28831752012-08-23 20:46:57 +00007683 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007684 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00007685 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007686 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00007687 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7688 To, Result.FloatReal) &&
7689 HandleIntToFloatCast(Info, E, From, Result.IntImag,
7690 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007691 }
7692 }
7693
7694 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007695}
7696
John McCall93d91dc2010-05-07 17:22:02 +00007697bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007698 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00007699 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7700
Richard Smith253c2a32012-01-27 01:14:48 +00007701 bool LHSOK = Visit(E->getLHS());
7702 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00007703 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007704
John McCall93d91dc2010-05-07 17:22:02 +00007705 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00007706 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00007707 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007708
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007709 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
7710 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007711 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007712 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007713 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007714 if (Result.isComplexFloat()) {
7715 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
7716 APFloat::rmNearestTiesToEven);
7717 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
7718 APFloat::rmNearestTiesToEven);
7719 } else {
7720 Result.getComplexIntReal() += RHS.getComplexIntReal();
7721 Result.getComplexIntImag() += RHS.getComplexIntImag();
7722 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007723 break;
John McCalle3027922010-08-25 11:45:40 +00007724 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007725 if (Result.isComplexFloat()) {
7726 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
7727 APFloat::rmNearestTiesToEven);
7728 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
7729 APFloat::rmNearestTiesToEven);
7730 } else {
7731 Result.getComplexIntReal() -= RHS.getComplexIntReal();
7732 Result.getComplexIntImag() -= RHS.getComplexIntImag();
7733 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007734 break;
John McCalle3027922010-08-25 11:45:40 +00007735 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007736 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00007737 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007738 APFloat &LHS_r = LHS.getComplexFloatReal();
7739 APFloat &LHS_i = LHS.getComplexFloatImag();
7740 APFloat &RHS_r = RHS.getComplexFloatReal();
7741 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00007742
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007743 APFloat Tmp = LHS_r;
7744 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7745 Result.getComplexFloatReal() = Tmp;
7746 Tmp = LHS_i;
7747 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7748 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
7749
7750 Tmp = LHS_r;
7751 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7752 Result.getComplexFloatImag() = Tmp;
7753 Tmp = LHS_i;
7754 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7755 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
7756 } else {
John McCall93d91dc2010-05-07 17:22:02 +00007757 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00007758 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007759 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
7760 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00007761 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007762 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
7763 LHS.getComplexIntImag() * RHS.getComplexIntReal());
7764 }
7765 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007766 case BO_Div:
7767 if (Result.isComplexFloat()) {
7768 ComplexValue LHS = Result;
7769 APFloat &LHS_r = LHS.getComplexFloatReal();
7770 APFloat &LHS_i = LHS.getComplexFloatImag();
7771 APFloat &RHS_r = RHS.getComplexFloatReal();
7772 APFloat &RHS_i = RHS.getComplexFloatImag();
7773 APFloat &Res_r = Result.getComplexFloatReal();
7774 APFloat &Res_i = Result.getComplexFloatImag();
7775
7776 APFloat Den = RHS_r;
7777 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7778 APFloat Tmp = RHS_i;
7779 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7780 Den.add(Tmp, APFloat::rmNearestTiesToEven);
7781
7782 Res_r = LHS_r;
7783 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7784 Tmp = LHS_i;
7785 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7786 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
7787 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
7788
7789 Res_i = LHS_i;
7790 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7791 Tmp = LHS_r;
7792 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7793 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
7794 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
7795 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007796 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
7797 return Error(E, diag::note_expr_divide_by_zero);
7798
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007799 ComplexValue LHS = Result;
7800 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
7801 RHS.getComplexIntImag() * RHS.getComplexIntImag();
7802 Result.getComplexIntReal() =
7803 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
7804 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
7805 Result.getComplexIntImag() =
7806 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
7807 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
7808 }
7809 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007810 }
7811
John McCall93d91dc2010-05-07 17:22:02 +00007812 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007813}
7814
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007815bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7816 // Get the operand value into 'Result'.
7817 if (!Visit(E->getSubExpr()))
7818 return false;
7819
7820 switch (E->getOpcode()) {
7821 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007822 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007823 case UO_Extension:
7824 return true;
7825 case UO_Plus:
7826 // The result is always just the subexpr.
7827 return true;
7828 case UO_Minus:
7829 if (Result.isComplexFloat()) {
7830 Result.getComplexFloatReal().changeSign();
7831 Result.getComplexFloatImag().changeSign();
7832 }
7833 else {
7834 Result.getComplexIntReal() = -Result.getComplexIntReal();
7835 Result.getComplexIntImag() = -Result.getComplexIntImag();
7836 }
7837 return true;
7838 case UO_Not:
7839 if (Result.isComplexFloat())
7840 Result.getComplexFloatImag().changeSign();
7841 else
7842 Result.getComplexIntImag() = -Result.getComplexIntImag();
7843 return true;
7844 }
7845}
7846
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007847bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7848 if (E->getNumInits() == 2) {
7849 if (E->getType()->isComplexType()) {
7850 Result.makeComplexFloat();
7851 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
7852 return false;
7853 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
7854 return false;
7855 } else {
7856 Result.makeComplexInt();
7857 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
7858 return false;
7859 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
7860 return false;
7861 }
7862 return true;
7863 }
7864 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
7865}
7866
Anders Carlsson537969c2008-11-16 20:27:53 +00007867//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00007868// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
7869// implicit conversion.
7870//===----------------------------------------------------------------------===//
7871
7872namespace {
7873class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00007874 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00007875 APValue &Result;
7876public:
7877 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
7878 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7879
7880 bool Success(const APValue &V, const Expr *E) {
7881 Result = V;
7882 return true;
7883 }
7884
7885 bool ZeroInitialization(const Expr *E) {
7886 ImplicitValueInitExpr VIE(
7887 E->getType()->castAs<AtomicType>()->getValueType());
7888 return Evaluate(Result, Info, &VIE);
7889 }
7890
7891 bool VisitCastExpr(const CastExpr *E) {
7892 switch (E->getCastKind()) {
7893 default:
7894 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7895 case CK_NonAtomicToAtomic:
7896 return Evaluate(Result, Info, E->getSubExpr());
7897 }
7898 }
7899};
7900} // end anonymous namespace
7901
7902static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
7903 assert(E->isRValue() && E->getType()->isAtomicType());
7904 return AtomicExprEvaluator(Info, Result).Visit(E);
7905}
7906
7907//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00007908// Void expression evaluation, primarily for a cast to void on the LHS of a
7909// comma operator
7910//===----------------------------------------------------------------------===//
7911
7912namespace {
7913class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007914 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00007915public:
7916 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
7917
Richard Smith2e312c82012-03-03 22:46:17 +00007918 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00007919
7920 bool VisitCastExpr(const CastExpr *E) {
7921 switch (E->getCastKind()) {
7922 default:
7923 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7924 case CK_ToVoid:
7925 VisitIgnoredValue(E->getSubExpr());
7926 return true;
7927 }
7928 }
7929};
7930} // end anonymous namespace
7931
7932static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
7933 assert(E->isRValue() && E->getType()->isVoidType());
7934 return VoidExprEvaluator(Info).Visit(E);
7935}
7936
7937//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00007938// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00007939//===----------------------------------------------------------------------===//
7940
Richard Smith2e312c82012-03-03 22:46:17 +00007941static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007942 // In C, function designators are not lvalues, but we evaluate them as if they
7943 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00007944 QualType T = E->getType();
7945 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00007946 LValue LV;
7947 if (!EvaluateLValue(E, LV, Info))
7948 return false;
7949 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007950 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007951 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007952 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007953 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007954 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007955 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007956 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00007957 LValue LV;
7958 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007959 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007960 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007961 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00007962 llvm::APFloat F(0.0);
7963 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007964 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007965 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00007966 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00007967 ComplexValue C;
7968 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007969 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007970 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007971 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00007972 MemberPtr P;
7973 if (!EvaluateMemberPointer(E, P, Info))
7974 return false;
7975 P.moveInto(Result);
7976 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00007977 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007978 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007979 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00007980 APValue &Value = Info.CurrentCall->createTemporary(E, false);
7981 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00007982 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00007983 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00007984 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007985 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007986 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00007987 APValue &Value = Info.CurrentCall->createTemporary(E, false);
7988 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00007989 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00007990 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00007991 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007992 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007993 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00007994 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00007995 if (!EvaluateVoid(E, Info))
7996 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007997 } else if (T->isAtomicType()) {
7998 if (!EvaluateAtomic(E, Result, Info))
7999 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008000 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008001 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00008002 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008003 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008004 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00008005 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008006 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008007
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00008008 return true;
8009}
8010
Richard Smithb228a862012-02-15 02:18:13 +00008011/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
8012/// cases, the in-place evaluation is essential, since later initializers for
8013/// an object can indirectly refer to subobjects which were initialized earlier.
8014static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00008015 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00008016 assert(!E->isValueDependent());
8017
Richard Smith7525ff62013-05-09 07:14:00 +00008018 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00008019 return false;
8020
8021 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00008022 // Evaluate arrays and record types in-place, so that later initializers can
8023 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00008024 if (E->getType()->isArrayType())
8025 return EvaluateArray(E, This, Result, Info);
8026 else if (E->getType()->isRecordType())
8027 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00008028 }
8029
8030 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00008031 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00008032}
8033
Richard Smithf57d8cb2011-12-09 22:58:01 +00008034/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
8035/// lvalue-to-rvalue cast if it is an lvalue.
8036static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00008037 if (E->getType().isNull())
8038 return false;
8039
Richard Smithfddd3842011-12-30 21:15:51 +00008040 if (!CheckLiteralType(Info, E))
8041 return false;
8042
Richard Smith2e312c82012-03-03 22:46:17 +00008043 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008044 return false;
8045
8046 if (E->isGLValue()) {
8047 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00008048 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00008049 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008050 return false;
8051 }
8052
Richard Smith2e312c82012-03-03 22:46:17 +00008053 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00008054 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008055}
Richard Smith11562c52011-10-28 17:51:58 +00008056
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008057static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
8058 const ASTContext &Ctx, bool &IsConst) {
8059 // Fast-path evaluations of integer literals, since we sometimes see files
8060 // containing vast quantities of these.
8061 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
8062 Result.Val = APValue(APSInt(L->getValue(),
8063 L->getType()->isUnsignedIntegerType()));
8064 IsConst = true;
8065 return true;
8066 }
James Dennett0492ef02014-03-14 17:44:10 +00008067
8068 // This case should be rare, but we need to check it before we check on
8069 // the type below.
8070 if (Exp->getType().isNull()) {
8071 IsConst = false;
8072 return true;
8073 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008074
8075 // FIXME: Evaluating values of large array and record types can cause
8076 // performance problems. Only do so in C++11 for now.
8077 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
8078 Exp->getType()->isRecordType()) &&
8079 !Ctx.getLangOpts().CPlusPlus11) {
8080 IsConst = false;
8081 return true;
8082 }
8083 return false;
8084}
8085
8086
Richard Smith7b553f12011-10-29 00:50:52 +00008087/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00008088/// any crazy technique (that has nothing to do with language standards) that
8089/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00008090/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
8091/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00008092bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008093 bool IsConst;
8094 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
8095 return IsConst;
8096
Richard Smith6d4c6582013-11-05 22:18:15 +00008097 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008098 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00008099}
8100
Jay Foad39c79802011-01-12 09:06:06 +00008101bool Expr::EvaluateAsBooleanCondition(bool &Result,
8102 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00008103 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00008104 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00008105 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00008106}
8107
Richard Smith5fab0c92011-12-28 19:48:30 +00008108bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
8109 SideEffectsKind AllowSideEffects) const {
8110 if (!getType()->isIntegralOrEnumerationType())
8111 return false;
8112
Richard Smith11562c52011-10-28 17:51:58 +00008113 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00008114 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
8115 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00008116 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008117
Richard Smith11562c52011-10-28 17:51:58 +00008118 Result = ExprResult.Val.getInt();
8119 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00008120}
8121
Jay Foad39c79802011-01-12 09:06:06 +00008122bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00008123 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00008124
John McCall45d55e42010-05-07 21:00:08 +00008125 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008126 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
8127 !CheckLValueConstantExpression(Info, getExprLoc(),
8128 Ctx.getLValueReferenceType(getType()), LV))
8129 return false;
8130
Richard Smith2e312c82012-03-03 22:46:17 +00008131 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00008132 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00008133}
8134
Richard Smithd0b4dd62011-12-19 06:19:21 +00008135bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
8136 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008137 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00008138 // FIXME: Evaluating initializers for large array and record types can cause
8139 // performance problems. Only do so in C++11 for now.
8140 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008141 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00008142 return false;
8143
Richard Smithd0b4dd62011-12-19 06:19:21 +00008144 Expr::EvalStatus EStatus;
8145 EStatus.Diag = &Notes;
8146
Richard Smith6d4c6582013-11-05 22:18:15 +00008147 EvalInfo InitInfo(Ctx, EStatus, EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008148 InitInfo.setEvaluatingDecl(VD, Value);
8149
8150 LValue LVal;
8151 LVal.set(VD);
8152
Richard Smithfddd3842011-12-30 21:15:51 +00008153 // C++11 [basic.start.init]p2:
8154 // Variables with static storage duration or thread storage duration shall be
8155 // zero-initialized before any other initialization takes place.
8156 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008157 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00008158 !VD->getType()->isReferenceType()) {
8159 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00008160 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00008161 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00008162 return false;
8163 }
8164
Richard Smith7525ff62013-05-09 07:14:00 +00008165 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
8166 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00008167 EStatus.HasSideEffects)
8168 return false;
8169
8170 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
8171 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008172}
8173
Richard Smith7b553f12011-10-29 00:50:52 +00008174/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
8175/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00008176bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00008177 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00008178 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00008179}
Anders Carlsson59689ed2008-11-22 21:04:56 +00008180
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008181APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008182 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008183 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008184 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00008185 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00008186 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00008187 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008188 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00008189
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008190 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00008191}
John McCall864e3962010-05-07 05:32:02 +00008192
Richard Smithe9ff7702013-11-05 22:23:30 +00008193void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008194 bool IsConst;
8195 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008196 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00008197 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008198 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
8199 }
8200}
8201
Richard Smithe6c01442013-06-05 00:46:14 +00008202bool Expr::EvalResult::isGlobalLValue() const {
8203 assert(Val.isLValue());
8204 return IsGlobalLValue(Val.getLValueBase());
8205}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00008206
8207
John McCall864e3962010-05-07 05:32:02 +00008208/// isIntegerConstantExpr - this recursive routine will test if an expression is
8209/// an integer constant expression.
8210
8211/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
8212/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00008213
8214// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00008215// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
8216// and a (possibly null) SourceLocation indicating the location of the problem.
8217//
John McCall864e3962010-05-07 05:32:02 +00008218// Note that to reduce code duplication, this helper does no evaluation
8219// itself; the caller checks whether the expression is evaluatable, and
8220// in the rare cases where CheckICE actually cares about the evaluated
8221// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00008222
Dan Gohman28ade552010-07-26 21:25:24 +00008223namespace {
8224
Richard Smith9e575da2012-12-28 13:25:52 +00008225enum ICEKind {
8226 /// This expression is an ICE.
8227 IK_ICE,
8228 /// This expression is not an ICE, but if it isn't evaluated, it's
8229 /// a legal subexpression for an ICE. This return value is used to handle
8230 /// the comma operator in C99 mode, and non-constant subexpressions.
8231 IK_ICEIfUnevaluated,
8232 /// This expression is not an ICE, and is not a legal subexpression for one.
8233 IK_NotICE
8234};
8235
John McCall864e3962010-05-07 05:32:02 +00008236struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00008237 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00008238 SourceLocation Loc;
8239
Richard Smith9e575da2012-12-28 13:25:52 +00008240 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00008241};
8242
Dan Gohman28ade552010-07-26 21:25:24 +00008243}
8244
Richard Smith9e575da2012-12-28 13:25:52 +00008245static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
8246
8247static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00008248
Craig Toppera31a8822013-08-22 07:09:37 +00008249static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008250 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00008251 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00008252 !EVResult.Val.isInt())
8253 return ICEDiag(IK_NotICE, E->getLocStart());
8254
John McCall864e3962010-05-07 05:32:02 +00008255 return NoDiag();
8256}
8257
Craig Toppera31a8822013-08-22 07:09:37 +00008258static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008259 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00008260 if (!E->getType()->isIntegralOrEnumerationType())
8261 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008262
8263 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00008264#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00008265#define STMT(Node, Base) case Expr::Node##Class:
8266#define EXPR(Node, Base)
8267#include "clang/AST/StmtNodes.inc"
8268 case Expr::PredefinedExprClass:
8269 case Expr::FloatingLiteralClass:
8270 case Expr::ImaginaryLiteralClass:
8271 case Expr::StringLiteralClass:
8272 case Expr::ArraySubscriptExprClass:
8273 case Expr::MemberExprClass:
8274 case Expr::CompoundAssignOperatorClass:
8275 case Expr::CompoundLiteralExprClass:
8276 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00008277 case Expr::DesignatedInitExprClass:
8278 case Expr::ImplicitValueInitExprClass:
8279 case Expr::ParenListExprClass:
8280 case Expr::VAArgExprClass:
8281 case Expr::AddrLabelExprClass:
8282 case Expr::StmtExprClass:
8283 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00008284 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00008285 case Expr::CXXDynamicCastExprClass:
8286 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00008287 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00008288 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008289 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00008290 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008291 case Expr::CXXThisExprClass:
8292 case Expr::CXXThrowExprClass:
8293 case Expr::CXXNewExprClass:
8294 case Expr::CXXDeleteExprClass:
8295 case Expr::CXXPseudoDestructorExprClass:
8296 case Expr::UnresolvedLookupExprClass:
8297 case Expr::DependentScopeDeclRefExprClass:
8298 case Expr::CXXConstructExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00008299 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00008300 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00008301 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00008302 case Expr::CXXTemporaryObjectExprClass:
8303 case Expr::CXXUnresolvedConstructExprClass:
8304 case Expr::CXXDependentScopeMemberExprClass:
8305 case Expr::UnresolvedMemberExprClass:
8306 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00008307 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008308 case Expr::ObjCArrayLiteralClass:
8309 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008310 case Expr::ObjCEncodeExprClass:
8311 case Expr::ObjCMessageExprClass:
8312 case Expr::ObjCSelectorExprClass:
8313 case Expr::ObjCProtocolExprClass:
8314 case Expr::ObjCIvarRefExprClass:
8315 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008316 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008317 case Expr::ObjCIsaExprClass:
8318 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00008319 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +00008320 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00008321 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00008322 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00008323 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00008324 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00008325 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00008326 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00008327 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00008328 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00008329 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00008330 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00008331 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00008332 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00008333
Richard Smithf137f932014-01-25 20:50:08 +00008334 case Expr::InitListExprClass: {
8335 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
8336 // form "T x = { a };" is equivalent to "T x = a;".
8337 // Unless we're initializing a reference, T is a scalar as it is known to be
8338 // of integral or enumeration type.
8339 if (E->isRValue())
8340 if (cast<InitListExpr>(E)->getNumInits() == 1)
8341 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
8342 return ICEDiag(IK_NotICE, E->getLocStart());
8343 }
8344
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008345 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00008346 case Expr::GNUNullExprClass:
8347 // GCC considers the GNU __null value to be an integral constant expression.
8348 return NoDiag();
8349
John McCall7c454bb2011-07-15 05:09:51 +00008350 case Expr::SubstNonTypeTemplateParmExprClass:
8351 return
8352 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
8353
John McCall864e3962010-05-07 05:32:02 +00008354 case Expr::ParenExprClass:
8355 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00008356 case Expr::GenericSelectionExprClass:
8357 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008358 case Expr::IntegerLiteralClass:
8359 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008360 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00008361 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00008362 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00008363 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00008364 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00008365 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00008366 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00008367 return NoDiag();
8368 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00008369 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00008370 // C99 6.6/3 allows function calls within unevaluated subexpressions of
8371 // constant expressions, but they can never be ICEs because an ICE cannot
8372 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00008373 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +00008374 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +00008375 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008376 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008377 }
Richard Smith6365c912012-02-24 22:12:32 +00008378 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008379 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
8380 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00008381 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008382 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00008383 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00008384 // Parameter variables are never constants. Without this check,
8385 // getAnyInitializer() can find a default argument, which leads
8386 // to chaos.
8387 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00008388 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008389
8390 // C++ 7.1.5.1p2
8391 // A variable of non-volatile const-qualified integral or enumeration
8392 // type initialized by an ICE can be used in ICEs.
8393 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00008394 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00008395 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00008396
Richard Smithd0b4dd62011-12-19 06:19:21 +00008397 const VarDecl *VD;
8398 // Look for a declaration of this variable that has an initializer, and
8399 // check whether it is an ICE.
8400 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
8401 return NoDiag();
8402 else
Richard Smith9e575da2012-12-28 13:25:52 +00008403 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008404 }
8405 }
Richard Smith9e575da2012-12-28 13:25:52 +00008406 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00008407 }
John McCall864e3962010-05-07 05:32:02 +00008408 case Expr::UnaryOperatorClass: {
8409 const UnaryOperator *Exp = cast<UnaryOperator>(E);
8410 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008411 case UO_PostInc:
8412 case UO_PostDec:
8413 case UO_PreInc:
8414 case UO_PreDec:
8415 case UO_AddrOf:
8416 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00008417 // C99 6.6/3 allows increment and decrement within unevaluated
8418 // subexpressions of constant expressions, but they can never be ICEs
8419 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008420 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00008421 case UO_Extension:
8422 case UO_LNot:
8423 case UO_Plus:
8424 case UO_Minus:
8425 case UO_Not:
8426 case UO_Real:
8427 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00008428 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008429 }
Richard Smith9e575da2012-12-28 13:25:52 +00008430
John McCall864e3962010-05-07 05:32:02 +00008431 // OffsetOf falls through here.
8432 }
8433 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00008434 // Note that per C99, offsetof must be an ICE. And AFAIK, using
8435 // EvaluateAsRValue matches the proposed gcc behavior for cases like
8436 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
8437 // compliance: we should warn earlier for offsetof expressions with
8438 // array subscripts that aren't ICEs, and if the array subscripts
8439 // are ICEs, the value of the offsetof must be an integer constant.
8440 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008441 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00008442 case Expr::UnaryExprOrTypeTraitExprClass: {
8443 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
8444 if ((Exp->getKind() == UETT_SizeOf) &&
8445 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00008446 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008447 return NoDiag();
8448 }
8449 case Expr::BinaryOperatorClass: {
8450 const BinaryOperator *Exp = cast<BinaryOperator>(E);
8451 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008452 case BO_PtrMemD:
8453 case BO_PtrMemI:
8454 case BO_Assign:
8455 case BO_MulAssign:
8456 case BO_DivAssign:
8457 case BO_RemAssign:
8458 case BO_AddAssign:
8459 case BO_SubAssign:
8460 case BO_ShlAssign:
8461 case BO_ShrAssign:
8462 case BO_AndAssign:
8463 case BO_XorAssign:
8464 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00008465 // C99 6.6/3 allows assignments within unevaluated subexpressions of
8466 // constant expressions, but they can never be ICEs because an ICE cannot
8467 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008468 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008469
John McCalle3027922010-08-25 11:45:40 +00008470 case BO_Mul:
8471 case BO_Div:
8472 case BO_Rem:
8473 case BO_Add:
8474 case BO_Sub:
8475 case BO_Shl:
8476 case BO_Shr:
8477 case BO_LT:
8478 case BO_GT:
8479 case BO_LE:
8480 case BO_GE:
8481 case BO_EQ:
8482 case BO_NE:
8483 case BO_And:
8484 case BO_Xor:
8485 case BO_Or:
8486 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00008487 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8488 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00008489 if (Exp->getOpcode() == BO_Div ||
8490 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00008491 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00008492 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00008493 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00008494 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008495 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00008496 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008497 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00008498 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008499 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00008500 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008501 }
8502 }
8503 }
John McCalle3027922010-08-25 11:45:40 +00008504 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008505 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00008506 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
8507 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00008508 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
8509 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008510 } else {
8511 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00008512 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008513 }
8514 }
Richard Smith9e575da2012-12-28 13:25:52 +00008515 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008516 }
John McCalle3027922010-08-25 11:45:40 +00008517 case BO_LAnd:
8518 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00008519 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8520 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008521 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00008522 // Rare case where the RHS has a comma "side-effect"; we need
8523 // to actually check the condition to see whether the side
8524 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00008525 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00008526 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00008527 return RHSResult;
8528 return NoDiag();
8529 }
8530
Richard Smith9e575da2012-12-28 13:25:52 +00008531 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008532 }
8533 }
8534 }
8535 case Expr::ImplicitCastExprClass:
8536 case Expr::CStyleCastExprClass:
8537 case Expr::CXXFunctionalCastExprClass:
8538 case Expr::CXXStaticCastExprClass:
8539 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00008540 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00008541 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008542 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00008543 if (isa<ExplicitCastExpr>(E)) {
8544 if (const FloatingLiteral *FL
8545 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
8546 unsigned DestWidth = Ctx.getIntWidth(E->getType());
8547 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
8548 APSInt IgnoredVal(DestWidth, !DestSigned);
8549 bool Ignored;
8550 // If the value does not fit in the destination type, the behavior is
8551 // undefined, so we are not required to treat it as a constant
8552 // expression.
8553 if (FL->getValue().convertToInteger(IgnoredVal,
8554 llvm::APFloat::rmTowardZero,
8555 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00008556 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00008557 return NoDiag();
8558 }
8559 }
Eli Friedman76d4e432011-09-29 21:49:34 +00008560 switch (cast<CastExpr>(E)->getCastKind()) {
8561 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008562 case CK_AtomicToNonAtomic:
8563 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00008564 case CK_NoOp:
8565 case CK_IntegralToBoolean:
8566 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00008567 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00008568 default:
Richard Smith9e575da2012-12-28 13:25:52 +00008569 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00008570 }
John McCall864e3962010-05-07 05:32:02 +00008571 }
John McCallc07a0c72011-02-17 10:25:35 +00008572 case Expr::BinaryConditionalOperatorClass: {
8573 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
8574 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008575 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00008576 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008577 if (FalseResult.Kind == IK_NotICE) return FalseResult;
8578 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
8579 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00008580 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00008581 return FalseResult;
8582 }
John McCall864e3962010-05-07 05:32:02 +00008583 case Expr::ConditionalOperatorClass: {
8584 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
8585 // If the condition (ignoring parens) is a __builtin_constant_p call,
8586 // then only the true side is actually considered in an integer constant
8587 // expression, and it is fully evaluated. This is an important GNU
8588 // extension. See GCC PR38377 for discussion.
8589 if (const CallExpr *CallCE
8590 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00008591 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +00008592 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008593 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008594 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008595 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008596
Richard Smithf57d8cb2011-12-09 22:58:01 +00008597 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
8598 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008599
Richard Smith9e575da2012-12-28 13:25:52 +00008600 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008601 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008602 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008603 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008604 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00008605 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008606 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00008607 return NoDiag();
8608 // Rare case where the diagnostics depend on which side is evaluated
8609 // Note that if we get here, CondResult is 0, and at least one of
8610 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00008611 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00008612 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00008613 return TrueResult;
8614 }
8615 case Expr::CXXDefaultArgExprClass:
8616 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00008617 case Expr::CXXDefaultInitExprClass:
8618 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008619 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +00008620 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008621 }
8622 }
8623
David Blaikiee4d798f2012-01-20 21:50:17 +00008624 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00008625}
8626
Richard Smithf57d8cb2011-12-09 22:58:01 +00008627/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +00008628static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00008629 const Expr *E,
8630 llvm::APSInt *Value,
8631 SourceLocation *Loc) {
8632 if (!E->getType()->isIntegralOrEnumerationType()) {
8633 if (Loc) *Loc = E->getExprLoc();
8634 return false;
8635 }
8636
Richard Smith66e05fe2012-01-18 05:21:49 +00008637 APValue Result;
8638 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00008639 return false;
8640
Richard Smith66e05fe2012-01-18 05:21:49 +00008641 assert(Result.isInt() && "pointer cast to int is not an ICE");
8642 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00008643 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008644}
8645
Craig Toppera31a8822013-08-22 07:09:37 +00008646bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
8647 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008648 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008649 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
8650
Richard Smith9e575da2012-12-28 13:25:52 +00008651 ICEDiag D = CheckICE(this, Ctx);
8652 if (D.Kind != IK_ICE) {
8653 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00008654 return false;
8655 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008656 return true;
8657}
8658
Craig Toppera31a8822013-08-22 07:09:37 +00008659bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00008660 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008661 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008662 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
8663
8664 if (!isIntegerConstantExpr(Ctx, Loc))
8665 return false;
8666 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00008667 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00008668 return true;
8669}
Richard Smith66e05fe2012-01-18 05:21:49 +00008670
Craig Toppera31a8822013-08-22 07:09:37 +00008671bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00008672 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00008673}
8674
Craig Toppera31a8822013-08-22 07:09:37 +00008675bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +00008676 SourceLocation *Loc) const {
8677 // We support this checking in C++98 mode in order to diagnose compatibility
8678 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008679 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00008680
Richard Smith98a0a492012-02-14 21:38:30 +00008681 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00008682 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008683 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00008684 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +00008685 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +00008686
8687 APValue Scratch;
8688 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
8689
8690 if (!Diags.empty()) {
8691 IsConstExpr = false;
8692 if (Loc) *Loc = Diags[0].first;
8693 } else if (!IsConstExpr) {
8694 // FIXME: This shouldn't happen.
8695 if (Loc) *Loc = getExprLoc();
8696 }
8697
8698 return IsConstExpr;
8699}
Richard Smith253c2a32012-01-27 01:14:48 +00008700
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008701bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
8702 const FunctionDecl *Callee,
8703 llvm::ArrayRef<const Expr*> Args) const {
8704 Expr::EvalStatus Status;
8705 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
8706
8707 ArgVector ArgValues(Args.size());
8708 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
8709 I != E; ++I) {
8710 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
8711 // If evaluation fails, throw away the argument entirely.
8712 ArgValues[I - Args.begin()] = APValue();
8713 if (Info.EvalStatus.HasSideEffects)
8714 return false;
8715 }
8716
8717 // Build fake call to Callee.
8718 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/0,
8719 ArgValues.data());
8720 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
8721}
8722
Richard Smith253c2a32012-01-27 01:14:48 +00008723bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008724 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00008725 PartialDiagnosticAt> &Diags) {
8726 // FIXME: It would be useful to check constexpr function templates, but at the
8727 // moment the constant expression evaluator cannot cope with the non-rigorous
8728 // ASTs which we build for dependent expressions.
8729 if (FD->isDependentContext())
8730 return true;
8731
8732 Expr::EvalStatus Status;
8733 Status.Diag = &Diags;
8734
Richard Smith6d4c6582013-11-05 22:18:15 +00008735 EvalInfo Info(FD->getASTContext(), Status,
8736 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +00008737
8738 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8739 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
8740
Richard Smith7525ff62013-05-09 07:14:00 +00008741 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00008742 // is a temporary being used as the 'this' pointer.
8743 LValue This;
8744 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00008745 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00008746
Richard Smith253c2a32012-01-27 01:14:48 +00008747 ArrayRef<const Expr*> Args;
8748
8749 SourceLocation Loc = FD->getLocation();
8750
Richard Smith2e312c82012-03-03 22:46:17 +00008751 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00008752 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
8753 // Evaluate the call as a constant initializer, to allow the construction
8754 // of objects of non-literal types.
8755 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00008756 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00008757 } else
Richard Smith253c2a32012-01-27 01:14:48 +00008758 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
8759 Args, FD->getBody(), Info, Scratch);
8760
8761 return Diags.empty();
8762}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008763
8764bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
8765 const FunctionDecl *FD,
8766 SmallVectorImpl<
8767 PartialDiagnosticAt> &Diags) {
8768 Expr::EvalStatus Status;
8769 Status.Diag = &Diags;
8770
8771 EvalInfo Info(FD->getASTContext(), Status,
8772 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
8773
8774 // Fabricate a call stack frame to give the arguments a plausible cover story.
8775 ArrayRef<const Expr*> Args;
8776 ArgVector ArgValues(0);
8777 bool Success = EvaluateArgs(Args, ArgValues, Info);
8778 (void)Success;
8779 assert(Success &&
8780 "Failed to set up arguments for potential constant evaluation");
8781 CallStackFrame Frame(Info, SourceLocation(), FD, 0, ArgValues.data());
8782
8783 APValue ResultScratch;
8784 Evaluate(ResultScratch, Info, E);
8785 return Diags.empty();
8786}