blob: a2b5867581fd5b06059d7cdb71a3b449e96a197b [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 }
1366 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1367 I != E; ++I) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001368 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1369 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001370 return false;
1371 }
1372 }
1373
1374 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001375 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001376 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001377 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1378 }
1379
1380 // Everything else is fine.
1381 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001382}
1383
Richard Smith83c68212011-10-31 05:11:32 +00001384const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001385 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001386}
1387
1388static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001389 if (Value.CallIndex)
1390 return false;
1391 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1392 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001393}
1394
Richard Smithcecf1842011-11-01 21:06:14 +00001395static bool IsWeakLValue(const LValue &Value) {
1396 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001397 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001398}
1399
Richard Smith2e312c82012-03-03 22:46:17 +00001400static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001401 // A null base expression indicates a null pointer. These are always
1402 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001403 if (!Value.getLValueBase()) {
1404 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001405 return true;
1406 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001407
Richard Smith027bf112011-11-17 22:56:20 +00001408 // We have a non-null base. These are generally known to be true, but if it's
1409 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001410 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001411 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001412 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001413}
1414
Richard Smith2e312c82012-03-03 22:46:17 +00001415static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001416 switch (Val.getKind()) {
1417 case APValue::Uninitialized:
1418 return false;
1419 case APValue::Int:
1420 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001421 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001422 case APValue::Float:
1423 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001424 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001425 case APValue::ComplexInt:
1426 Result = Val.getComplexIntReal().getBoolValue() ||
1427 Val.getComplexIntImag().getBoolValue();
1428 return true;
1429 case APValue::ComplexFloat:
1430 Result = !Val.getComplexFloatReal().isZero() ||
1431 !Val.getComplexFloatImag().isZero();
1432 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001433 case APValue::LValue:
1434 return EvalPointerValueAsBool(Val, Result);
1435 case APValue::MemberPointer:
1436 Result = Val.getMemberPointerDecl();
1437 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001438 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001439 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001440 case APValue::Struct:
1441 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001442 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001443 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001444 }
1445
Richard Smith11562c52011-10-28 17:51:58 +00001446 llvm_unreachable("unknown APValue kind");
1447}
1448
1449static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1450 EvalInfo &Info) {
1451 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001452 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001453 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001454 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001455 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001456}
1457
Richard Smith357362d2011-12-13 06:39:58 +00001458template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001459static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001460 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001461 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001462 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001463}
1464
1465static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1466 QualType SrcType, const APFloat &Value,
1467 QualType DestType, APSInt &Result) {
1468 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001469 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001470 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001471
Richard Smith357362d2011-12-13 06:39:58 +00001472 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001473 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001474 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1475 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001476 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001477 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001478}
1479
Richard Smith357362d2011-12-13 06:39:58 +00001480static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1481 QualType SrcType, QualType DestType,
1482 APFloat &Result) {
1483 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001484 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001485 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1486 APFloat::rmNearestTiesToEven, &ignored)
1487 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001488 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001489 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001490}
1491
Richard Smith911e1422012-01-30 22:27:01 +00001492static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1493 QualType DestType, QualType SrcType,
1494 APSInt &Value) {
1495 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001496 APSInt Result = Value;
1497 // Figure out if this is a truncate, extend or noop cast.
1498 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001499 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001500 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001501 return Result;
1502}
1503
Richard Smith357362d2011-12-13 06:39:58 +00001504static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1505 QualType SrcType, const APSInt &Value,
1506 QualType DestType, APFloat &Result) {
1507 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1508 if (Result.convertFromAPInt(Value, Value.isSigned(),
1509 APFloat::rmNearestTiesToEven)
1510 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001511 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001512 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001513}
1514
Richard Smith49ca8aa2013-08-06 07:09:20 +00001515static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1516 APValue &Value, const FieldDecl *FD) {
1517 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1518
1519 if (!Value.isInt()) {
1520 // Trying to store a pointer-cast-to-integer into a bitfield.
1521 // FIXME: In this case, we should provide the diagnostic for casting
1522 // a pointer to an integer.
1523 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1524 Info.Diag(E);
1525 return false;
1526 }
1527
1528 APSInt &Int = Value.getInt();
1529 unsigned OldBitWidth = Int.getBitWidth();
1530 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1531 if (NewBitWidth < OldBitWidth)
1532 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1533 return true;
1534}
1535
Eli Friedman803acb32011-12-22 03:51:45 +00001536static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1537 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001538 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001539 if (!Evaluate(SVal, Info, E))
1540 return false;
1541 if (SVal.isInt()) {
1542 Res = SVal.getInt();
1543 return true;
1544 }
1545 if (SVal.isFloat()) {
1546 Res = SVal.getFloat().bitcastToAPInt();
1547 return true;
1548 }
1549 if (SVal.isVector()) {
1550 QualType VecTy = E->getType();
1551 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1552 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1553 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1554 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1555 Res = llvm::APInt::getNullValue(VecSize);
1556 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1557 APValue &Elt = SVal.getVectorElt(i);
1558 llvm::APInt EltAsInt;
1559 if (Elt.isInt()) {
1560 EltAsInt = Elt.getInt();
1561 } else if (Elt.isFloat()) {
1562 EltAsInt = Elt.getFloat().bitcastToAPInt();
1563 } else {
1564 // Don't try to handle vectors of anything other than int or float
1565 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001566 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001567 return false;
1568 }
1569 unsigned BaseEltSize = EltAsInt.getBitWidth();
1570 if (BigEndian)
1571 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1572 else
1573 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1574 }
1575 return true;
1576 }
1577 // Give up if the input isn't an int, float, or vector. For example, we
1578 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001579 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001580 return false;
1581}
1582
Richard Smith43e77732013-05-07 04:50:00 +00001583/// Perform the given integer operation, which is known to need at most BitWidth
1584/// bits, and check for overflow in the original type (if that type was not an
1585/// unsigned type).
1586template<typename Operation>
1587static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1588 const APSInt &LHS, const APSInt &RHS,
1589 unsigned BitWidth, Operation Op) {
1590 if (LHS.isUnsigned())
1591 return Op(LHS, RHS);
1592
1593 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1594 APSInt Result = Value.trunc(LHS.getBitWidth());
1595 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001596 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001597 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1598 diag::warn_integer_constant_overflow)
1599 << Result.toString(10) << E->getType();
1600 else
1601 HandleOverflow(Info, E, Value, E->getType());
1602 }
1603 return Result;
1604}
1605
1606/// Perform the given binary integer operation.
1607static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1608 BinaryOperatorKind Opcode, APSInt RHS,
1609 APSInt &Result) {
1610 switch (Opcode) {
1611 default:
1612 Info.Diag(E);
1613 return false;
1614 case BO_Mul:
1615 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1616 std::multiplies<APSInt>());
1617 return true;
1618 case BO_Add:
1619 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1620 std::plus<APSInt>());
1621 return true;
1622 case BO_Sub:
1623 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1624 std::minus<APSInt>());
1625 return true;
1626 case BO_And: Result = LHS & RHS; return true;
1627 case BO_Xor: Result = LHS ^ RHS; return true;
1628 case BO_Or: Result = LHS | RHS; return true;
1629 case BO_Div:
1630 case BO_Rem:
1631 if (RHS == 0) {
1632 Info.Diag(E, diag::note_expr_divide_by_zero);
1633 return false;
1634 }
1635 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1636 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1637 LHS.isSigned() && LHS.isMinSignedValue())
1638 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1639 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1640 return true;
1641 case BO_Shl: {
1642 if (Info.getLangOpts().OpenCL)
1643 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1644 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1645 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1646 RHS.isUnsigned());
1647 else if (RHS.isSigned() && RHS.isNegative()) {
1648 // During constant-folding, a negative shift is an opposite shift. Such
1649 // a shift is not a constant expression.
1650 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1651 RHS = -RHS;
1652 goto shift_right;
1653 }
1654 shift_left:
1655 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1656 // the shifted type.
1657 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1658 if (SA != RHS) {
1659 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1660 << RHS << E->getType() << LHS.getBitWidth();
1661 } else if (LHS.isSigned()) {
1662 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1663 // operand, and must not overflow the corresponding unsigned type.
1664 if (LHS.isNegative())
1665 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1666 else if (LHS.countLeadingZeros() < SA)
1667 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1668 }
1669 Result = LHS << SA;
1670 return true;
1671 }
1672 case BO_Shr: {
1673 if (Info.getLangOpts().OpenCL)
1674 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1675 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1676 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1677 RHS.isUnsigned());
1678 else if (RHS.isSigned() && RHS.isNegative()) {
1679 // During constant-folding, a negative shift is an opposite shift. Such a
1680 // shift is not a constant expression.
1681 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1682 RHS = -RHS;
1683 goto shift_left;
1684 }
1685 shift_right:
1686 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1687 // shifted type.
1688 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1689 if (SA != RHS)
1690 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1691 << RHS << E->getType() << LHS.getBitWidth();
1692 Result = LHS >> SA;
1693 return true;
1694 }
1695
1696 case BO_LT: Result = LHS < RHS; return true;
1697 case BO_GT: Result = LHS > RHS; return true;
1698 case BO_LE: Result = LHS <= RHS; return true;
1699 case BO_GE: Result = LHS >= RHS; return true;
1700 case BO_EQ: Result = LHS == RHS; return true;
1701 case BO_NE: Result = LHS != RHS; return true;
1702 }
1703}
1704
Richard Smith861b5b52013-05-07 23:34:45 +00001705/// Perform the given binary floating-point operation, in-place, on LHS.
1706static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1707 APFloat &LHS, BinaryOperatorKind Opcode,
1708 const APFloat &RHS) {
1709 switch (Opcode) {
1710 default:
1711 Info.Diag(E);
1712 return false;
1713 case BO_Mul:
1714 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1715 break;
1716 case BO_Add:
1717 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1718 break;
1719 case BO_Sub:
1720 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1721 break;
1722 case BO_Div:
1723 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1724 break;
1725 }
1726
1727 if (LHS.isInfinity() || LHS.isNaN())
1728 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1729 return true;
1730}
1731
Richard Smitha8105bc2012-01-06 16:39:00 +00001732/// Cast an lvalue referring to a base subobject to a derived class, by
1733/// truncating the lvalue's path to the given length.
1734static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1735 const RecordDecl *TruncatedType,
1736 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001737 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001738
1739 // Check we actually point to a derived class object.
1740 if (TruncatedElements == D.Entries.size())
1741 return true;
1742 assert(TruncatedElements >= D.MostDerivedPathLength &&
1743 "not casting to a derived class");
1744 if (!Result.checkSubobject(Info, E, CSK_Derived))
1745 return false;
1746
1747 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001748 const RecordDecl *RD = TruncatedType;
1749 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001750 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001751 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1752 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001753 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001754 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001755 else
Richard Smithd62306a2011-11-10 06:34:14 +00001756 Result.Offset -= Layout.getBaseClassOffset(Base);
1757 RD = Base;
1758 }
Richard Smith027bf112011-11-17 22:56:20 +00001759 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001760 return true;
1761}
1762
John McCalld7bca762012-05-01 00:38:49 +00001763static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001764 const CXXRecordDecl *Derived,
1765 const CXXRecordDecl *Base,
1766 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001767 if (!RL) {
1768 if (Derived->isInvalidDecl()) return false;
1769 RL = &Info.Ctx.getASTRecordLayout(Derived);
1770 }
1771
Richard Smithd62306a2011-11-10 06:34:14 +00001772 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001773 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001774 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001775}
1776
Richard Smitha8105bc2012-01-06 16:39:00 +00001777static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001778 const CXXRecordDecl *DerivedDecl,
1779 const CXXBaseSpecifier *Base) {
1780 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1781
John McCalld7bca762012-05-01 00:38:49 +00001782 if (!Base->isVirtual())
1783 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001784
Richard Smitha8105bc2012-01-06 16:39:00 +00001785 SubobjectDesignator &D = Obj.Designator;
1786 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001787 return false;
1788
Richard Smitha8105bc2012-01-06 16:39:00 +00001789 // Extract most-derived object and corresponding type.
1790 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1791 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1792 return false;
1793
1794 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001795 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001796 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1797 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001798 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001799 return true;
1800}
1801
Richard Smith84401042013-06-03 05:03:02 +00001802static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1803 QualType Type, LValue &Result) {
1804 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1805 PathE = E->path_end();
1806 PathI != PathE; ++PathI) {
1807 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1808 *PathI))
1809 return false;
1810 Type = (*PathI)->getType();
1811 }
1812 return true;
1813}
1814
Richard Smithd62306a2011-11-10 06:34:14 +00001815/// Update LVal to refer to the given field, which must be a member of the type
1816/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001817static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001818 const FieldDecl *FD,
1819 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001820 if (!RL) {
1821 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001822 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001823 }
Richard Smithd62306a2011-11-10 06:34:14 +00001824
1825 unsigned I = FD->getFieldIndex();
1826 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001827 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001828 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001829}
1830
Richard Smith1b78b3d2012-01-25 22:15:11 +00001831/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001832static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001833 LValue &LVal,
1834 const IndirectFieldDecl *IFD) {
Aaron Ballman13916082014-03-07 18:11:58 +00001835 for (const auto *C : IFD->chains())
1836 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00001837 return false;
1838 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001839}
1840
Richard Smithd62306a2011-11-10 06:34:14 +00001841/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001842static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1843 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001844 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1845 // extension.
1846 if (Type->isVoidType() || Type->isFunctionType()) {
1847 Size = CharUnits::One();
1848 return true;
1849 }
1850
1851 if (!Type->isConstantSizeType()) {
1852 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001853 // FIXME: Better diagnostic.
1854 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001855 return false;
1856 }
1857
1858 Size = Info.Ctx.getTypeSizeInChars(Type);
1859 return true;
1860}
1861
1862/// Update a pointer value to model pointer arithmetic.
1863/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001864/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001865/// \param LVal - The pointer value to be updated.
1866/// \param EltTy - The pointee type represented by LVal.
1867/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001868static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1869 LValue &LVal, QualType EltTy,
1870 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001871 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001872 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001873 return false;
1874
1875 // Compute the new offset in the appropriate width.
1876 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001877 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001878 return true;
1879}
1880
Richard Smith66c96992012-02-18 22:04:06 +00001881/// Update an lvalue to refer to a component of a complex number.
1882/// \param Info - Information about the ongoing evaluation.
1883/// \param LVal - The lvalue to be updated.
1884/// \param EltTy - The complex number's component type.
1885/// \param Imag - False for the real component, true for the imaginary.
1886static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1887 LValue &LVal, QualType EltTy,
1888 bool Imag) {
1889 if (Imag) {
1890 CharUnits SizeOfComponent;
1891 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1892 return false;
1893 LVal.Offset += SizeOfComponent;
1894 }
1895 LVal.addComplex(Info, E, EltTy, Imag);
1896 return true;
1897}
1898
Richard Smith27908702011-10-24 17:54:18 +00001899/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001900///
1901/// \param Info Information about the ongoing evaluation.
1902/// \param E An expression to be used when printing diagnostics.
1903/// \param VD The variable whose initializer should be obtained.
1904/// \param Frame The frame in which the variable was created. Must be null
1905/// if this variable is not local to the evaluation.
1906/// \param Result Filled in with a pointer to the value of the variable.
1907static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1908 const VarDecl *VD, CallStackFrame *Frame,
1909 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001910 // If this is a parameter to an active constexpr function call, perform
1911 // argument substitution.
1912 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001913 // Assume arguments of a potential constant expression are unknown
1914 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00001915 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00001916 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001917 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001918 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001919 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001920 }
Richard Smith3229b742013-05-05 21:17:10 +00001921 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00001922 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001923 }
Richard Smith27908702011-10-24 17:54:18 +00001924
Richard Smithd9f663b2013-04-22 15:31:51 +00001925 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00001926 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00001927 Result = Frame->getTemporary(VD);
1928 assert(Result && "missing value for local variable");
1929 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001930 }
1931
Richard Smithd0b4dd62011-12-19 06:19:21 +00001932 // Dig out the initializer, and use the declaration which it's attached to.
1933 const Expr *Init = VD->getAnyInitializer(VD);
1934 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001935 // If we're checking a potential constant expression, the variable could be
1936 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00001937 if (!Info.checkingPotentialConstantExpression())
Richard Smithce1ec5e2012-03-15 04:53:45 +00001938 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001939 return false;
1940 }
1941
Richard Smithd62306a2011-11-10 06:34:14 +00001942 // If we're currently evaluating the initializer of this declaration, use that
1943 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00001944 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00001945 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00001946 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001947 }
1948
Richard Smithcecf1842011-11-01 21:06:14 +00001949 // Never evaluate the initializer of a weak variable. We can't be sure that
1950 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001951 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001952 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001953 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001954 }
Richard Smithcecf1842011-11-01 21:06:14 +00001955
Richard Smithd0b4dd62011-12-19 06:19:21 +00001956 // Check that we can fold the initializer. In C++, we will have already done
1957 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001958 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001959 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001960 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001961 Notes.size() + 1) << VD;
1962 Info.Note(VD->getLocation(), diag::note_declared_at);
1963 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001964 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001965 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001966 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001967 Notes.size() + 1) << VD;
1968 Info.Note(VD->getLocation(), diag::note_declared_at);
1969 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001970 }
Richard Smith27908702011-10-24 17:54:18 +00001971
Richard Smith3229b742013-05-05 21:17:10 +00001972 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001973 return true;
Richard Smith27908702011-10-24 17:54:18 +00001974}
1975
Richard Smith11562c52011-10-28 17:51:58 +00001976static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001977 Qualifiers Quals = T.getQualifiers();
1978 return Quals.hasConst() && !Quals.hasVolatile();
1979}
1980
Richard Smithe97cbd72011-11-11 04:05:33 +00001981/// Get the base index of the given base class within an APValue representing
1982/// the given derived class.
1983static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1984 const CXXRecordDecl *Base) {
1985 Base = Base->getCanonicalDecl();
1986 unsigned Index = 0;
1987 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1988 E = Derived->bases_end(); I != E; ++I, ++Index) {
1989 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1990 return Index;
1991 }
1992
1993 llvm_unreachable("base class missing from derived class's bases list");
1994}
1995
Richard Smith3da88fa2013-04-26 14:36:30 +00001996/// Extract the value of a character from a string literal.
1997static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1998 uint64_t Index) {
Richard Smith14a94132012-02-17 03:35:37 +00001999 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith3da88fa2013-04-26 14:36:30 +00002000 const StringLiteral *S = cast<StringLiteral>(Lit);
2001 const ConstantArrayType *CAT =
2002 Info.Ctx.getAsConstantArrayType(S->getType());
2003 assert(CAT && "string literal isn't an array");
2004 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002005 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002006
2007 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002008 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002009 if (Index < S->getLength())
2010 Value = S->getCodeUnit(Index);
2011 return Value;
2012}
2013
Richard Smith3da88fa2013-04-26 14:36:30 +00002014// Expand a string literal into an array of characters.
2015static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2016 APValue &Result) {
2017 const StringLiteral *S = cast<StringLiteral>(Lit);
2018 const ConstantArrayType *CAT =
2019 Info.Ctx.getAsConstantArrayType(S->getType());
2020 assert(CAT && "string literal isn't an array");
2021 QualType CharType = CAT->getElementType();
2022 assert(CharType->isIntegerType() && "unexpected character type");
2023
2024 unsigned Elts = CAT->getSize().getZExtValue();
2025 Result = APValue(APValue::UninitArray(),
2026 std::min(S->getLength(), Elts), Elts);
2027 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2028 CharType->isUnsignedIntegerType());
2029 if (Result.hasArrayFiller())
2030 Result.getArrayFiller() = APValue(Value);
2031 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2032 Value = S->getCodeUnit(I);
2033 Result.getArrayInitializedElt(I) = APValue(Value);
2034 }
2035}
2036
2037// Expand an array so that it has more than Index filled elements.
2038static void expandArray(APValue &Array, unsigned Index) {
2039 unsigned Size = Array.getArraySize();
2040 assert(Index < Size);
2041
2042 // Always at least double the number of elements for which we store a value.
2043 unsigned OldElts = Array.getArrayInitializedElts();
2044 unsigned NewElts = std::max(Index+1, OldElts * 2);
2045 NewElts = std::min(Size, std::max(NewElts, 8u));
2046
2047 // Copy the data across.
2048 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2049 for (unsigned I = 0; I != OldElts; ++I)
2050 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2051 for (unsigned I = OldElts; I != NewElts; ++I)
2052 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2053 if (NewValue.hasArrayFiller())
2054 NewValue.getArrayFiller() = Array.getArrayFiller();
2055 Array.swap(NewValue);
2056}
2057
Richard Smith861b5b52013-05-07 23:34:45 +00002058/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002059enum AccessKinds {
2060 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002061 AK_Assign,
2062 AK_Increment,
2063 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002064};
2065
Richard Smith3229b742013-05-05 21:17:10 +00002066/// A handle to a complete object (an object that is not a subobject of
2067/// another object).
2068struct CompleteObject {
2069 /// The value of the complete object.
2070 APValue *Value;
2071 /// The type of the complete object.
2072 QualType Type;
2073
2074 CompleteObject() : Value(0) {}
2075 CompleteObject(APValue *Value, QualType Type)
2076 : Value(Value), Type(Type) {
2077 assert(Value && "missing value for complete object");
2078 }
2079
David Blaikie7d170102013-05-15 07:37:26 +00002080 LLVM_EXPLICIT operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002081};
2082
Richard Smith3da88fa2013-04-26 14:36:30 +00002083/// Find the designated sub-object of an rvalue.
2084template<typename SubobjectHandler>
2085typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002086findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002087 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002088 if (Sub.Invalid)
2089 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002090 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002091 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002092 if (Info.getLangOpts().CPlusPlus11)
2093 Info.Diag(E, diag::note_constexpr_access_past_end)
2094 << handler.AccessKind;
2095 else
2096 Info.Diag(E);
2097 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002098 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002099
Richard Smith3229b742013-05-05 21:17:10 +00002100 APValue *O = Obj.Value;
2101 QualType ObjType = Obj.Type;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002102 const FieldDecl *LastField = 0;
2103
Richard Smithd62306a2011-11-10 06:34:14 +00002104 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002105 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2106 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002107 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00002108 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2109 return handler.failed();
2110 }
2111
Richard Smith49ca8aa2013-08-06 07:09:20 +00002112 if (I == N) {
2113 if (!handler.found(*O, ObjType))
2114 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002115
Richard Smith49ca8aa2013-08-06 07:09:20 +00002116 // If we modified a bit-field, truncate it to the right width.
2117 if (handler.AccessKind != AK_Read &&
2118 LastField && LastField->isBitField() &&
2119 !truncateBitfieldValue(Info, E, *O, LastField))
2120 return false;
2121
2122 return true;
2123 }
2124
2125 LastField = 0;
Richard Smithf3e9e432011-11-07 09:22:26 +00002126 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002127 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002128 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002129 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002130 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002131 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002132 // Note, it should not be possible to form a pointer with a valid
2133 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002134 if (Info.getLangOpts().CPlusPlus11)
2135 Info.Diag(E, diag::note_constexpr_access_past_end)
2136 << handler.AccessKind;
2137 else
2138 Info.Diag(E);
2139 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002140 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002141
2142 ObjType = CAT->getElementType();
2143
Richard Smith14a94132012-02-17 03:35:37 +00002144 // An array object is represented as either an Array APValue or as an
2145 // LValue which refers to a string literal.
2146 if (O->isLValue()) {
2147 assert(I == N - 1 && "extracting subobject of character?");
2148 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002149 if (handler.AccessKind != AK_Read)
2150 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2151 *O);
2152 else
2153 return handler.foundString(*O, ObjType, Index);
2154 }
2155
2156 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002157 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002158 else if (handler.AccessKind != AK_Read) {
2159 expandArray(*O, Index);
2160 O = &O->getArrayInitializedElt(Index);
2161 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002162 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002163 } else if (ObjType->isAnyComplexType()) {
2164 // Next subobject is a complex number.
2165 uint64_t Index = Sub.Entries[I].ArrayIndex;
2166 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002167 if (Info.getLangOpts().CPlusPlus11)
2168 Info.Diag(E, diag::note_constexpr_access_past_end)
2169 << handler.AccessKind;
2170 else
2171 Info.Diag(E);
2172 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002173 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002174
2175 bool WasConstQualified = ObjType.isConstQualified();
2176 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2177 if (WasConstQualified)
2178 ObjType.addConst();
2179
Richard Smith66c96992012-02-18 22:04:06 +00002180 assert(I == N - 1 && "extracting subobject of scalar?");
2181 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002182 return handler.found(Index ? O->getComplexIntImag()
2183 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002184 } else {
2185 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002186 return handler.found(Index ? O->getComplexFloatImag()
2187 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002188 }
Richard Smithd62306a2011-11-10 06:34:14 +00002189 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002190 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002191 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002192 << Field;
2193 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002194 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002195 }
2196
Richard Smithd62306a2011-11-10 06:34:14 +00002197 // Next subobject is a class, struct or union field.
2198 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2199 if (RD->isUnion()) {
2200 const FieldDecl *UnionField = O->getUnionField();
2201 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002202 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002203 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2204 << handler.AccessKind << Field << !UnionField << UnionField;
2205 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002206 }
Richard Smithd62306a2011-11-10 06:34:14 +00002207 O = &O->getUnionValue();
2208 } else
2209 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002210
2211 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002212 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002213 if (WasConstQualified && !Field->isMutable())
2214 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002215
2216 if (ObjType.isVolatileQualified()) {
2217 if (Info.getLangOpts().CPlusPlus) {
2218 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00002219 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2220 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002221 Info.Note(Field->getLocation(), diag::note_declared_at);
2222 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002223 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002224 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002225 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002226 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002227
2228 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002229 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002230 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002231 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2232 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2233 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002234
2235 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002236 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002237 if (WasConstQualified)
2238 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002239 }
2240 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002241}
2242
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002243namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002244struct ExtractSubobjectHandler {
2245 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002246 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002247
2248 static const AccessKinds AccessKind = AK_Read;
2249
2250 typedef bool result_type;
2251 bool failed() { return false; }
2252 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002253 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002254 return true;
2255 }
2256 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002257 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002258 return true;
2259 }
2260 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002261 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002262 return true;
2263 }
2264 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002265 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002266 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2267 return true;
2268 }
2269};
Richard Smith3229b742013-05-05 21:17:10 +00002270} // end anonymous namespace
2271
Richard Smith3da88fa2013-04-26 14:36:30 +00002272const AccessKinds ExtractSubobjectHandler::AccessKind;
2273
2274/// Extract the designated sub-object of an rvalue.
2275static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002276 const CompleteObject &Obj,
2277 const SubobjectDesignator &Sub,
2278 APValue &Result) {
2279 ExtractSubobjectHandler Handler = { Info, Result };
2280 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002281}
2282
Richard Smith3229b742013-05-05 21:17:10 +00002283namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002284struct ModifySubobjectHandler {
2285 EvalInfo &Info;
2286 APValue &NewVal;
2287 const Expr *E;
2288
2289 typedef bool result_type;
2290 static const AccessKinds AccessKind = AK_Assign;
2291
2292 bool checkConst(QualType QT) {
2293 // Assigning to a const object has undefined behavior.
2294 if (QT.isConstQualified()) {
2295 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2296 return false;
2297 }
2298 return true;
2299 }
2300
2301 bool failed() { return false; }
2302 bool found(APValue &Subobj, QualType SubobjType) {
2303 if (!checkConst(SubobjType))
2304 return false;
2305 // We've been given ownership of NewVal, so just swap it in.
2306 Subobj.swap(NewVal);
2307 return true;
2308 }
2309 bool found(APSInt &Value, QualType SubobjType) {
2310 if (!checkConst(SubobjType))
2311 return false;
2312 if (!NewVal.isInt()) {
2313 // Maybe trying to write a cast pointer value into a complex?
2314 Info.Diag(E);
2315 return false;
2316 }
2317 Value = NewVal.getInt();
2318 return true;
2319 }
2320 bool found(APFloat &Value, QualType SubobjType) {
2321 if (!checkConst(SubobjType))
2322 return false;
2323 Value = NewVal.getFloat();
2324 return true;
2325 }
2326 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2327 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2328 }
2329};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002330} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002331
Richard Smith3229b742013-05-05 21:17:10 +00002332const AccessKinds ModifySubobjectHandler::AccessKind;
2333
Richard Smith3da88fa2013-04-26 14:36:30 +00002334/// Update the designated sub-object of an rvalue to the given value.
2335static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002336 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002337 const SubobjectDesignator &Sub,
2338 APValue &NewVal) {
2339 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002340 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002341}
2342
Richard Smith84f6dcf2012-02-02 01:16:57 +00002343/// Find the position where two subobject designators diverge, or equivalently
2344/// the length of the common initial subsequence.
2345static unsigned FindDesignatorMismatch(QualType ObjType,
2346 const SubobjectDesignator &A,
2347 const SubobjectDesignator &B,
2348 bool &WasArrayIndex) {
2349 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2350 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002351 if (!ObjType.isNull() &&
2352 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002353 // Next subobject is an array element.
2354 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2355 WasArrayIndex = true;
2356 return I;
2357 }
Richard Smith66c96992012-02-18 22:04:06 +00002358 if (ObjType->isAnyComplexType())
2359 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2360 else
2361 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002362 } else {
2363 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2364 WasArrayIndex = false;
2365 return I;
2366 }
2367 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2368 // Next subobject is a field.
2369 ObjType = FD->getType();
2370 else
2371 // Next subobject is a base class.
2372 ObjType = QualType();
2373 }
2374 }
2375 WasArrayIndex = false;
2376 return I;
2377}
2378
2379/// Determine whether the given subobject designators refer to elements of the
2380/// same array object.
2381static bool AreElementsOfSameArray(QualType ObjType,
2382 const SubobjectDesignator &A,
2383 const SubobjectDesignator &B) {
2384 if (A.Entries.size() != B.Entries.size())
2385 return false;
2386
2387 bool IsArray = A.MostDerivedArraySize != 0;
2388 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2389 // A is a subobject of the array element.
2390 return false;
2391
2392 // If A (and B) designates an array element, the last entry will be the array
2393 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2394 // of length 1' case, and the entire path must match.
2395 bool WasArrayIndex;
2396 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2397 return CommonLength >= A.Entries.size() - IsArray;
2398}
2399
Richard Smith3229b742013-05-05 21:17:10 +00002400/// Find the complete object to which an LValue refers.
2401CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
2402 const LValue &LVal, QualType LValType) {
2403 if (!LVal.Base) {
2404 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2405 return CompleteObject();
2406 }
2407
2408 CallStackFrame *Frame = 0;
2409 if (LVal.CallIndex) {
2410 Frame = Info.getCallFrame(LVal.CallIndex);
2411 if (!Frame) {
2412 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2413 << AK << LVal.Base.is<const ValueDecl*>();
2414 NoteLValueLocation(Info, LVal.Base);
2415 return CompleteObject();
2416 }
Richard Smith3229b742013-05-05 21:17:10 +00002417 }
2418
2419 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2420 // is not a constant expression (even if the object is non-volatile). We also
2421 // apply this rule to C++98, in order to conform to the expected 'volatile'
2422 // semantics.
2423 if (LValType.isVolatileQualified()) {
2424 if (Info.getLangOpts().CPlusPlus)
2425 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2426 << AK << LValType;
2427 else
2428 Info.Diag(E);
2429 return CompleteObject();
2430 }
2431
2432 // Compute value storage location and type of base object.
2433 APValue *BaseVal = 0;
Richard Smith84401042013-06-03 05:03:02 +00002434 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002435
2436 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2437 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2438 // In C++11, constexpr, non-volatile variables initialized with constant
2439 // expressions are constant expressions too. Inside constexpr functions,
2440 // parameters are constant expressions even if they're non-const.
2441 // In C++1y, objects local to a constant expression (those with a Frame) are
2442 // both readable and writable inside constant expressions.
2443 // In C, such things can also be folded, although they are not ICEs.
2444 const VarDecl *VD = dyn_cast<VarDecl>(D);
2445 if (VD) {
2446 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2447 VD = VDef;
2448 }
2449 if (!VD || VD->isInvalidDecl()) {
2450 Info.Diag(E);
2451 return CompleteObject();
2452 }
2453
2454 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002455 if (BaseType.isVolatileQualified()) {
2456 if (Info.getLangOpts().CPlusPlus) {
2457 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2458 << AK << 1 << VD;
2459 Info.Note(VD->getLocation(), diag::note_declared_at);
2460 } else {
2461 Info.Diag(E);
2462 }
2463 return CompleteObject();
2464 }
2465
2466 // Unless we're looking at a local variable or argument in a constexpr call,
2467 // the variable we're reading must be const.
2468 if (!Frame) {
Richard Smith7525ff62013-05-09 07:14:00 +00002469 if (Info.getLangOpts().CPlusPlus1y &&
2470 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2471 // OK, we can read and modify an object if we're in the process of
2472 // evaluating its initializer, because its lifetime began in this
2473 // evaluation.
2474 } else if (AK != AK_Read) {
2475 // All the remaining cases only permit reading.
2476 Info.Diag(E, diag::note_constexpr_modify_global);
2477 return CompleteObject();
2478 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002479 // OK, we can read this variable.
2480 } else if (BaseType->isIntegralOrEnumerationType()) {
2481 if (!BaseType.isConstQualified()) {
2482 if (Info.getLangOpts().CPlusPlus) {
2483 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2484 Info.Note(VD->getLocation(), diag::note_declared_at);
2485 } else {
2486 Info.Diag(E);
2487 }
2488 return CompleteObject();
2489 }
2490 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2491 // We support folding of const floating-point types, in order to make
2492 // static const data members of such types (supported as an extension)
2493 // more useful.
2494 if (Info.getLangOpts().CPlusPlus11) {
2495 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2496 Info.Note(VD->getLocation(), diag::note_declared_at);
2497 } else {
2498 Info.CCEDiag(E);
2499 }
2500 } else {
2501 // FIXME: Allow folding of values of any literal type in all languages.
2502 if (Info.getLangOpts().CPlusPlus11) {
2503 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2504 Info.Note(VD->getLocation(), diag::note_declared_at);
2505 } else {
2506 Info.Diag(E);
2507 }
2508 return CompleteObject();
2509 }
2510 }
2511
2512 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2513 return CompleteObject();
2514 } else {
2515 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2516
2517 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002518 if (const MaterializeTemporaryExpr *MTE =
2519 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2520 assert(MTE->getStorageDuration() == SD_Static &&
2521 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002522
Richard Smithe6c01442013-06-05 00:46:14 +00002523 // Per C++1y [expr.const]p2:
2524 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2525 // - a [...] glvalue of integral or enumeration type that refers to
2526 // a non-volatile const object [...]
2527 // [...]
2528 // - a [...] glvalue of literal type that refers to a non-volatile
2529 // object whose lifetime began within the evaluation of e.
2530 //
2531 // C++11 misses the 'began within the evaluation of e' check and
2532 // instead allows all temporaries, including things like:
2533 // int &&r = 1;
2534 // int x = ++r;
2535 // constexpr int k = r;
2536 // Therefore we use the C++1y rules in C++11 too.
2537 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2538 const ValueDecl *ED = MTE->getExtendingDecl();
2539 if (!(BaseType.isConstQualified() &&
2540 BaseType->isIntegralOrEnumerationType()) &&
2541 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2542 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2543 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2544 return CompleteObject();
2545 }
2546
2547 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2548 assert(BaseVal && "got reference to unevaluated temporary");
2549 } else {
2550 Info.Diag(E);
2551 return CompleteObject();
2552 }
2553 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002554 BaseVal = Frame->getTemporary(Base);
2555 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002556 }
Richard Smith3229b742013-05-05 21:17:10 +00002557
2558 // Volatile temporary objects cannot be accessed in constant expressions.
2559 if (BaseType.isVolatileQualified()) {
2560 if (Info.getLangOpts().CPlusPlus) {
2561 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2562 << AK << 0;
2563 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2564 } else {
2565 Info.Diag(E);
2566 }
2567 return CompleteObject();
2568 }
2569 }
2570
Richard Smith7525ff62013-05-09 07:14:00 +00002571 // During the construction of an object, it is not yet 'const'.
2572 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2573 // and this doesn't do quite the right thing for const subobjects of the
2574 // object under construction.
2575 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2576 BaseType = Info.Ctx.getCanonicalType(BaseType);
2577 BaseType.removeLocalConst();
2578 }
2579
Richard Smith6d4c6582013-11-05 22:18:15 +00002580 // In C++1y, we can't safely access any mutable state when we might be
2581 // evaluating after an unmodeled side effect or an evaluation failure.
2582 //
2583 // FIXME: Not all local state is mutable. Allow local constant subobjects
2584 // to be read here (but take care with 'mutable' fields).
Richard Smith3229b742013-05-05 21:17:10 +00002585 if (Frame && Info.getLangOpts().CPlusPlus1y &&
Richard Smith6d4c6582013-11-05 22:18:15 +00002586 (Info.EvalStatus.HasSideEffects || Info.keepEvaluatingAfterFailure()))
Richard Smith3229b742013-05-05 21:17:10 +00002587 return CompleteObject();
2588
2589 return CompleteObject(BaseVal, BaseType);
2590}
2591
Richard Smith243ef902013-05-05 23:31:59 +00002592/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2593/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2594/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002595///
2596/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002597/// \param Conv - The expression for which we are performing the conversion.
2598/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002599/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2600/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002601/// \param LVal - The glvalue on which we are attempting to perform this action.
2602/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002603static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002604 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002605 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002606 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002607 return false;
2608
Richard Smith3229b742013-05-05 21:17:10 +00002609 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002610 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith3229b742013-05-05 21:17:10 +00002611 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2612 !Type.isVolatileQualified()) {
2613 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2614 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2615 // initializer until now for such expressions. Such an expression can't be
2616 // an ICE in C, so this only matters for fold.
2617 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2618 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002619 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002620 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002621 }
Richard Smith3229b742013-05-05 21:17:10 +00002622 APValue Lit;
2623 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2624 return false;
2625 CompleteObject LitObj(&Lit, Base->getType());
2626 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2627 } else if (isa<StringLiteral>(Base)) {
2628 // We represent a string literal array as an lvalue pointing at the
2629 // corresponding expression, rather than building an array of chars.
2630 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2631 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2632 CompleteObject StrObj(&Str, Base->getType());
2633 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002634 }
Richard Smith11562c52011-10-28 17:51:58 +00002635 }
2636
Richard Smith3229b742013-05-05 21:17:10 +00002637 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2638 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002639}
2640
2641/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002642static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002643 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002644 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002645 return false;
2646
Richard Smith3229b742013-05-05 21:17:10 +00002647 if (!Info.getLangOpts().CPlusPlus1y) {
2648 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002649 return false;
2650 }
2651
Richard Smith3229b742013-05-05 21:17:10 +00002652 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2653 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002654}
2655
Richard Smith243ef902013-05-05 23:31:59 +00002656static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2657 return T->isSignedIntegerType() &&
2658 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2659}
2660
2661namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002662struct CompoundAssignSubobjectHandler {
2663 EvalInfo &Info;
2664 const Expr *E;
2665 QualType PromotedLHSType;
2666 BinaryOperatorKind Opcode;
2667 const APValue &RHS;
2668
2669 static const AccessKinds AccessKind = AK_Assign;
2670
2671 typedef bool result_type;
2672
2673 bool checkConst(QualType QT) {
2674 // Assigning to a const object has undefined behavior.
2675 if (QT.isConstQualified()) {
2676 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2677 return false;
2678 }
2679 return true;
2680 }
2681
2682 bool failed() { return false; }
2683 bool found(APValue &Subobj, QualType SubobjType) {
2684 switch (Subobj.getKind()) {
2685 case APValue::Int:
2686 return found(Subobj.getInt(), SubobjType);
2687 case APValue::Float:
2688 return found(Subobj.getFloat(), SubobjType);
2689 case APValue::ComplexInt:
2690 case APValue::ComplexFloat:
2691 // FIXME: Implement complex compound assignment.
2692 Info.Diag(E);
2693 return false;
2694 case APValue::LValue:
2695 return foundPointer(Subobj, SubobjType);
2696 default:
2697 // FIXME: can this happen?
2698 Info.Diag(E);
2699 return false;
2700 }
2701 }
2702 bool found(APSInt &Value, QualType SubobjType) {
2703 if (!checkConst(SubobjType))
2704 return false;
2705
2706 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2707 // We don't support compound assignment on integer-cast-to-pointer
2708 // values.
2709 Info.Diag(E);
2710 return false;
2711 }
2712
2713 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2714 SubobjType, Value);
2715 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2716 return false;
2717 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2718 return true;
2719 }
2720 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002721 return checkConst(SubobjType) &&
2722 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2723 Value) &&
2724 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2725 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00002726 }
2727 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2728 if (!checkConst(SubobjType))
2729 return false;
2730
2731 QualType PointeeType;
2732 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2733 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00002734
2735 if (PointeeType.isNull() || !RHS.isInt() ||
2736 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00002737 Info.Diag(E);
2738 return false;
2739 }
2740
Richard Smith861b5b52013-05-07 23:34:45 +00002741 int64_t Offset = getExtValue(RHS.getInt());
2742 if (Opcode == BO_Sub)
2743 Offset = -Offset;
2744
2745 LValue LVal;
2746 LVal.setFrom(Info.Ctx, Subobj);
2747 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2748 return false;
2749 LVal.moveInto(Subobj);
2750 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002751 }
2752 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2753 llvm_unreachable("shouldn't encounter string elements here");
2754 }
2755};
2756} // end anonymous namespace
2757
2758const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2759
2760/// Perform a compound assignment of LVal <op>= RVal.
2761static bool handleCompoundAssignment(
2762 EvalInfo &Info, const Expr *E,
2763 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2764 BinaryOperatorKind Opcode, const APValue &RVal) {
2765 if (LVal.Designator.Invalid)
2766 return false;
2767
2768 if (!Info.getLangOpts().CPlusPlus1y) {
2769 Info.Diag(E);
2770 return false;
2771 }
2772
2773 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2774 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2775 RVal };
2776 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2777}
2778
2779namespace {
Richard Smith243ef902013-05-05 23:31:59 +00002780struct IncDecSubobjectHandler {
2781 EvalInfo &Info;
2782 const Expr *E;
2783 AccessKinds AccessKind;
2784 APValue *Old;
2785
2786 typedef bool result_type;
2787
2788 bool checkConst(QualType QT) {
2789 // Assigning to a const object has undefined behavior.
2790 if (QT.isConstQualified()) {
2791 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2792 return false;
2793 }
2794 return true;
2795 }
2796
2797 bool failed() { return false; }
2798 bool found(APValue &Subobj, QualType SubobjType) {
2799 // Stash the old value. Also clear Old, so we don't clobber it later
2800 // if we're post-incrementing a complex.
2801 if (Old) {
2802 *Old = Subobj;
2803 Old = 0;
2804 }
2805
2806 switch (Subobj.getKind()) {
2807 case APValue::Int:
2808 return found(Subobj.getInt(), SubobjType);
2809 case APValue::Float:
2810 return found(Subobj.getFloat(), SubobjType);
2811 case APValue::ComplexInt:
2812 return found(Subobj.getComplexIntReal(),
2813 SubobjType->castAs<ComplexType>()->getElementType()
2814 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2815 case APValue::ComplexFloat:
2816 return found(Subobj.getComplexFloatReal(),
2817 SubobjType->castAs<ComplexType>()->getElementType()
2818 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2819 case APValue::LValue:
2820 return foundPointer(Subobj, SubobjType);
2821 default:
2822 // FIXME: can this happen?
2823 Info.Diag(E);
2824 return false;
2825 }
2826 }
2827 bool found(APSInt &Value, QualType SubobjType) {
2828 if (!checkConst(SubobjType))
2829 return false;
2830
2831 if (!SubobjType->isIntegerType()) {
2832 // We don't support increment / decrement on integer-cast-to-pointer
2833 // values.
2834 Info.Diag(E);
2835 return false;
2836 }
2837
2838 if (Old) *Old = APValue(Value);
2839
2840 // bool arithmetic promotes to int, and the conversion back to bool
2841 // doesn't reduce mod 2^n, so special-case it.
2842 if (SubobjType->isBooleanType()) {
2843 if (AccessKind == AK_Increment)
2844 Value = 1;
2845 else
2846 Value = !Value;
2847 return true;
2848 }
2849
2850 bool WasNegative = Value.isNegative();
2851 if (AccessKind == AK_Increment) {
2852 ++Value;
2853
2854 if (!WasNegative && Value.isNegative() &&
2855 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2856 APSInt ActualValue(Value, /*IsUnsigned*/true);
2857 HandleOverflow(Info, E, ActualValue, SubobjType);
2858 }
2859 } else {
2860 --Value;
2861
2862 if (WasNegative && !Value.isNegative() &&
2863 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2864 unsigned BitWidth = Value.getBitWidth();
2865 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2866 ActualValue.setBit(BitWidth);
2867 HandleOverflow(Info, E, ActualValue, SubobjType);
2868 }
2869 }
2870 return true;
2871 }
2872 bool found(APFloat &Value, QualType SubobjType) {
2873 if (!checkConst(SubobjType))
2874 return false;
2875
2876 if (Old) *Old = APValue(Value);
2877
2878 APFloat One(Value.getSemantics(), 1);
2879 if (AccessKind == AK_Increment)
2880 Value.add(One, APFloat::rmNearestTiesToEven);
2881 else
2882 Value.subtract(One, APFloat::rmNearestTiesToEven);
2883 return true;
2884 }
2885 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2886 if (!checkConst(SubobjType))
2887 return false;
2888
2889 QualType PointeeType;
2890 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2891 PointeeType = PT->getPointeeType();
2892 else {
2893 Info.Diag(E);
2894 return false;
2895 }
2896
2897 LValue LVal;
2898 LVal.setFrom(Info.Ctx, Subobj);
2899 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2900 AccessKind == AK_Increment ? 1 : -1))
2901 return false;
2902 LVal.moveInto(Subobj);
2903 return true;
2904 }
2905 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2906 llvm_unreachable("shouldn't encounter string elements here");
2907 }
2908};
2909} // end anonymous namespace
2910
2911/// Perform an increment or decrement on LVal.
2912static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
2913 QualType LValType, bool IsIncrement, APValue *Old) {
2914 if (LVal.Designator.Invalid)
2915 return false;
2916
2917 if (!Info.getLangOpts().CPlusPlus1y) {
2918 Info.Diag(E);
2919 return false;
2920 }
2921
2922 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
2923 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
2924 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
2925 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2926}
2927
Richard Smithe97cbd72011-11-11 04:05:33 +00002928/// Build an lvalue for the object argument of a member function call.
2929static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2930 LValue &This) {
2931 if (Object->getType()->isPointerType())
2932 return EvaluatePointer(Object, This, Info);
2933
2934 if (Object->isGLValue())
2935 return EvaluateLValue(Object, This, Info);
2936
Richard Smithd9f663b2013-04-22 15:31:51 +00002937 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00002938 return EvaluateTemporary(Object, This, Info);
2939
2940 return false;
2941}
2942
2943/// HandleMemberPointerAccess - Evaluate a member access operation and build an
2944/// lvalue referring to the result.
2945///
2946/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00002947/// \param LV - An lvalue referring to the base of the member pointer.
2948/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00002949/// \param IncludeMember - Specifies whether the member itself is included in
2950/// the resulting LValue subobject designator. This is not possible when
2951/// creating a bound member function.
2952/// \return The field or method declaration to which the member pointer refers,
2953/// or 0 if evaluation fails.
2954static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00002955 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00002956 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00002957 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00002958 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00002959 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00002960 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Richard Smith027bf112011-11-17 22:56:20 +00002961 return 0;
2962
2963 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2964 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00002965 if (!MemPtr.getDecl()) {
2966 // FIXME: Specific diagnostic.
2967 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002968 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002969 }
Richard Smith253c2a32012-01-27 01:14:48 +00002970
Richard Smith027bf112011-11-17 22:56:20 +00002971 if (MemPtr.isDerivedMember()) {
2972 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00002973 // The end of the derived-to-base path for the base object must match the
2974 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00002975 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00002976 LV.Designator.Entries.size()) {
2977 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002978 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002979 }
Richard Smith027bf112011-11-17 22:56:20 +00002980 unsigned PathLengthToMember =
2981 LV.Designator.Entries.size() - MemPtr.Path.size();
2982 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
2983 const CXXRecordDecl *LVDecl = getAsBaseClass(
2984 LV.Designator.Entries[PathLengthToMember + I]);
2985 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00002986 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
2987 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002988 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002989 }
Richard Smith027bf112011-11-17 22:56:20 +00002990 }
2991
2992 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00002993 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00002994 PathLengthToMember))
2995 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002996 } else if (!MemPtr.Path.empty()) {
2997 // Extend the LValue path with the member pointer's path.
2998 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
2999 MemPtr.Path.size() + IncludeMember);
3000
3001 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003002 if (const PointerType *PT = LVType->getAs<PointerType>())
3003 LVType = PT->getPointeeType();
3004 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3005 assert(RD && "member pointer access on non-class-type expression");
3006 // The first class in the path is that of the lvalue.
3007 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3008 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003009 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
John McCalld7bca762012-05-01 00:38:49 +00003010 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00003011 RD = Base;
3012 }
3013 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003014 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3015 MemPtr.getContainingRecord()))
John McCalld7bca762012-05-01 00:38:49 +00003016 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00003017 }
3018
3019 // Add the member. Note that we cannot build bound member functions here.
3020 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003021 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003022 if (!HandleLValueMember(Info, RHS, LV, FD))
John McCalld7bca762012-05-01 00:38:49 +00003023 return 0;
3024 } else if (const IndirectFieldDecl *IFD =
3025 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003026 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
John McCalld7bca762012-05-01 00:38:49 +00003027 return 0;
3028 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003029 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003030 }
Richard Smith027bf112011-11-17 22:56:20 +00003031 }
3032
3033 return MemPtr.getDecl();
3034}
3035
Richard Smith84401042013-06-03 05:03:02 +00003036static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3037 const BinaryOperator *BO,
3038 LValue &LV,
3039 bool IncludeMember = true) {
3040 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3041
3042 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3043 if (Info.keepEvaluatingAfterFailure()) {
3044 MemberPtr MemPtr;
3045 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3046 }
3047 return 0;
3048 }
3049
3050 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3051 BO->getRHS(), IncludeMember);
3052}
3053
Richard Smith027bf112011-11-17 22:56:20 +00003054/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3055/// the provided lvalue, which currently refers to the base object.
3056static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3057 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003058 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003059 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003060 return false;
3061
Richard Smitha8105bc2012-01-06 16:39:00 +00003062 QualType TargetQT = E->getType();
3063 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3064 TargetQT = PT->getPointeeType();
3065
3066 // Check this cast lands within the final derived-to-base subobject path.
3067 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003068 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003069 << D.MostDerivedType << TargetQT;
3070 return false;
3071 }
3072
Richard Smith027bf112011-11-17 22:56:20 +00003073 // Check the type of the final cast. We don't need to check the path,
3074 // since a cast can only be formed if the path is unique.
3075 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003076 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3077 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003078 if (NewEntriesSize == D.MostDerivedPathLength)
3079 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3080 else
Richard Smith027bf112011-11-17 22:56:20 +00003081 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003082 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003083 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003084 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003085 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003086 }
Richard Smith027bf112011-11-17 22:56:20 +00003087
3088 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003089 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003090}
3091
Mike Stump876387b2009-10-27 22:09:17 +00003092namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003093enum EvalStmtResult {
3094 /// Evaluation failed.
3095 ESR_Failed,
3096 /// Hit a 'return' statement.
3097 ESR_Returned,
3098 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003099 ESR_Succeeded,
3100 /// Hit a 'continue' statement.
3101 ESR_Continue,
3102 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003103 ESR_Break,
3104 /// Still scanning for 'case' or 'default' statement.
3105 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003106};
3107}
3108
Richard Smithd9f663b2013-04-22 15:31:51 +00003109static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3110 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3111 // We don't need to evaluate the initializer for a static local.
3112 if (!VD->hasLocalStorage())
3113 return true;
3114
3115 LValue Result;
3116 Result.set(VD, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003117 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003118
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003119 const Expr *InitE = VD->getInit();
3120 if (!InitE) {
Richard Smith51f03172013-06-20 03:00:05 +00003121 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3122 << false << VD->getType();
3123 Val = APValue();
3124 return false;
3125 }
3126
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003127 if (InitE->isValueDependent())
3128 return false;
3129
3130 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003131 // Wipe out any partially-computed value, to allow tracking that this
3132 // evaluation failed.
3133 Val = APValue();
3134 return false;
3135 }
3136 }
3137
3138 return true;
3139}
3140
Richard Smith4e18ca52013-05-06 05:56:11 +00003141/// Evaluate a condition (either a variable declaration or an expression).
3142static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3143 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003144 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003145 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3146 return false;
3147 return EvaluateAsBooleanCondition(Cond, Result, Info);
3148}
3149
3150static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003151 const Stmt *S, const SwitchCase *SC = 0);
Richard Smith4e18ca52013-05-06 05:56:11 +00003152
3153/// Evaluate the body of a loop, and translate the result as appropriate.
3154static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003155 const Stmt *Body,
3156 const SwitchCase *Case = 0) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003157 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003158 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003159 case ESR_Break:
3160 return ESR_Succeeded;
3161 case ESR_Succeeded:
3162 case ESR_Continue:
3163 return ESR_Continue;
3164 case ESR_Failed:
3165 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003166 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003167 return ESR;
3168 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003169 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003170}
3171
Richard Smith496ddcf2013-05-12 17:32:42 +00003172/// Evaluate a switch statement.
3173static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
3174 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003175 BlockScopeRAII Scope(Info);
3176
Richard Smith496ddcf2013-05-12 17:32:42 +00003177 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003178 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003179 {
3180 FullExpressionRAII Scope(Info);
3181 if (SS->getConditionVariable() &&
3182 !EvaluateDecl(Info, SS->getConditionVariable()))
3183 return ESR_Failed;
3184 if (!EvaluateInteger(SS->getCond(), Value, Info))
3185 return ESR_Failed;
3186 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003187
3188 // Find the switch case corresponding to the value of the condition.
3189 // FIXME: Cache this lookup.
3190 const SwitchCase *Found = 0;
3191 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3192 SC = SC->getNextSwitchCase()) {
3193 if (isa<DefaultStmt>(SC)) {
3194 Found = SC;
3195 continue;
3196 }
3197
3198 const CaseStmt *CS = cast<CaseStmt>(SC);
3199 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3200 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3201 : LHS;
3202 if (LHS <= Value && Value <= RHS) {
3203 Found = SC;
3204 break;
3205 }
3206 }
3207
3208 if (!Found)
3209 return ESR_Succeeded;
3210
3211 // Search the switch body for the switch case and evaluate it from there.
3212 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3213 case ESR_Break:
3214 return ESR_Succeeded;
3215 case ESR_Succeeded:
3216 case ESR_Continue:
3217 case ESR_Failed:
3218 case ESR_Returned:
3219 return ESR;
3220 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003221 // This can only happen if the switch case is nested within a statement
3222 // expression. We have no intention of supporting that.
3223 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3224 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003225 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003226 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003227}
3228
Richard Smith254a73d2011-10-28 22:34:42 +00003229// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00003230static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003231 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003232 if (!Info.nextStep(S))
3233 return ESR_Failed;
3234
Richard Smith496ddcf2013-05-12 17:32:42 +00003235 // If we're hunting down a 'case' or 'default' label, recurse through
3236 // substatements until we hit the label.
3237 if (Case) {
3238 // FIXME: We don't start the lifetime of objects whose initialization we
3239 // jump over. However, such objects must be of class type with a trivial
3240 // default constructor that initialize all subobjects, so must be empty,
3241 // so this almost never matters.
3242 switch (S->getStmtClass()) {
3243 case Stmt::CompoundStmtClass:
3244 // FIXME: Precompute which substatement of a compound statement we
3245 // would jump to, and go straight there rather than performing a
3246 // linear scan each time.
3247 case Stmt::LabelStmtClass:
3248 case Stmt::AttributedStmtClass:
3249 case Stmt::DoStmtClass:
3250 break;
3251
3252 case Stmt::CaseStmtClass:
3253 case Stmt::DefaultStmtClass:
3254 if (Case == S)
3255 Case = 0;
3256 break;
3257
3258 case Stmt::IfStmtClass: {
3259 // FIXME: Precompute which side of an 'if' we would jump to, and go
3260 // straight there rather than scanning both sides.
3261 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003262
3263 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3264 // preceded by our switch label.
3265 BlockScopeRAII Scope(Info);
3266
Richard Smith496ddcf2013-05-12 17:32:42 +00003267 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3268 if (ESR != ESR_CaseNotFound || !IS->getElse())
3269 return ESR;
3270 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3271 }
3272
3273 case Stmt::WhileStmtClass: {
3274 EvalStmtResult ESR =
3275 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3276 if (ESR != ESR_Continue)
3277 return ESR;
3278 break;
3279 }
3280
3281 case Stmt::ForStmtClass: {
3282 const ForStmt *FS = cast<ForStmt>(S);
3283 EvalStmtResult ESR =
3284 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3285 if (ESR != ESR_Continue)
3286 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003287 if (FS->getInc()) {
3288 FullExpressionRAII IncScope(Info);
3289 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3290 return ESR_Failed;
3291 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003292 break;
3293 }
3294
3295 case Stmt::DeclStmtClass:
3296 // FIXME: If the variable has initialization that can't be jumped over,
3297 // bail out of any immediately-surrounding compound-statement too.
3298 default:
3299 return ESR_CaseNotFound;
3300 }
3301 }
3302
Richard Smith254a73d2011-10-28 22:34:42 +00003303 switch (S->getStmtClass()) {
3304 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003305 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003306 // Don't bother evaluating beyond an expression-statement which couldn't
3307 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003308 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003309 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003310 return ESR_Failed;
3311 return ESR_Succeeded;
3312 }
3313
3314 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003315 return ESR_Failed;
3316
3317 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003318 return ESR_Succeeded;
3319
Richard Smithd9f663b2013-04-22 15:31:51 +00003320 case Stmt::DeclStmtClass: {
3321 const DeclStmt *DS = cast<DeclStmt>(S);
3322 for (DeclStmt::const_decl_iterator DclIt = DS->decl_begin(),
Richard Smith08d6a2c2013-07-24 07:11:57 +00003323 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
3324 // Each declaration initialization is its own full-expression.
3325 // FIXME: This isn't quite right; if we're performing aggregate
3326 // initialization, each braced subexpression is its own full-expression.
3327 FullExpressionRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003328 if (!EvaluateDecl(Info, *DclIt) && !Info.keepEvaluatingAfterFailure())
3329 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003330 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003331 return ESR_Succeeded;
3332 }
3333
Richard Smith357362d2011-12-13 06:39:58 +00003334 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003335 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003336 FullExpressionRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003337 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00003338 return ESR_Failed;
3339 return ESR_Returned;
3340 }
Richard Smith254a73d2011-10-28 22:34:42 +00003341
3342 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003343 BlockScopeRAII Scope(Info);
3344
Richard Smith254a73d2011-10-28 22:34:42 +00003345 const CompoundStmt *CS = cast<CompoundStmt>(S);
3346 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
3347 BE = CS->body_end(); BI != BE; ++BI) {
Richard Smith496ddcf2013-05-12 17:32:42 +00003348 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI, Case);
3349 if (ESR == ESR_Succeeded)
3350 Case = 0;
3351 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003352 return ESR;
3353 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003354 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003355 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003356
3357 case Stmt::IfStmtClass: {
3358 const IfStmt *IS = cast<IfStmt>(S);
3359
3360 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003361 BlockScopeRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003362 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003363 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003364 return ESR_Failed;
3365
3366 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3367 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3368 if (ESR != ESR_Succeeded)
3369 return ESR;
3370 }
3371 return ESR_Succeeded;
3372 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003373
3374 case Stmt::WhileStmtClass: {
3375 const WhileStmt *WS = cast<WhileStmt>(S);
3376 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003377 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003378 bool Continue;
3379 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3380 Continue))
3381 return ESR_Failed;
3382 if (!Continue)
3383 break;
3384
3385 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3386 if (ESR != ESR_Continue)
3387 return ESR;
3388 }
3389 return ESR_Succeeded;
3390 }
3391
3392 case Stmt::DoStmtClass: {
3393 const DoStmt *DS = cast<DoStmt>(S);
3394 bool Continue;
3395 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003396 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003397 if (ESR != ESR_Continue)
3398 return ESR;
Richard Smith496ddcf2013-05-12 17:32:42 +00003399 Case = 0;
Richard Smith4e18ca52013-05-06 05:56:11 +00003400
Richard Smith08d6a2c2013-07-24 07:11:57 +00003401 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003402 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3403 return ESR_Failed;
3404 } while (Continue);
3405 return ESR_Succeeded;
3406 }
3407
3408 case Stmt::ForStmtClass: {
3409 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003410 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003411 if (FS->getInit()) {
3412 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3413 if (ESR != ESR_Succeeded)
3414 return ESR;
3415 }
3416 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003417 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003418 bool Continue = true;
3419 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3420 FS->getCond(), Continue))
3421 return ESR_Failed;
3422 if (!Continue)
3423 break;
3424
3425 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3426 if (ESR != ESR_Continue)
3427 return ESR;
3428
Richard Smith08d6a2c2013-07-24 07:11:57 +00003429 if (FS->getInc()) {
3430 FullExpressionRAII IncScope(Info);
3431 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3432 return ESR_Failed;
3433 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003434 }
3435 return ESR_Succeeded;
3436 }
3437
Richard Smith896e0d72013-05-06 06:51:17 +00003438 case Stmt::CXXForRangeStmtClass: {
3439 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003440 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003441
3442 // Initialize the __range variable.
3443 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3444 if (ESR != ESR_Succeeded)
3445 return ESR;
3446
3447 // Create the __begin and __end iterators.
3448 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3449 if (ESR != ESR_Succeeded)
3450 return ESR;
3451
3452 while (true) {
3453 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003454 {
3455 bool Continue = true;
3456 FullExpressionRAII CondExpr(Info);
3457 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3458 return ESR_Failed;
3459 if (!Continue)
3460 break;
3461 }
Richard Smith896e0d72013-05-06 06:51:17 +00003462
3463 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003464 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003465 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3466 if (ESR != ESR_Succeeded)
3467 return ESR;
3468
3469 // Loop body.
3470 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3471 if (ESR != ESR_Continue)
3472 return ESR;
3473
3474 // Increment: ++__begin
3475 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3476 return ESR_Failed;
3477 }
3478
3479 return ESR_Succeeded;
3480 }
3481
Richard Smith496ddcf2013-05-12 17:32:42 +00003482 case Stmt::SwitchStmtClass:
3483 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3484
Richard Smith4e18ca52013-05-06 05:56:11 +00003485 case Stmt::ContinueStmtClass:
3486 return ESR_Continue;
3487
3488 case Stmt::BreakStmtClass:
3489 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003490
3491 case Stmt::LabelStmtClass:
3492 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3493
3494 case Stmt::AttributedStmtClass:
3495 // As a general principle, C++11 attributes can be ignored without
3496 // any semantic impact.
3497 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3498 Case);
3499
3500 case Stmt::CaseStmtClass:
3501 case Stmt::DefaultStmtClass:
3502 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003503 }
3504}
3505
Richard Smithcc36f692011-12-22 02:22:31 +00003506/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3507/// default constructor. If so, we'll fold it whether or not it's marked as
3508/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3509/// so we need special handling.
3510static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003511 const CXXConstructorDecl *CD,
3512 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003513 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3514 return false;
3515
Richard Smith66e05fe2012-01-18 05:21:49 +00003516 // Value-initialization does not call a trivial default constructor, so such a
3517 // call is a core constant expression whether or not the constructor is
3518 // constexpr.
3519 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003520 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003521 // FIXME: If DiagDecl is an implicitly-declared special member function,
3522 // we should be much more explicit about why it's not constexpr.
3523 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3524 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3525 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003526 } else {
3527 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3528 }
3529 }
3530 return true;
3531}
3532
Richard Smith357362d2011-12-13 06:39:58 +00003533/// CheckConstexprFunction - Check that a function can be called in a constant
3534/// expression.
3535static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3536 const FunctionDecl *Declaration,
3537 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00003538 // Potential constant expressions can contain calls to declared, but not yet
3539 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00003540 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00003541 Declaration->isConstexpr())
3542 return false;
3543
Richard Smith0838f3a2013-05-14 05:18:44 +00003544 // Bail out with no diagnostic if the function declaration itself is invalid.
3545 // We will have produced a relevant diagnostic while parsing it.
3546 if (Declaration->isInvalidDecl())
3547 return false;
3548
Richard Smith357362d2011-12-13 06:39:58 +00003549 // Can we evaluate this function call?
3550 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3551 return true;
3552
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003553 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003554 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003555 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3556 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003557 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3558 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3559 << DiagDecl;
3560 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3561 } else {
3562 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3563 }
3564 return false;
3565}
3566
Richard Smithd62306a2011-11-10 06:34:14 +00003567namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003568typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003569}
3570
3571/// EvaluateArgs - Evaluate the arguments to a function call.
3572static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3573 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003574 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003575 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003576 I != E; ++I) {
3577 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3578 // If we're checking for a potential constant expression, evaluate all
3579 // initializers even if some of them fail.
3580 if (!Info.keepEvaluatingAfterFailure())
3581 return false;
3582 Success = false;
3583 }
3584 }
3585 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003586}
3587
Richard Smith254a73d2011-10-28 22:34:42 +00003588/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003589static bool HandleFunctionCall(SourceLocation CallLoc,
3590 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003591 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00003592 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003593 ArgVector ArgValues(Args.size());
3594 if (!EvaluateArgs(Args, ArgValues, Info))
3595 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003596
Richard Smith253c2a32012-01-27 01:14:48 +00003597 if (!Info.CheckCallLimit(CallLoc))
3598 return false;
3599
3600 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003601
3602 // For a trivial copy or move assignment, perform an APValue copy. This is
3603 // essential for unions, where the operations performed by the assignment
3604 // operator cannot be represented as statements.
3605 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3606 if (MD && MD->isDefaulted() && MD->isTrivial()) {
3607 assert(This &&
3608 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3609 LValue RHS;
3610 RHS.setFrom(Info.Ctx, ArgValues[0]);
3611 APValue RHSValue;
3612 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3613 RHS, RHSValue))
3614 return false;
3615 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3616 RHSValue))
3617 return false;
3618 This->moveInto(Result);
3619 return true;
3620 }
3621
Richard Smithd9f663b2013-04-22 15:31:51 +00003622 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003623 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00003624 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00003625 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003626 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003627 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003628 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003629}
3630
Richard Smithd62306a2011-11-10 06:34:14 +00003631/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003632static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003633 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003634 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003635 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003636 ArgVector ArgValues(Args.size());
3637 if (!EvaluateArgs(Args, ArgValues, Info))
3638 return false;
3639
Richard Smith253c2a32012-01-27 01:14:48 +00003640 if (!Info.CheckCallLimit(CallLoc))
3641 return false;
3642
Richard Smith3607ffe2012-02-13 03:54:03 +00003643 const CXXRecordDecl *RD = Definition->getParent();
3644 if (RD->getNumVBases()) {
3645 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3646 return false;
3647 }
3648
Richard Smith253c2a32012-01-27 01:14:48 +00003649 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003650
3651 // If it's a delegating constructor, just delegate.
3652 if (Definition->isDelegatingConstructor()) {
3653 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00003654 {
3655 FullExpressionRAII InitScope(Info);
3656 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3657 return false;
3658 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003659 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003660 }
3661
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003662 // For a trivial copy or move constructor, perform an APValue copy. This is
3663 // essential for unions, where the operations performed by the constructor
3664 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003665 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00003666 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3667 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003668 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003669 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003670 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003671 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003672 }
3673
3674 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003675 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003676 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3677 std::distance(RD->field_begin(), RD->field_end()));
3678
John McCalld7bca762012-05-01 00:38:49 +00003679 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003680 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3681
Richard Smith08d6a2c2013-07-24 07:11:57 +00003682 // A scope for temporaries lifetime-extended by reference members.
3683 BlockScopeRAII LifetimeExtendedScope(Info);
3684
Richard Smith253c2a32012-01-27 01:14:48 +00003685 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003686 unsigned BasesSeen = 0;
3687#ifndef NDEBUG
3688 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3689#endif
3690 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
3691 E = Definition->init_end(); I != E; ++I) {
Richard Smith253c2a32012-01-27 01:14:48 +00003692 LValue Subobject = This;
3693 APValue *Value = &Result;
3694
3695 // Determine the subobject to initialize.
Richard Smith49ca8aa2013-08-06 07:09:20 +00003696 FieldDecl *FD = 0;
Richard Smithd62306a2011-11-10 06:34:14 +00003697 if ((*I)->isBaseInitializer()) {
3698 QualType BaseType((*I)->getBaseClass(), 0);
3699#ifndef NDEBUG
3700 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003701 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003702 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3703 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3704 "base class initializers not in expected order");
3705 ++BaseIt;
3706#endif
John McCalld7bca762012-05-01 00:38:49 +00003707 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
3708 BaseType->getAsCXXRecordDecl(), &Layout))
3709 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003710 Value = &Result.getStructBase(BasesSeen++);
Richard Smith49ca8aa2013-08-06 07:09:20 +00003711 } else if ((FD = (*I)->getMember())) {
John McCalld7bca762012-05-01 00:38:49 +00003712 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
3713 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003714 if (RD->isUnion()) {
3715 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003716 Value = &Result.getUnionValue();
3717 } else {
3718 Value = &Result.getStructField(FD->getFieldIndex());
3719 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00003720 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003721 // Walk the indirect field decl's chain to find the object to initialize,
3722 // and make sure we've initialized every step along it.
Aaron Ballman13916082014-03-07 18:11:58 +00003723 for (auto *C : IFD->chains()) {
3724 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00003725 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3726 // Switch the union field if it differs. This happens if we had
3727 // preceding zero-initialization, and we're now initializing a union
3728 // subobject other than the first.
3729 // FIXME: In this case, the values of the other subobjects are
3730 // specified, since zero-initialization sets all padding bits to zero.
3731 if (Value->isUninit() ||
3732 (Value->isUnion() && Value->getUnionField() != FD)) {
3733 if (CD->isUnion())
3734 *Value = APValue(FD);
3735 else
3736 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
3737 std::distance(CD->field_begin(), CD->field_end()));
3738 }
John McCalld7bca762012-05-01 00:38:49 +00003739 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
3740 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003741 if (CD->isUnion())
3742 Value = &Value->getUnionValue();
3743 else
3744 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00003745 }
Richard Smithd62306a2011-11-10 06:34:14 +00003746 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003747 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00003748 }
Richard Smith253c2a32012-01-27 01:14:48 +00003749
Richard Smith08d6a2c2013-07-24 07:11:57 +00003750 FullExpressionRAII InitScope(Info);
Richard Smith49ca8aa2013-08-06 07:09:20 +00003751 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit()) ||
3752 (FD && FD->isBitField() && !truncateBitfieldValue(Info, (*I)->getInit(),
3753 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00003754 // If we're checking for a potential constant expression, evaluate all
3755 // initializers even if some of them fail.
3756 if (!Info.keepEvaluatingAfterFailure())
3757 return false;
3758 Success = false;
3759 }
Richard Smithd62306a2011-11-10 06:34:14 +00003760 }
3761
Richard Smithd9f663b2013-04-22 15:31:51 +00003762 return Success &&
3763 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003764}
3765
Eli Friedman9a156e52008-11-12 09:44:48 +00003766//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00003767// Generic Evaluation
3768//===----------------------------------------------------------------------===//
3769namespace {
3770
Aaron Ballman68af21c2014-01-03 19:26:43 +00003771template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00003772class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00003773 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00003774private:
Aaron Ballman68af21c2014-01-03 19:26:43 +00003775 bool DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003776 return static_cast<Derived*>(this)->Success(V, E);
3777 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003778 bool DerivedZeroInitialization(const Expr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003779 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003780 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003781
Richard Smith17100ba2012-02-16 02:46:34 +00003782 // Check whether a conditional operator with a non-constant condition is a
3783 // potential constant expression. If neither arm is a potential constant
3784 // expression, then the conditional operator is not either.
3785 template<typename ConditionalOperator>
3786 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003787 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00003788
3789 // Speculatively evaluate both arms.
3790 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003791 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00003792 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3793
3794 StmtVisitorTy::Visit(E->getFalseExpr());
3795 if (Diag.empty())
3796 return;
3797
3798 Diag.clear();
3799 StmtVisitorTy::Visit(E->getTrueExpr());
3800 if (Diag.empty())
3801 return;
3802 }
3803
3804 Error(E, diag::note_constexpr_conditional_never_const);
3805 }
3806
3807
3808 template<typename ConditionalOperator>
3809 bool HandleConditionalOperator(const ConditionalOperator *E) {
3810 bool BoolResult;
3811 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003812 if (Info.checkingPotentialConstantExpression())
Richard Smith17100ba2012-02-16 02:46:34 +00003813 CheckPotentialConstantConditional(E);
3814 return false;
3815 }
3816
3817 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3818 return StmtVisitorTy::Visit(EvalExpr);
3819 }
3820
Peter Collingbournee9200682011-05-13 03:29:01 +00003821protected:
3822 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00003823 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00003824 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3825
Richard Smith92b1ce02011-12-12 09:28:41 +00003826 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003827 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003828 }
3829
Aaron Ballman68af21c2014-01-03 19:26:43 +00003830 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003831
3832public:
3833 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3834
3835 EvalInfo &getEvalInfo() { return Info; }
3836
Richard Smithf57d8cb2011-12-09 22:58:01 +00003837 /// Report an evaluation error. This should only be called when an error is
3838 /// first discovered. When propagating an error, just return false.
3839 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003840 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003841 return false;
3842 }
3843 bool Error(const Expr *E) {
3844 return Error(E, diag::note_invalid_subexpr_in_const_expr);
3845 }
3846
Aaron Ballman68af21c2014-01-03 19:26:43 +00003847 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00003848 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00003849 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003850 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003851 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003852 }
3853
Aaron Ballman68af21c2014-01-03 19:26:43 +00003854 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003855 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003856 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003857 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003858 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003859 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003860 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00003861 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003862 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003863 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003864 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00003865 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003866 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00003867 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003868 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00003869 // The initializer may not have been parsed yet, or might be erroneous.
3870 if (!E->getExpr())
3871 return Error(E);
3872 return StmtVisitorTy::Visit(E->getExpr());
3873 }
Richard Smith5894a912011-12-19 22:12:41 +00003874 // We cannot create any objects for which cleanups are required, so there is
3875 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00003876 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00003877 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003878
Aaron Ballman68af21c2014-01-03 19:26:43 +00003879 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00003880 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3881 return static_cast<Derived*>(this)->VisitCastExpr(E);
3882 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003883 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00003884 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3885 return static_cast<Derived*>(this)->VisitCastExpr(E);
3886 }
3887
Aaron Ballman68af21c2014-01-03 19:26:43 +00003888 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003889 switch (E->getOpcode()) {
3890 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003891 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003892
3893 case BO_Comma:
3894 VisitIgnoredValue(E->getLHS());
3895 return StmtVisitorTy::Visit(E->getRHS());
3896
3897 case BO_PtrMemD:
3898 case BO_PtrMemI: {
3899 LValue Obj;
3900 if (!HandleMemberPointerAccess(Info, E, Obj))
3901 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003902 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00003903 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00003904 return false;
3905 return DerivedSuccess(Result, E);
3906 }
3907 }
3908 }
3909
Aaron Ballman68af21c2014-01-03 19:26:43 +00003910 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003911 // Evaluate and cache the common expression. We treat it as a temporary,
3912 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003913 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00003914 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003915 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00003916
Richard Smith17100ba2012-02-16 02:46:34 +00003917 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003918 }
3919
Aaron Ballman68af21c2014-01-03 19:26:43 +00003920 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003921 bool IsBcpCall = false;
3922 // If the condition (ignoring parens) is a __builtin_constant_p call,
3923 // the result is a constant expression if it can be folded without
3924 // side-effects. This is an important GNU extension. See GCC PR38377
3925 // for discussion.
3926 if (const CallExpr *CallCE =
3927 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00003928 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00003929 IsBcpCall = true;
3930
3931 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3932 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00003933 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00003934 return false;
3935
Richard Smith6d4c6582013-11-05 22:18:15 +00003936 FoldConstant Fold(Info, IsBcpCall);
3937 if (!HandleConditionalOperator(E)) {
3938 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003939 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00003940 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00003941
3942 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00003943 }
3944
Aaron Ballman68af21c2014-01-03 19:26:43 +00003945 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003946 if (APValue *Value = Info.CurrentCall->getTemporary(E))
3947 return DerivedSuccess(*Value, E);
3948
3949 const Expr *Source = E->getSourceExpr();
3950 if (!Source)
3951 return Error(E);
3952 if (Source == E) { // sanity checking.
3953 assert(0 && "OpaqueValueExpr recursively refers to itself");
3954 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003955 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003956 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00003957 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003958
Aaron Ballman68af21c2014-01-03 19:26:43 +00003959 bool VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003960 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00003961 QualType CalleeType = Callee->getType();
3962
Richard Smith254a73d2011-10-28 22:34:42 +00003963 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00003964 LValue *This = 0, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003965 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00003966 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00003967
Richard Smithe97cbd72011-11-11 04:05:33 +00003968 // Extract function decl and 'this' pointer from the callee.
3969 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003970 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00003971 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3972 // Explicit bound member calls, such as x.f() or p->g();
3973 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003974 return false;
3975 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00003976 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00003977 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00003978 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
3979 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00003980 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
3981 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00003982 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00003983 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003984 return Error(Callee);
3985
3986 FD = dyn_cast<FunctionDecl>(Member);
3987 if (!FD)
3988 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003989 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003990 LValue Call;
3991 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003992 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00003993
Richard Smitha8105bc2012-01-06 16:39:00 +00003994 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003995 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00003996 FD = dyn_cast_or_null<FunctionDecl>(
3997 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00003998 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003999 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004000
4001 // Overloaded operator calls to member functions are represented as normal
4002 // calls with '*this' as the first argument.
4003 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4004 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004005 // FIXME: When selecting an implicit conversion for an overloaded
4006 // operator delete, we sometimes try to evaluate calls to conversion
4007 // operators without a 'this' parameter!
4008 if (Args.empty())
4009 return Error(E);
4010
Richard Smithe97cbd72011-11-11 04:05:33 +00004011 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4012 return false;
4013 This = &ThisVal;
4014 Args = Args.slice(1);
4015 }
4016
4017 // Don't call function pointers which have been cast to some other type.
4018 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004019 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00004020 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004021 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004022
Richard Smith47b34932012-02-01 02:39:43 +00004023 if (This && !This->checkSubobject(Info, E, CSK_This))
4024 return false;
4025
Richard Smith3607ffe2012-02-13 03:54:03 +00004026 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4027 // calls to such functions in constant expressions.
4028 if (This && !HasQualifier &&
4029 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4030 return Error(E, diag::note_constexpr_virtual_call);
4031
Richard Smith357362d2011-12-13 06:39:58 +00004032 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00004033 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00004034 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00004035
Richard Smith357362d2011-12-13 06:39:58 +00004036 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00004037 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
4038 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004039 return false;
4040
Richard Smithb228a862012-02-15 02:18:13 +00004041 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00004042 }
4043
Aaron Ballman68af21c2014-01-03 19:26:43 +00004044 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004045 return StmtVisitorTy::Visit(E->getInitializer());
4046 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004047 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004048 if (E->getNumInits() == 0)
4049 return DerivedZeroInitialization(E);
4050 if (E->getNumInits() == 1)
4051 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004052 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004053 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004054 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *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 VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004058 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004059 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004060 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004061 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004062 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004063
Richard Smithd62306a2011-11-10 06:34:14 +00004064 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004065 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004066 assert(!E->isArrow() && "missing call to bound member function?");
4067
Richard Smith2e312c82012-03-03 22:46:17 +00004068 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004069 if (!Evaluate(Val, Info, E->getBase()))
4070 return false;
4071
4072 QualType BaseTy = E->getBase()->getType();
4073
4074 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004075 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004076 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004077 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004078 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4079
Richard Smith3229b742013-05-05 21:17:10 +00004080 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004081 SubobjectDesignator Designator(BaseTy);
4082 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004083
Richard Smith3229b742013-05-05 21:17:10 +00004084 APValue Result;
4085 return extractSubobject(Info, E, Obj, Designator, Result) &&
4086 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004087 }
4088
Aaron Ballman68af21c2014-01-03 19:26:43 +00004089 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004090 switch (E->getCastKind()) {
4091 default:
4092 break;
4093
Richard Smitha23ab512013-05-23 00:30:41 +00004094 case CK_AtomicToNonAtomic: {
4095 APValue AtomicVal;
4096 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4097 return false;
4098 return DerivedSuccess(AtomicVal, E);
4099 }
4100
Richard Smith11562c52011-10-28 17:51:58 +00004101 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004102 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004103 return StmtVisitorTy::Visit(E->getSubExpr());
4104
4105 case CK_LValueToRValue: {
4106 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004107 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4108 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004109 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004110 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004111 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004112 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004113 return false;
4114 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004115 }
4116 }
4117
Richard Smithf57d8cb2011-12-09 22:58:01 +00004118 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004119 }
4120
Aaron Ballman68af21c2014-01-03 19:26:43 +00004121 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004122 return VisitUnaryPostIncDec(UO);
4123 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004124 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004125 return VisitUnaryPostIncDec(UO);
4126 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004127 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004128 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4129 return Error(UO);
4130
4131 LValue LVal;
4132 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4133 return false;
4134 APValue RVal;
4135 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4136 UO->isIncrementOp(), &RVal))
4137 return false;
4138 return DerivedSuccess(RVal, UO);
4139 }
4140
Aaron Ballman68af21c2014-01-03 19:26:43 +00004141 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004142 // We will have checked the full-expressions inside the statement expression
4143 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004144 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004145 return Error(E);
4146
Richard Smith08d6a2c2013-07-24 07:11:57 +00004147 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004148 const CompoundStmt *CS = E->getSubStmt();
4149 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4150 BE = CS->body_end();
4151 /**/; ++BI) {
4152 if (BI + 1 == BE) {
4153 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4154 if (!FinalExpr) {
4155 Info.Diag((*BI)->getLocStart(),
4156 diag::note_constexpr_stmt_expr_unsupported);
4157 return false;
4158 }
4159 return this->Visit(FinalExpr);
4160 }
4161
4162 APValue ReturnValue;
4163 EvalStmtResult ESR = EvaluateStmt(ReturnValue, Info, *BI);
4164 if (ESR != ESR_Succeeded) {
4165 // FIXME: If the statement-expression terminated due to 'return',
4166 // 'break', or 'continue', it would be nice to propagate that to
4167 // the outer statement evaluation rather than bailing out.
4168 if (ESR != ESR_Failed)
4169 Info.Diag((*BI)->getLocStart(),
4170 diag::note_constexpr_stmt_expr_unsupported);
4171 return false;
4172 }
4173 }
4174 }
4175
Richard Smith4a678122011-10-24 18:44:57 +00004176 /// Visit a value which is evaluated, but whose value is ignored.
4177 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004178 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004179 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004180};
4181
4182}
4183
4184//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004185// Common base class for lvalue and temporary evaluation.
4186//===----------------------------------------------------------------------===//
4187namespace {
4188template<class Derived>
4189class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004190 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004191protected:
4192 LValue &Result;
4193 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004194 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004195
4196 bool Success(APValue::LValueBase B) {
4197 Result.set(B);
4198 return true;
4199 }
4200
4201public:
4202 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4203 ExprEvaluatorBaseTy(Info), Result(Result) {}
4204
Richard Smith2e312c82012-03-03 22:46:17 +00004205 bool Success(const APValue &V, const Expr *E) {
4206 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004207 return true;
4208 }
Richard Smith027bf112011-11-17 22:56:20 +00004209
Richard Smith027bf112011-11-17 22:56:20 +00004210 bool VisitMemberExpr(const MemberExpr *E) {
4211 // Handle non-static data members.
4212 QualType BaseTy;
4213 if (E->isArrow()) {
4214 if (!EvaluatePointer(E->getBase(), Result, this->Info))
4215 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00004216 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004217 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004218 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00004219 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
4220 return false;
4221 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004222 } else {
4223 if (!this->Visit(E->getBase()))
4224 return false;
4225 BaseTy = E->getBase()->getType();
4226 }
Richard Smith027bf112011-11-17 22:56:20 +00004227
Richard Smith1b78b3d2012-01-25 22:15:11 +00004228 const ValueDecl *MD = E->getMemberDecl();
4229 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4230 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4231 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4232 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004233 if (!HandleLValueMember(this->Info, E, Result, FD))
4234 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004235 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004236 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4237 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004238 } else
4239 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004240
Richard Smith1b78b3d2012-01-25 22:15:11 +00004241 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004242 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004243 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004244 RefValue))
4245 return false;
4246 return Success(RefValue, E);
4247 }
4248 return true;
4249 }
4250
4251 bool VisitBinaryOperator(const BinaryOperator *E) {
4252 switch (E->getOpcode()) {
4253 default:
4254 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4255
4256 case BO_PtrMemD:
4257 case BO_PtrMemI:
4258 return HandleMemberPointerAccess(this->Info, E, Result);
4259 }
4260 }
4261
4262 bool VisitCastExpr(const CastExpr *E) {
4263 switch (E->getCastKind()) {
4264 default:
4265 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4266
4267 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004268 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004269 if (!this->Visit(E->getSubExpr()))
4270 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004271
4272 // Now figure out the necessary offset to add to the base LV to get from
4273 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004274 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4275 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004276 }
4277 }
4278};
4279}
4280
4281//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004282// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004283//
4284// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4285// function designators (in C), decl references to void objects (in C), and
4286// temporaries (if building with -Wno-address-of-temporary).
4287//
4288// LValue evaluation produces values comprising a base expression of one of the
4289// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004290// - Declarations
4291// * VarDecl
4292// * FunctionDecl
4293// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00004294// * CompoundLiteralExpr in C
4295// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004296// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004297// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004298// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004299// * ObjCEncodeExpr
4300// * AddrLabelExpr
4301// * BlockExpr
4302// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004303// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004304// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004305// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004306// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4307// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004308// * A MaterializeTemporaryExpr that has static storage duration, with no
4309// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004310// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004311//===----------------------------------------------------------------------===//
4312namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004313class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004314 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004315public:
Richard Smith027bf112011-11-17 22:56:20 +00004316 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4317 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004318
Richard Smith11562c52011-10-28 17:51:58 +00004319 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004320 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004321
Peter Collingbournee9200682011-05-13 03:29:01 +00004322 bool VisitDeclRefExpr(const DeclRefExpr *E);
4323 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004324 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004325 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4326 bool VisitMemberExpr(const MemberExpr *E);
4327 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4328 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004329 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004330 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004331 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4332 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004333 bool VisitUnaryReal(const UnaryOperator *E);
4334 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004335 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4336 return VisitUnaryPreIncDec(UO);
4337 }
4338 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4339 return VisitUnaryPreIncDec(UO);
4340 }
Richard Smith3229b742013-05-05 21:17:10 +00004341 bool VisitBinAssign(const BinaryOperator *BO);
4342 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004343
Peter Collingbournee9200682011-05-13 03:29:01 +00004344 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004345 switch (E->getCastKind()) {
4346 default:
Richard Smith027bf112011-11-17 22:56:20 +00004347 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004348
Eli Friedmance3e02a2011-10-11 00:13:24 +00004349 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004350 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004351 if (!Visit(E->getSubExpr()))
4352 return false;
4353 Result.Designator.setInvalid();
4354 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004355
Richard Smith027bf112011-11-17 22:56:20 +00004356 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004357 if (!Visit(E->getSubExpr()))
4358 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004359 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004360 }
4361 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004362};
4363} // end anonymous namespace
4364
Richard Smith11562c52011-10-28 17:51:58 +00004365/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smith9f8400e2013-05-01 19:00:39 +00004366/// expressions which are not glvalues, in two cases:
4367/// * function designators in C, and
4368/// * "extern void" objects
4369static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4370 assert(E->isGLValue() || E->getType()->isFunctionType() ||
4371 E->getType()->isVoidType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004372 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004373}
4374
Peter Collingbournee9200682011-05-13 03:29:01 +00004375bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004376 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
4377 return Success(FD);
4378 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004379 return VisitVarDecl(E, VD);
4380 return Error(E);
4381}
Richard Smith733237d2011-10-24 23:14:33 +00004382
Richard Smith11562c52011-10-28 17:51:58 +00004383bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith3229b742013-05-05 21:17:10 +00004384 CallStackFrame *Frame = 0;
4385 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4386 Frame = Info.CurrentCall;
4387
Richard Smithfec09922011-11-01 16:57:24 +00004388 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004389 if (Frame) {
4390 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004391 return true;
4392 }
Richard Smithce40ad62011-11-12 22:28:03 +00004393 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004394 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004395
Richard Smith3229b742013-05-05 21:17:10 +00004396 APValue *V;
4397 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004398 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004399 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004400 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004401 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4402 return false;
4403 }
Richard Smith3229b742013-05-05 21:17:10 +00004404 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004405}
4406
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004407bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4408 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004409 // Walk through the expression to find the materialized temporary itself.
4410 SmallVector<const Expr *, 2> CommaLHSs;
4411 SmallVector<SubobjectAdjustment, 2> Adjustments;
4412 const Expr *Inner = E->GetTemporaryExpr()->
4413 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004414
Richard Smith84401042013-06-03 05:03:02 +00004415 // If we passed any comma operators, evaluate their LHSs.
4416 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4417 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4418 return false;
4419
Richard Smithe6c01442013-06-05 00:46:14 +00004420 // A materialized temporary with static storage duration can appear within the
4421 // result of a constant expression evaluation, so we need to preserve its
4422 // value for use outside this evaluation.
4423 APValue *Value;
4424 if (E->getStorageDuration() == SD_Static) {
4425 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004426 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004427 Result.set(E);
4428 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004429 Value = &Info.CurrentCall->
4430 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00004431 Result.set(E, Info.CurrentCall->Index);
4432 }
4433
Richard Smithea4ad5d2013-06-06 08:19:16 +00004434 QualType Type = Inner->getType();
4435
Richard Smith84401042013-06-03 05:03:02 +00004436 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004437 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4438 (E->getStorageDuration() == SD_Static &&
4439 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4440 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004441 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004442 }
Richard Smith84401042013-06-03 05:03:02 +00004443
4444 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004445 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4446 --I;
4447 switch (Adjustments[I].Kind) {
4448 case SubobjectAdjustment::DerivedToBaseAdjustment:
4449 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4450 Type, Result))
4451 return false;
4452 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4453 break;
4454
4455 case SubobjectAdjustment::FieldAdjustment:
4456 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4457 return false;
4458 Type = Adjustments[I].Field->getType();
4459 break;
4460
4461 case SubobjectAdjustment::MemberPointerAdjustment:
4462 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4463 Adjustments[I].Ptr.RHS))
4464 return false;
4465 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4466 break;
4467 }
4468 }
4469
4470 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004471}
4472
Peter Collingbournee9200682011-05-13 03:29:01 +00004473bool
4474LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004475 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4476 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4477 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004478 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004479}
4480
Richard Smith6e525142011-12-27 12:18:28 +00004481bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004482 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004483 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004484
4485 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4486 << E->getExprOperand()->getType()
4487 << E->getExprOperand()->getSourceRange();
4488 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004489}
4490
Francois Pichet0066db92012-04-16 04:08:35 +00004491bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4492 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004493}
Francois Pichet0066db92012-04-16 04:08:35 +00004494
Peter Collingbournee9200682011-05-13 03:29:01 +00004495bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004496 // Handle static data members.
4497 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4498 VisitIgnoredValue(E->getBase());
4499 return VisitVarDecl(E, VD);
4500 }
4501
Richard Smith254a73d2011-10-28 22:34:42 +00004502 // Handle static member functions.
4503 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4504 if (MD->isStatic()) {
4505 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004506 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004507 }
4508 }
4509
Richard Smithd62306a2011-11-10 06:34:14 +00004510 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004511 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004512}
4513
Peter Collingbournee9200682011-05-13 03:29:01 +00004514bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004515 // FIXME: Deal with vectors as array subscript bases.
4516 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004517 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004518
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004519 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004520 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004521
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004522 APSInt Index;
4523 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004524 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004525
Richard Smith861b5b52013-05-07 23:34:45 +00004526 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4527 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004528}
Eli Friedman9a156e52008-11-12 09:44:48 +00004529
Peter Collingbournee9200682011-05-13 03:29:01 +00004530bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004531 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004532}
4533
Richard Smith66c96992012-02-18 22:04:06 +00004534bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4535 if (!Visit(E->getSubExpr()))
4536 return false;
4537 // __real is a no-op on scalar lvalues.
4538 if (E->getSubExpr()->getType()->isAnyComplexType())
4539 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4540 return true;
4541}
4542
4543bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4544 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4545 "lvalue __imag__ on scalar?");
4546 if (!Visit(E->getSubExpr()))
4547 return false;
4548 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4549 return true;
4550}
4551
Richard Smith243ef902013-05-05 23:31:59 +00004552bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4553 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004554 return Error(UO);
4555
4556 if (!this->Visit(UO->getSubExpr()))
4557 return false;
4558
Richard Smith243ef902013-05-05 23:31:59 +00004559 return handleIncDec(
4560 this->Info, UO, Result, UO->getSubExpr()->getType(),
4561 UO->isIncrementOp(), 0);
Richard Smith3229b742013-05-05 21:17:10 +00004562}
4563
4564bool LValueExprEvaluator::VisitCompoundAssignOperator(
4565 const CompoundAssignOperator *CAO) {
Richard Smith243ef902013-05-05 23:31:59 +00004566 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004567 return Error(CAO);
4568
Richard Smith3229b742013-05-05 21:17:10 +00004569 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004570
4571 // The overall lvalue result is the result of evaluating the LHS.
4572 if (!this->Visit(CAO->getLHS())) {
4573 if (Info.keepEvaluatingAfterFailure())
4574 Evaluate(RHS, this->Info, CAO->getRHS());
4575 return false;
4576 }
4577
Richard Smith3229b742013-05-05 21:17:10 +00004578 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4579 return false;
4580
Richard Smith43e77732013-05-07 04:50:00 +00004581 return handleCompoundAssignment(
4582 this->Info, CAO,
4583 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4584 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004585}
4586
4587bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Richard Smith243ef902013-05-05 23:31:59 +00004588 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4589 return Error(E);
4590
Richard Smith3229b742013-05-05 21:17:10 +00004591 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004592
4593 if (!this->Visit(E->getLHS())) {
4594 if (Info.keepEvaluatingAfterFailure())
4595 Evaluate(NewVal, this->Info, E->getRHS());
4596 return false;
4597 }
4598
Richard Smith3229b742013-05-05 21:17:10 +00004599 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4600 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004601
4602 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004603 NewVal);
4604}
4605
Eli Friedman9a156e52008-11-12 09:44:48 +00004606//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004607// Pointer Evaluation
4608//===----------------------------------------------------------------------===//
4609
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004610namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004611class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004612 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00004613 LValue &Result;
4614
Peter Collingbournee9200682011-05-13 03:29:01 +00004615 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004616 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004617 return true;
4618 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004619public:
Mike Stump11289f42009-09-09 15:08:12 +00004620
John McCall45d55e42010-05-07 21:00:08 +00004621 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004622 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004623
Richard Smith2e312c82012-03-03 22:46:17 +00004624 bool Success(const APValue &V, const Expr *E) {
4625 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004626 return true;
4627 }
Richard Smithfddd3842011-12-30 21:15:51 +00004628 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00004629 return Success((Expr*)0);
4630 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004631
John McCall45d55e42010-05-07 21:00:08 +00004632 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004633 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004634 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004635 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004636 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004637 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00004638 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004639 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004640 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004641 bool VisitCallExpr(const CallExpr *E);
4642 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004643 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004644 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004645 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004646 }
Richard Smithd62306a2011-11-10 06:34:14 +00004647 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004648 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00004649 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00004650 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004651 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004652 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004653 Result = *Info.CurrentCall->This;
4654 return true;
4655 }
John McCallc07a0c72011-02-17 10:25:35 +00004656
Eli Friedman449fe542009-03-23 04:56:01 +00004657 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004658};
Chris Lattner05706e882008-07-11 18:11:29 +00004659} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004660
John McCall45d55e42010-05-07 21:00:08 +00004661static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004662 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004663 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004664}
4665
John McCall45d55e42010-05-07 21:00:08 +00004666bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004667 if (E->getOpcode() != BO_Add &&
4668 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004669 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004670
Chris Lattner05706e882008-07-11 18:11:29 +00004671 const Expr *PExp = E->getLHS();
4672 const Expr *IExp = E->getRHS();
4673 if (IExp->getType()->isPointerType())
4674 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004675
Richard Smith253c2a32012-01-27 01:14:48 +00004676 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4677 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004678 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004679
John McCall45d55e42010-05-07 21:00:08 +00004680 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004681 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004682 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004683
4684 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004685 if (E->getOpcode() == BO_Sub)
4686 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004687
Ted Kremenek28831752012-08-23 20:46:57 +00004688 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004689 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4690 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004691}
Eli Friedman9a156e52008-11-12 09:44:48 +00004692
John McCall45d55e42010-05-07 21:00:08 +00004693bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4694 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004695}
Mike Stump11289f42009-09-09 15:08:12 +00004696
Peter Collingbournee9200682011-05-13 03:29:01 +00004697bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4698 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004699
Eli Friedman847a2bc2009-12-27 05:43:15 +00004700 switch (E->getCastKind()) {
4701 default:
4702 break;
4703
John McCalle3027922010-08-25 11:45:40 +00004704 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004705 case CK_CPointerToObjCPointerCast:
4706 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004707 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004708 if (!Visit(SubExpr))
4709 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004710 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4711 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4712 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004713 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004714 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004715 if (SubExpr->getType()->isVoidPointerType())
4716 CCEDiag(E, diag::note_constexpr_invalid_cast)
4717 << 3 << SubExpr->getType();
4718 else
4719 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4720 }
Richard Smith96e0c102011-11-04 02:25:55 +00004721 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004722
Anders Carlsson18275092010-10-31 20:41:46 +00004723 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004724 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00004725 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004726 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004727 if (!Result.Base && Result.Offset.isZero())
4728 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00004729
Richard Smithd62306a2011-11-10 06:34:14 +00004730 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00004731 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004732 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4733 castAs<PointerType>()->getPointeeType(),
4734 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00004735
Richard Smith027bf112011-11-17 22:56:20 +00004736 case CK_BaseToDerived:
4737 if (!Visit(E->getSubExpr()))
4738 return false;
4739 if (!Result.Base && Result.Offset.isZero())
4740 return true;
4741 return HandleBaseToDerivedCast(Info, E, Result);
4742
Richard Smith0b0a0b62011-10-29 20:57:55 +00004743 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004744 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004745 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00004746
John McCalle3027922010-08-25 11:45:40 +00004747 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004748 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4749
Richard Smith2e312c82012-03-03 22:46:17 +00004750 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00004751 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00004752 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00004753
John McCall45d55e42010-05-07 21:00:08 +00004754 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004755 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4756 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00004757 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004758 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00004759 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00004760 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004761 return true;
4762 } else {
4763 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00004764 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00004765 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00004766 }
4767 }
John McCalle3027922010-08-25 11:45:40 +00004768 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00004769 if (SubExpr->isGLValue()) {
4770 if (!EvaluateLValue(SubExpr, Result, Info))
4771 return false;
4772 } else {
Richard Smithb228a862012-02-15 02:18:13 +00004773 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004774 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00004775 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00004776 return false;
4777 }
Richard Smith96e0c102011-11-04 02:25:55 +00004778 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00004779 if (const ConstantArrayType *CAT
4780 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4781 Result.addArray(Info, E, CAT);
4782 else
4783 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00004784 return true;
Richard Smithdd785442011-10-31 20:57:44 +00004785
John McCalle3027922010-08-25 11:45:40 +00004786 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00004787 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004788 }
4789
Richard Smith11562c52011-10-28 17:51:58 +00004790 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00004791}
Chris Lattner05706e882008-07-11 18:11:29 +00004792
Peter Collingbournee9200682011-05-13 03:29:01 +00004793bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004794 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00004795 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00004796
Alp Tokera724cff2013-12-28 21:59:02 +00004797 switch (E->getBuiltinCallee()) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00004798 case Builtin::BI__builtin_addressof:
4799 return EvaluateLValue(E->getArg(0), Result, Info);
4800
4801 default:
4802 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4803 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004804}
Chris Lattner05706e882008-07-11 18:11:29 +00004805
4806//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004807// Member Pointer Evaluation
4808//===----------------------------------------------------------------------===//
4809
4810namespace {
4811class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004812 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00004813 MemberPtr &Result;
4814
4815 bool Success(const ValueDecl *D) {
4816 Result = MemberPtr(D);
4817 return true;
4818 }
4819public:
4820
4821 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
4822 : ExprEvaluatorBaseTy(Info), Result(Result) {}
4823
Richard Smith2e312c82012-03-03 22:46:17 +00004824 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004825 Result.setFrom(V);
4826 return true;
4827 }
Richard Smithfddd3842011-12-30 21:15:51 +00004828 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004829 return Success((const ValueDecl*)0);
4830 }
4831
4832 bool VisitCastExpr(const CastExpr *E);
4833 bool VisitUnaryAddrOf(const UnaryOperator *E);
4834};
4835} // end anonymous namespace
4836
4837static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
4838 EvalInfo &Info) {
4839 assert(E->isRValue() && E->getType()->isMemberPointerType());
4840 return MemberPointerExprEvaluator(Info, Result).Visit(E);
4841}
4842
4843bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
4844 switch (E->getCastKind()) {
4845 default:
4846 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4847
4848 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004849 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004850 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004851
4852 case CK_BaseToDerivedMemberPointer: {
4853 if (!Visit(E->getSubExpr()))
4854 return false;
4855 if (E->path_empty())
4856 return true;
4857 // Base-to-derived member pointer casts store the path in derived-to-base
4858 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
4859 // the wrong end of the derived->base arc, so stagger the path by one class.
4860 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
4861 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
4862 PathI != PathE; ++PathI) {
4863 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4864 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
4865 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004866 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004867 }
4868 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
4869 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004870 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004871 return true;
4872 }
4873
4874 case CK_DerivedToBaseMemberPointer:
4875 if (!Visit(E->getSubExpr()))
4876 return false;
4877 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4878 PathE = E->path_end(); PathI != PathE; ++PathI) {
4879 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4880 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4881 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004882 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004883 }
4884 return true;
4885 }
4886}
4887
4888bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4889 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
4890 // member can be formed.
4891 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
4892}
4893
4894//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00004895// Record Evaluation
4896//===----------------------------------------------------------------------===//
4897
4898namespace {
4899 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004900 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00004901 const LValue &This;
4902 APValue &Result;
4903 public:
4904
4905 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
4906 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
4907
Richard Smith2e312c82012-03-03 22:46:17 +00004908 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004909 Result = V;
4910 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00004911 }
Richard Smithfddd3842011-12-30 21:15:51 +00004912 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004913
Richard Smithe97cbd72011-11-11 04:05:33 +00004914 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004915 bool VisitInitListExpr(const InitListExpr *E);
4916 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc1b96d2013-06-12 22:31:48 +00004917 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004918 };
4919}
4920
Richard Smithfddd3842011-12-30 21:15:51 +00004921/// Perform zero-initialization on an object of non-union class type.
4922/// C++11 [dcl.init]p5:
4923/// To zero-initialize an object or reference of type T means:
4924/// [...]
4925/// -- if T is a (possibly cv-qualified) non-union class type,
4926/// each non-static data member and each base-class subobject is
4927/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00004928static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
4929 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00004930 const LValue &This, APValue &Result) {
4931 assert(!RD->isUnion() && "Expected non-union class type");
4932 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
4933 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
4934 std::distance(RD->field_begin(), RD->field_end()));
4935
John McCalld7bca762012-05-01 00:38:49 +00004936 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004937 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4938
4939 if (CD) {
4940 unsigned Index = 0;
4941 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00004942 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00004943 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4944 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004945 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4946 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004947 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00004948 Result.getStructBase(Index)))
4949 return false;
4950 }
4951 }
4952
Richard Smitha8105bc2012-01-06 16:39:00 +00004953 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
4954 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00004955 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004956 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00004957 continue;
4958
4959 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004960 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004961 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004962
David Blaikie2d7c57e2012-04-30 02:36:29 +00004963 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004964 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00004965 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004966 return false;
4967 }
4968
4969 return true;
4970}
4971
4972bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
4973 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004974 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004975 if (RD->isUnion()) {
4976 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4977 // object's first non-static named data member is zero-initialized
4978 RecordDecl::field_iterator I = RD->field_begin();
4979 if (I == RD->field_end()) {
4980 Result = APValue((const FieldDecl*)0);
4981 return true;
4982 }
4983
4984 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004985 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00004986 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00004987 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00004988 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004989 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004990 }
4991
Richard Smith5d108602012-02-17 00:44:16 +00004992 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004993 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00004994 return false;
4995 }
4996
Richard Smitha8105bc2012-01-06 16:39:00 +00004997 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00004998}
4999
Richard Smithe97cbd72011-11-11 04:05:33 +00005000bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5001 switch (E->getCastKind()) {
5002 default:
5003 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5004
5005 case CK_ConstructorConversion:
5006 return Visit(E->getSubExpr());
5007
5008 case CK_DerivedToBase:
5009 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00005010 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005011 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00005012 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005013 if (!DerivedObject.isStruct())
5014 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00005015
5016 // Derived-to-base rvalue conversion: just slice off the derived part.
5017 APValue *Value = &DerivedObject;
5018 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5019 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5020 PathE = E->path_end(); PathI != PathE; ++PathI) {
5021 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5022 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5023 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5024 RD = Base;
5025 }
5026 Result = *Value;
5027 return true;
5028 }
5029 }
5030}
5031
Richard Smithd62306a2011-11-10 06:34:14 +00005032bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5033 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005034 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005035 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5036
5037 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005038 const FieldDecl *Field = E->getInitializedFieldInUnion();
5039 Result = APValue(Field);
5040 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005041 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005042
5043 // If the initializer list for a union does not contain any elements, the
5044 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005045 // FIXME: The element should be initialized from an initializer list.
5046 // Is this difference ever observable for initializer lists which
5047 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005048 ImplicitValueInitExpr VIE(Field->getType());
5049 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5050
Richard Smithd62306a2011-11-10 06:34:14 +00005051 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005052 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5053 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005054
5055 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5056 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5057 isa<CXXDefaultInitExpr>(InitExpr));
5058
Richard Smithb228a862012-02-15 02:18:13 +00005059 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005060 }
5061
5062 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
5063 "initializer list for class with base classes");
5064 Result = APValue(APValue::UninitStruct(), 0,
5065 std::distance(RD->field_begin(), RD->field_end()));
5066 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005067 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00005068 for (RecordDecl::field_iterator Field = RD->field_begin(),
5069 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
5070 // Anonymous bit-fields are not considered members of the class for
5071 // purposes of aggregate initialization.
5072 if (Field->isUnnamedBitfield())
5073 continue;
5074
5075 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00005076
Richard Smith253c2a32012-01-27 01:14:48 +00005077 bool HaveInit = ElementNo < E->getNumInits();
5078
5079 // FIXME: Diagnostics here should point to the end of the initializer
5080 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00005081 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie40ed2972012-06-06 20:45:41 +00005082 Subobject, *Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005083 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005084
5085 // Perform an implicit value-initialization for members beyond the end of
5086 // the initializer list.
5087 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00005088 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00005089
Richard Smith852c9db2013-04-20 22:23:05 +00005090 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5091 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5092 isa<CXXDefaultInitExpr>(Init));
5093
Richard Smith49ca8aa2013-08-06 07:09:20 +00005094 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5095 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5096 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
5097 FieldVal, *Field))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005098 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00005099 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005100 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00005101 }
5102 }
5103
Richard Smith253c2a32012-01-27 01:14:48 +00005104 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005105}
5106
5107bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5108 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00005109 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5110
Richard Smithfddd3842011-12-30 21:15:51 +00005111 bool ZeroInit = E->requiresZeroInitialization();
5112 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005113 // If we've already performed zero-initialization, we're already done.
5114 if (!Result.isUninit())
5115 return true;
5116
Richard Smithda3f4fd2014-03-05 23:32:50 +00005117 // We can get here in two different ways:
5118 // 1) We're performing value-initialization, and should zero-initialize
5119 // the object, or
5120 // 2) We're performing default-initialization of an object with a trivial
5121 // constexpr default constructor, in which case we should start the
5122 // lifetimes of all the base subobjects (there can be no data member
5123 // subobjects in this case) per [basic.life]p1.
5124 // Either way, ZeroInitialization is appropriate.
5125 return ZeroInitialization(E);
Richard Smithcc36f692011-12-22 02:22:31 +00005126 }
5127
Richard Smithd62306a2011-11-10 06:34:14 +00005128 const FunctionDecl *Definition = 0;
5129 FD->getBody(Definition);
5130
Richard Smith357362d2011-12-13 06:39:58 +00005131 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5132 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005133
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005134 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00005135 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00005136 if (const MaterializeTemporaryExpr *ME
5137 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5138 return Visit(ME->GetTemporaryExpr());
5139
Richard Smithfddd3842011-12-30 21:15:51 +00005140 if (ZeroInit && !ZeroInitialization(E))
5141 return false;
5142
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005143 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005144 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005145 cast<CXXConstructorDecl>(Definition), Info,
5146 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00005147}
5148
Richard Smithcc1b96d2013-06-12 22:31:48 +00005149bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5150 const CXXStdInitializerListExpr *E) {
5151 const ConstantArrayType *ArrayType =
5152 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5153
5154 LValue Array;
5155 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5156 return false;
5157
5158 // Get a pointer to the first element of the array.
5159 Array.addArray(Info, E, ArrayType);
5160
5161 // FIXME: Perform the checks on the field types in SemaInit.
5162 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5163 RecordDecl::field_iterator Field = Record->field_begin();
5164 if (Field == Record->field_end())
5165 return Error(E);
5166
5167 // Start pointer.
5168 if (!Field->getType()->isPointerType() ||
5169 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5170 ArrayType->getElementType()))
5171 return Error(E);
5172
5173 // FIXME: What if the initializer_list type has base classes, etc?
5174 Result = APValue(APValue::UninitStruct(), 0, 2);
5175 Array.moveInto(Result.getStructField(0));
5176
5177 if (++Field == Record->field_end())
5178 return Error(E);
5179
5180 if (Field->getType()->isPointerType() &&
5181 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5182 ArrayType->getElementType())) {
5183 // End pointer.
5184 if (!HandleLValueArrayAdjustment(Info, E, Array,
5185 ArrayType->getElementType(),
5186 ArrayType->getSize().getZExtValue()))
5187 return false;
5188 Array.moveInto(Result.getStructField(1));
5189 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5190 // Length.
5191 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5192 else
5193 return Error(E);
5194
5195 if (++Field != Record->field_end())
5196 return Error(E);
5197
5198 return true;
5199}
5200
Richard Smithd62306a2011-11-10 06:34:14 +00005201static bool EvaluateRecord(const Expr *E, const LValue &This,
5202 APValue &Result, EvalInfo &Info) {
5203 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005204 "can't evaluate expression as a record rvalue");
5205 return RecordExprEvaluator(Info, This, Result).Visit(E);
5206}
5207
5208//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005209// Temporary Evaluation
5210//
5211// Temporaries are represented in the AST as rvalues, but generally behave like
5212// lvalues. The full-object of which the temporary is a subobject is implicitly
5213// materialized so that a reference can bind to it.
5214//===----------------------------------------------------------------------===//
5215namespace {
5216class TemporaryExprEvaluator
5217 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5218public:
5219 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5220 LValueExprEvaluatorBaseTy(Info, Result) {}
5221
5222 /// Visit an expression which constructs the value of this temporary.
5223 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005224 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005225 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5226 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005227 }
5228
5229 bool VisitCastExpr(const CastExpr *E) {
5230 switch (E->getCastKind()) {
5231 default:
5232 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5233
5234 case CK_ConstructorConversion:
5235 return VisitConstructExpr(E->getSubExpr());
5236 }
5237 }
5238 bool VisitInitListExpr(const InitListExpr *E) {
5239 return VisitConstructExpr(E);
5240 }
5241 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5242 return VisitConstructExpr(E);
5243 }
5244 bool VisitCallExpr(const CallExpr *E) {
5245 return VisitConstructExpr(E);
5246 }
5247};
5248} // end anonymous namespace
5249
5250/// Evaluate an expression of record type as a temporary.
5251static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005252 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005253 return TemporaryExprEvaluator(Info, Result).Visit(E);
5254}
5255
5256//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005257// Vector Evaluation
5258//===----------------------------------------------------------------------===//
5259
5260namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005261 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005262 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00005263 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005264 public:
Mike Stump11289f42009-09-09 15:08:12 +00005265
Richard Smith2d406342011-10-22 21:10:00 +00005266 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5267 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00005268
Richard Smith2d406342011-10-22 21:10:00 +00005269 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
5270 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5271 // FIXME: remove this APValue copy.
5272 Result = APValue(V.data(), V.size());
5273 return true;
5274 }
Richard Smith2e312c82012-03-03 22:46:17 +00005275 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00005276 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00005277 Result = V;
5278 return true;
5279 }
Richard Smithfddd3842011-12-30 21:15:51 +00005280 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00005281
Richard Smith2d406342011-10-22 21:10:00 +00005282 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00005283 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00005284 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00005285 bool VisitInitListExpr(const InitListExpr *E);
5286 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005287 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00005288 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00005289 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005290 };
5291} // end anonymous namespace
5292
5293static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005294 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00005295 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005296}
5297
Richard Smith2d406342011-10-22 21:10:00 +00005298bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5299 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005300 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005301
Richard Smith161f09a2011-12-06 22:44:34 +00005302 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00005303 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005304
Eli Friedmanc757de22011-03-25 00:43:55 +00005305 switch (E->getCastKind()) {
5306 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00005307 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00005308 if (SETy->isIntegerType()) {
5309 APSInt IntResult;
5310 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005311 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005312 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00005313 } else if (SETy->isRealFloatingType()) {
5314 APFloat F(0.0);
5315 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005316 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005317 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00005318 } else {
Richard Smith2d406342011-10-22 21:10:00 +00005319 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005320 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005321
5322 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00005323 SmallVector<APValue, 4> Elts(NElts, Val);
5324 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00005325 }
Eli Friedman803acb32011-12-22 03:51:45 +00005326 case CK_BitCast: {
5327 // Evaluate the operand into an APInt we can extract from.
5328 llvm::APInt SValInt;
5329 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5330 return false;
5331 // Extract the elements
5332 QualType EltTy = VTy->getElementType();
5333 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5334 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5335 SmallVector<APValue, 4> Elts;
5336 if (EltTy->isRealFloatingType()) {
5337 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00005338 unsigned FloatEltSize = EltSize;
5339 if (&Sem == &APFloat::x87DoubleExtended)
5340 FloatEltSize = 80;
5341 for (unsigned i = 0; i < NElts; i++) {
5342 llvm::APInt Elt;
5343 if (BigEndian)
5344 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5345 else
5346 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00005347 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00005348 }
5349 } else if (EltTy->isIntegerType()) {
5350 for (unsigned i = 0; i < NElts; i++) {
5351 llvm::APInt Elt;
5352 if (BigEndian)
5353 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5354 else
5355 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5356 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5357 }
5358 } else {
5359 return Error(E);
5360 }
5361 return Success(Elts, E);
5362 }
Eli Friedmanc757de22011-03-25 00:43:55 +00005363 default:
Richard Smith11562c52011-10-28 17:51:58 +00005364 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005365 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005366}
5367
Richard Smith2d406342011-10-22 21:10:00 +00005368bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005369VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005370 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005371 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00005372 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005373
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005374 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005375 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005376
Eli Friedmanb9c71292012-01-03 23:24:20 +00005377 // The number of initializers can be less than the number of
5378 // vector elements. For OpenCL, this can be due to nested vector
5379 // initialization. For GCC compatibility, missing trailing elements
5380 // should be initialized with zeroes.
5381 unsigned CountInits = 0, CountElts = 0;
5382 while (CountElts < NumElements) {
5383 // Handle nested vector initialization.
5384 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00005385 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00005386 APValue v;
5387 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5388 return Error(E);
5389 unsigned vlen = v.getVectorLength();
5390 for (unsigned j = 0; j < vlen; j++)
5391 Elements.push_back(v.getVectorElt(j));
5392 CountElts += vlen;
5393 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005394 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005395 if (CountInits < NumInits) {
5396 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005397 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005398 } else // trailing integer zero.
5399 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5400 Elements.push_back(APValue(sInt));
5401 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005402 } else {
5403 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005404 if (CountInits < NumInits) {
5405 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005406 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005407 } else // trailing float zero.
5408 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5409 Elements.push_back(APValue(f));
5410 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00005411 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00005412 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005413 }
Richard Smith2d406342011-10-22 21:10:00 +00005414 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005415}
5416
Richard Smith2d406342011-10-22 21:10:00 +00005417bool
Richard Smithfddd3842011-12-30 21:15:51 +00005418VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005419 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00005420 QualType EltTy = VT->getElementType();
5421 APValue ZeroElement;
5422 if (EltTy->isIntegerType())
5423 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5424 else
5425 ZeroElement =
5426 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5427
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005428 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00005429 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005430}
5431
Richard Smith2d406342011-10-22 21:10:00 +00005432bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00005433 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005434 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005435}
5436
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005437//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00005438// Array Evaluation
5439//===----------------------------------------------------------------------===//
5440
5441namespace {
5442 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005443 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005444 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00005445 APValue &Result;
5446 public:
5447
Richard Smithd62306a2011-11-10 06:34:14 +00005448 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5449 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00005450
5451 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00005452 assert((V.isArray() || V.isLValue()) &&
5453 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00005454 Result = V;
5455 return true;
5456 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005457
Richard Smithfddd3842011-12-30 21:15:51 +00005458 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005459 const ConstantArrayType *CAT =
5460 Info.Ctx.getAsConstantArrayType(E->getType());
5461 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005462 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005463
5464 Result = APValue(APValue::UninitArray(), 0,
5465 CAT->getSize().getZExtValue());
5466 if (!Result.hasArrayFiller()) return true;
5467
Richard Smithfddd3842011-12-30 21:15:51 +00005468 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00005469 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005470 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00005471 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00005472 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00005473 }
5474
Richard Smithf3e9e432011-11-07 09:22:26 +00005475 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00005476 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00005477 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5478 const LValue &Subobject,
5479 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00005480 };
5481} // end anonymous namespace
5482
Richard Smithd62306a2011-11-10 06:34:14 +00005483static bool EvaluateArray(const Expr *E, const LValue &This,
5484 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00005485 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00005486 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005487}
5488
5489bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5490 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5491 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005492 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005493
Richard Smithca2cfbf2011-12-22 01:07:19 +00005494 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5495 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00005496 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00005497 LValue LV;
5498 if (!EvaluateLValue(E->getInit(0), LV, Info))
5499 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005500 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00005501 LV.moveInto(Val);
5502 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00005503 }
5504
Richard Smith253c2a32012-01-27 01:14:48 +00005505 bool Success = true;
5506
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005507 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5508 "zero-initialized array shouldn't have any initialized elts");
5509 APValue Filler;
5510 if (Result.isArray() && Result.hasArrayFiller())
5511 Filler = Result.getArrayFiller();
5512
Richard Smith9543c5e2013-04-22 14:44:29 +00005513 unsigned NumEltsToInit = E->getNumInits();
5514 unsigned NumElts = CAT->getSize().getZExtValue();
5515 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
5516
5517 // If the initializer might depend on the array index, run it for each
5518 // array element. For now, just whitelist non-class value-initialization.
5519 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5520 NumEltsToInit = NumElts;
5521
5522 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005523
5524 // If the array was previously zero-initialized, preserve the
5525 // zero-initialized values.
5526 if (!Filler.isUninit()) {
5527 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5528 Result.getArrayInitializedElt(I) = Filler;
5529 if (Result.hasArrayFiller())
5530 Result.getArrayFiller() = Filler;
5531 }
5532
Richard Smithd62306a2011-11-10 06:34:14 +00005533 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005534 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00005535 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5536 const Expr *Init =
5537 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00005538 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00005539 Info, Subobject, Init) ||
5540 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00005541 CAT->getElementType(), 1)) {
5542 if (!Info.keepEvaluatingAfterFailure())
5543 return false;
5544 Success = false;
5545 }
Richard Smithd62306a2011-11-10 06:34:14 +00005546 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005547
Richard Smith9543c5e2013-04-22 14:44:29 +00005548 if (!Result.hasArrayFiller())
5549 return Success;
5550
5551 // If we get here, we have a trivial filler, which we can just evaluate
5552 // once and splat over the rest of the array elements.
5553 assert(FillerExpr && "no array filler for incomplete init list");
5554 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5555 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00005556}
5557
Richard Smith027bf112011-11-17 22:56:20 +00005558bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005559 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5560}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005561
Richard Smith9543c5e2013-04-22 14:44:29 +00005562bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5563 const LValue &Subobject,
5564 APValue *Value,
5565 QualType Type) {
5566 bool HadZeroInit = !Value->isUninit();
5567
5568 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5569 unsigned N = CAT->getSize().getZExtValue();
5570
5571 // Preserve the array filler if we had prior zero-initialization.
5572 APValue Filler =
5573 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5574 : APValue();
5575
5576 *Value = APValue(APValue::UninitArray(), N, N);
5577
5578 if (HadZeroInit)
5579 for (unsigned I = 0; I != N; ++I)
5580 Value->getArrayInitializedElt(I) = Filler;
5581
5582 // Initialize the elements.
5583 LValue ArrayElt = Subobject;
5584 ArrayElt.addArray(Info, E, CAT);
5585 for (unsigned I = 0; I != N; ++I)
5586 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5587 CAT->getElementType()) ||
5588 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5589 CAT->getElementType(), 1))
5590 return false;
5591
5592 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005593 }
Richard Smith027bf112011-11-17 22:56:20 +00005594
Richard Smith9543c5e2013-04-22 14:44:29 +00005595 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00005596 return Error(E);
5597
Richard Smith027bf112011-11-17 22:56:20 +00005598 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00005599
Richard Smithfddd3842011-12-30 21:15:51 +00005600 bool ZeroInit = E->requiresZeroInitialization();
5601 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005602 if (HadZeroInit)
5603 return true;
5604
Richard Smithda3f4fd2014-03-05 23:32:50 +00005605 // See RecordExprEvaluator::VisitCXXConstructExpr for explanation.
5606 ImplicitValueInitExpr VIE(Type);
5607 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithcc36f692011-12-22 02:22:31 +00005608 }
5609
Richard Smith027bf112011-11-17 22:56:20 +00005610 const FunctionDecl *Definition = 0;
5611 FD->getBody(Definition);
5612
Richard Smith357362d2011-12-13 06:39:58 +00005613 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5614 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005615
Richard Smith9eae7232012-01-12 18:54:33 +00005616 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005617 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005618 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005619 return false;
5620 }
5621
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005622 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005623 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00005624 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005625 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00005626}
5627
Richard Smithf3e9e432011-11-07 09:22:26 +00005628//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005629// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005630//
5631// As a GNU extension, we support casting pointers to sufficiently-wide integer
5632// types and back in constant folding. Integer values are thus represented
5633// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00005634//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005635
5636namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005637class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005638 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00005639 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005640public:
Richard Smith2e312c82012-03-03 22:46:17 +00005641 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005642 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005643
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005644 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005645 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005646 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005647 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005648 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005649 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005650 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005651 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005652 return true;
5653 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005654 bool Success(const llvm::APSInt &SI, const Expr *E) {
5655 return Success(SI, E, Result);
5656 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005657
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005658 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005659 assert(E->getType()->isIntegralOrEnumerationType() &&
5660 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005661 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005662 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005663 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005664 Result.getInt().setIsUnsigned(
5665 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005666 return true;
5667 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005668 bool Success(const llvm::APInt &I, const Expr *E) {
5669 return Success(I, E, Result);
5670 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005671
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005672 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005673 assert(E->getType()->isIntegralOrEnumerationType() &&
5674 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005675 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005676 return true;
5677 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005678 bool Success(uint64_t Value, const Expr *E) {
5679 return Success(Value, E, Result);
5680 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005681
Ken Dyckdbc01912011-03-11 02:13:43 +00005682 bool Success(CharUnits Size, const Expr *E) {
5683 return Success(Size.getQuantity(), E);
5684 }
5685
Richard Smith2e312c82012-03-03 22:46:17 +00005686 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005687 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00005688 Result = V;
5689 return true;
5690 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005691 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00005692 }
Mike Stump11289f42009-09-09 15:08:12 +00005693
Richard Smithfddd3842011-12-30 21:15:51 +00005694 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00005695
Peter Collingbournee9200682011-05-13 03:29:01 +00005696 //===--------------------------------------------------------------------===//
5697 // Visitor Methods
5698 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005699
Chris Lattner7174bf32008-07-12 00:38:25 +00005700 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005701 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005702 }
5703 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005704 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005705 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005706
5707 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5708 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005709 if (CheckReferencedDecl(E, E->getDecl()))
5710 return true;
5711
5712 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005713 }
5714 bool VisitMemberExpr(const MemberExpr *E) {
5715 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00005716 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005717 return true;
5718 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005719
5720 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005721 }
5722
Peter Collingbournee9200682011-05-13 03:29:01 +00005723 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005724 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00005725 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005726 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00005727
Peter Collingbournee9200682011-05-13 03:29:01 +00005728 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005729 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00005730
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005731 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005732 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005733 }
Mike Stump11289f42009-09-09 15:08:12 +00005734
Ted Kremeneke65b0862012-03-06 20:05:56 +00005735 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5736 return Success(E->getValue(), E);
5737 }
5738
Richard Smith4ce706a2011-10-11 21:43:33 +00005739 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00005740 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005741 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005742 }
5743
Douglas Gregor29c42f22012-02-24 07:38:34 +00005744 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5745 return Success(E->getValue(), E);
5746 }
5747
John Wiegley6242b6a2011-04-28 00:16:57 +00005748 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5749 return Success(E->getValue(), E);
5750 }
5751
John Wiegleyf9f65842011-04-25 06:54:41 +00005752 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5753 return Success(E->getValue(), E);
5754 }
5755
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005756 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005757 bool VisitUnaryImag(const UnaryOperator *E);
5758
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005759 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005760 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00005761
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005762private:
Ken Dyck160146e2010-01-27 17:10:57 +00005763 CharUnits GetAlignOfExpr(const Expr *E);
5764 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00005765 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00005766 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005767 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00005768};
Chris Lattner05706e882008-07-11 18:11:29 +00005769} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005770
Richard Smith11562c52011-10-28 17:51:58 +00005771/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
5772/// produce either the integer value or a pointer.
5773///
5774/// GCC has a heinous extension which folds casts between pointer types and
5775/// pointer-sized integral types. We support this by allowing the evaluation of
5776/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
5777/// Some simple arithmetic on such values is supported (they are treated much
5778/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00005779static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00005780 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005781 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005782 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00005783}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005784
Richard Smithf57d8cb2011-12-09 22:58:01 +00005785static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00005786 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005787 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00005788 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005789 if (!Val.isInt()) {
5790 // FIXME: It would be better to produce the diagnostic for casting
5791 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00005792 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005793 return false;
5794 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005795 Result = Val.getInt();
5796 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005797}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005798
Richard Smithf57d8cb2011-12-09 22:58:01 +00005799/// Check whether the given declaration can be directly converted to an integral
5800/// rvalue. If not, no diagnostic is produced; there are other things we can
5801/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005802bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00005803 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005804 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005805 // Check for signedness/width mismatches between E type and ECD value.
5806 bool SameSign = (ECD->getInitVal().isSigned()
5807 == E->getType()->isSignedIntegerOrEnumerationType());
5808 bool SameWidth = (ECD->getInitVal().getBitWidth()
5809 == Info.Ctx.getIntWidth(E->getType()));
5810 if (SameSign && SameWidth)
5811 return Success(ECD->getInitVal(), E);
5812 else {
5813 // Get rid of mismatch (otherwise Success assertions will fail)
5814 // by computing a new value matching the type of E.
5815 llvm::APSInt Val = ECD->getInitVal();
5816 if (!SameSign)
5817 Val.setIsSigned(!ECD->getInitVal().isSigned());
5818 if (!SameWidth)
5819 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
5820 return Success(Val, E);
5821 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005822 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005823 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00005824}
5825
Chris Lattner86ee2862008-10-06 06:40:35 +00005826/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
5827/// as GCC.
5828static int EvaluateBuiltinClassifyType(const CallExpr *E) {
5829 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005830 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00005831 enum gcc_type_class {
5832 no_type_class = -1,
5833 void_type_class, integer_type_class, char_type_class,
5834 enumeral_type_class, boolean_type_class,
5835 pointer_type_class, reference_type_class, offset_type_class,
5836 real_type_class, complex_type_class,
5837 function_type_class, method_type_class,
5838 record_type_class, union_type_class,
5839 array_type_class, string_type_class,
5840 lang_type_class
5841 };
Mike Stump11289f42009-09-09 15:08:12 +00005842
5843 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00005844 // ideal, however it is what gcc does.
5845 if (E->getNumArgs() == 0)
5846 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00005847
Chris Lattner86ee2862008-10-06 06:40:35 +00005848 QualType ArgTy = E->getArg(0)->getType();
5849 if (ArgTy->isVoidType())
5850 return void_type_class;
5851 else if (ArgTy->isEnumeralType())
5852 return enumeral_type_class;
5853 else if (ArgTy->isBooleanType())
5854 return boolean_type_class;
5855 else if (ArgTy->isCharType())
5856 return string_type_class; // gcc doesn't appear to use char_type_class
5857 else if (ArgTy->isIntegerType())
5858 return integer_type_class;
5859 else if (ArgTy->isPointerType())
5860 return pointer_type_class;
5861 else if (ArgTy->isReferenceType())
5862 return reference_type_class;
5863 else if (ArgTy->isRealType())
5864 return real_type_class;
5865 else if (ArgTy->isComplexType())
5866 return complex_type_class;
5867 else if (ArgTy->isFunctionType())
5868 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00005869 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00005870 return record_type_class;
5871 else if (ArgTy->isUnionType())
5872 return union_type_class;
5873 else if (ArgTy->isArrayType())
5874 return array_type_class;
5875 else if (ArgTy->isUnionType())
5876 return union_type_class;
5877 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00005878 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00005879}
5880
Richard Smith5fab0c92011-12-28 19:48:30 +00005881/// EvaluateBuiltinConstantPForLValue - Determine the result of
5882/// __builtin_constant_p when applied to the given lvalue.
5883///
5884/// An lvalue is only "constant" if it is a pointer or reference to the first
5885/// character of a string literal.
5886template<typename LValue>
5887static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00005888 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00005889 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
5890}
5891
5892/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
5893/// GCC as we can manage.
5894static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
5895 QualType ArgType = Arg->getType();
5896
5897 // __builtin_constant_p always has one operand. The rules which gcc follows
5898 // are not precisely documented, but are as follows:
5899 //
5900 // - If the operand is of integral, floating, complex or enumeration type,
5901 // and can be folded to a known value of that type, it returns 1.
5902 // - If the operand and can be folded to a pointer to the first character
5903 // of a string literal (or such a pointer cast to an integral type), it
5904 // returns 1.
5905 //
5906 // Otherwise, it returns 0.
5907 //
5908 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
5909 // its support for this does not currently work.
5910 if (ArgType->isIntegralOrEnumerationType()) {
5911 Expr::EvalResult Result;
5912 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
5913 return false;
5914
5915 APValue &V = Result.Val;
5916 if (V.getKind() == APValue::Int)
5917 return true;
5918
5919 return EvaluateBuiltinConstantPForLValue(V);
5920 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
5921 return Arg->isEvaluatable(Ctx);
5922 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
5923 LValue LV;
5924 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00005925 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00005926 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
5927 : EvaluatePointer(Arg, LV, Info)) &&
5928 !Status.HasSideEffects)
5929 return EvaluateBuiltinConstantPForLValue(LV);
5930 }
5931
5932 // Anything else isn't considered to be sufficiently constant.
5933 return false;
5934}
5935
John McCall95007602010-05-10 23:27:23 +00005936/// Retrieves the "underlying object type" of the given expression,
5937/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00005938QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
5939 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
5940 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00005941 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00005942 } else if (const Expr *E = B.get<const Expr*>()) {
5943 if (isa<CompoundLiteralExpr>(E))
5944 return E->getType();
John McCall95007602010-05-10 23:27:23 +00005945 }
5946
5947 return QualType();
5948}
5949
Peter Collingbournee9200682011-05-13 03:29:01 +00005950bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00005951 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00005952
5953 {
5954 // The operand of __builtin_object_size is never evaluated for side-effects.
5955 // If there are any, but we can determine the pointed-to object anyway, then
5956 // ignore the side-effects.
5957 SpeculativeEvaluationRAII SpeculativeEval(Info);
5958 if (!EvaluatePointer(E->getArg(0), Base, Info))
5959 return false;
5960 }
John McCall95007602010-05-10 23:27:23 +00005961
5962 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00005963 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00005964
Richard Smithce40ad62011-11-12 22:28:03 +00005965 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00005966 if (T.isNull() ||
5967 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00005968 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00005969 T->isVariablyModifiedType() ||
5970 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005971 return Error(E);
John McCall95007602010-05-10 23:27:23 +00005972
5973 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
5974 CharUnits Offset = Base.getLValueOffset();
5975
5976 if (!Offset.isNegative() && Offset <= Size)
5977 Size -= Offset;
5978 else
5979 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00005980 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00005981}
5982
Peter Collingbournee9200682011-05-13 03:29:01 +00005983bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00005984 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005985 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00005986 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005987
5988 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00005989 if (TryEvaluateBuiltinObjectSize(E))
5990 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00005991
Richard Smith0421ce72012-08-07 04:16:51 +00005992 // If evaluating the argument has side-effects, we can't determine the size
5993 // of the object, and so we lower it to unknown now. CodeGen relies on us to
5994 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005995 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00005996 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00005997 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00005998 return Success(0, E);
5999 }
Mike Stump876387b2009-10-27 22:09:17 +00006000
Richard Smith01ade172012-05-23 04:13:20 +00006001 // Expression had no side effects, but we couldn't statically determine the
6002 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006003 switch (Info.EvalMode) {
6004 case EvalInfo::EM_ConstantExpression:
6005 case EvalInfo::EM_PotentialConstantExpression:
6006 case EvalInfo::EM_ConstantFold:
6007 case EvalInfo::EM_EvaluateForOverflow:
6008 case EvalInfo::EM_IgnoreSideEffects:
6009 return Error(E);
6010 case EvalInfo::EM_ConstantExpressionUnevaluated:
6011 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
6012 return Success(-1ULL, E);
6013 }
Mike Stump722cedf2009-10-26 18:35:08 +00006014 }
6015
Benjamin Kramera801f4a2012-10-06 14:42:22 +00006016 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00006017 case Builtin::BI__builtin_bswap32:
6018 case Builtin::BI__builtin_bswap64: {
6019 APSInt Val;
6020 if (!EvaluateInteger(E->getArg(0), Val, Info))
6021 return false;
6022
6023 return Success(Val.byteSwap(), E);
6024 }
6025
Richard Smith8889a3d2013-06-13 06:26:32 +00006026 case Builtin::BI__builtin_classify_type:
6027 return Success(EvaluateBuiltinClassifyType(E), E);
6028
6029 // FIXME: BI__builtin_clrsb
6030 // FIXME: BI__builtin_clrsbl
6031 // FIXME: BI__builtin_clrsbll
6032
Richard Smith80b3c8e2013-06-13 05:04:16 +00006033 case Builtin::BI__builtin_clz:
6034 case Builtin::BI__builtin_clzl:
6035 case Builtin::BI__builtin_clzll: {
6036 APSInt Val;
6037 if (!EvaluateInteger(E->getArg(0), Val, Info))
6038 return false;
6039 if (!Val)
6040 return Error(E);
6041
6042 return Success(Val.countLeadingZeros(), E);
6043 }
6044
Richard Smith8889a3d2013-06-13 06:26:32 +00006045 case Builtin::BI__builtin_constant_p:
6046 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6047
Richard Smith80b3c8e2013-06-13 05:04:16 +00006048 case Builtin::BI__builtin_ctz:
6049 case Builtin::BI__builtin_ctzl:
6050 case Builtin::BI__builtin_ctzll: {
6051 APSInt Val;
6052 if (!EvaluateInteger(E->getArg(0), Val, Info))
6053 return false;
6054 if (!Val)
6055 return Error(E);
6056
6057 return Success(Val.countTrailingZeros(), E);
6058 }
6059
Richard Smith8889a3d2013-06-13 06:26:32 +00006060 case Builtin::BI__builtin_eh_return_data_regno: {
6061 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6062 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6063 return Success(Operand, E);
6064 }
6065
6066 case Builtin::BI__builtin_expect:
6067 return Visit(E->getArg(0));
6068
6069 case Builtin::BI__builtin_ffs:
6070 case Builtin::BI__builtin_ffsl:
6071 case Builtin::BI__builtin_ffsll: {
6072 APSInt Val;
6073 if (!EvaluateInteger(E->getArg(0), Val, Info))
6074 return false;
6075
6076 unsigned N = Val.countTrailingZeros();
6077 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6078 }
6079
6080 case Builtin::BI__builtin_fpclassify: {
6081 APFloat Val(0.0);
6082 if (!EvaluateFloat(E->getArg(5), Val, Info))
6083 return false;
6084 unsigned Arg;
6085 switch (Val.getCategory()) {
6086 case APFloat::fcNaN: Arg = 0; break;
6087 case APFloat::fcInfinity: Arg = 1; break;
6088 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6089 case APFloat::fcZero: Arg = 4; break;
6090 }
6091 return Visit(E->getArg(Arg));
6092 }
6093
6094 case Builtin::BI__builtin_isinf_sign: {
6095 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00006096 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00006097 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6098 }
6099
Richard Smithea3019d2013-10-15 19:07:14 +00006100 case Builtin::BI__builtin_isinf: {
6101 APFloat Val(0.0);
6102 return EvaluateFloat(E->getArg(0), Val, Info) &&
6103 Success(Val.isInfinity() ? 1 : 0, E);
6104 }
6105
6106 case Builtin::BI__builtin_isfinite: {
6107 APFloat Val(0.0);
6108 return EvaluateFloat(E->getArg(0), Val, Info) &&
6109 Success(Val.isFinite() ? 1 : 0, E);
6110 }
6111
6112 case Builtin::BI__builtin_isnan: {
6113 APFloat Val(0.0);
6114 return EvaluateFloat(E->getArg(0), Val, Info) &&
6115 Success(Val.isNaN() ? 1 : 0, E);
6116 }
6117
6118 case Builtin::BI__builtin_isnormal: {
6119 APFloat Val(0.0);
6120 return EvaluateFloat(E->getArg(0), Val, Info) &&
6121 Success(Val.isNormal() ? 1 : 0, E);
6122 }
6123
Richard Smith8889a3d2013-06-13 06:26:32 +00006124 case Builtin::BI__builtin_parity:
6125 case Builtin::BI__builtin_parityl:
6126 case Builtin::BI__builtin_parityll: {
6127 APSInt Val;
6128 if (!EvaluateInteger(E->getArg(0), Val, Info))
6129 return false;
6130
6131 return Success(Val.countPopulation() % 2, E);
6132 }
6133
Richard Smith80b3c8e2013-06-13 05:04:16 +00006134 case Builtin::BI__builtin_popcount:
6135 case Builtin::BI__builtin_popcountl:
6136 case Builtin::BI__builtin_popcountll: {
6137 APSInt Val;
6138 if (!EvaluateInteger(E->getArg(0), Val, Info))
6139 return false;
6140
6141 return Success(Val.countPopulation(), E);
6142 }
6143
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006144 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00006145 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006146 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006147 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00006148 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6149 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00006150 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00006151 // Fall through.
Richard Smithe6c19f22013-11-15 02:10:04 +00006152 case Builtin::BI__builtin_strlen: {
6153 // As an extension, we support __builtin_strlen() as a constant expression,
6154 // and support folding strlen() to a constant.
6155 LValue String;
6156 if (!EvaluatePointer(E->getArg(0), String, Info))
6157 return false;
6158
6159 // Fast path: if it's a string literal, search the string value.
6160 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
6161 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006162 // The string literal may have embedded null characters. Find the first
6163 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00006164 StringRef Str = S->getBytes();
6165 int64_t Off = String.Offset.getQuantity();
6166 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
6167 S->getCharByteWidth() == 1) {
6168 Str = Str.substr(Off);
6169
6170 StringRef::size_type Pos = Str.find(0);
6171 if (Pos != StringRef::npos)
6172 Str = Str.substr(0, Pos);
6173
6174 return Success(Str.size(), E);
6175 }
6176
6177 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006178 }
Richard Smithe6c19f22013-11-15 02:10:04 +00006179
6180 // Slow path: scan the bytes of the string looking for the terminating 0.
6181 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
6182 for (uint64_t Strlen = 0; /**/; ++Strlen) {
6183 APValue Char;
6184 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
6185 !Char.isInt())
6186 return false;
6187 if (!Char.getInt())
6188 return Success(Strlen, E);
6189 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
6190 return false;
6191 }
6192 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006193
Richard Smith01ba47d2012-04-13 00:45:38 +00006194 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00006195 case Builtin::BI__atomic_is_lock_free:
6196 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00006197 APSInt SizeVal;
6198 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6199 return false;
6200
6201 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6202 // of two less than the maximum inline atomic width, we know it is
6203 // lock-free. If the size isn't a power of two, or greater than the
6204 // maximum alignment where we promote atomics, we know it is not lock-free
6205 // (at least not in the sense of atomic_is_lock_free). Otherwise,
6206 // the answer can only be determined at runtime; for example, 16-byte
6207 // atomics have lock-free implementations on some, but not all,
6208 // x86-64 processors.
6209
6210 // Check power-of-two.
6211 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00006212 if (Size.isPowerOfTwo()) {
6213 // Check against inlining width.
6214 unsigned InlineWidthBits =
6215 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6216 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6217 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6218 Size == CharUnits::One() ||
6219 E->getArg(1)->isNullPointerConstant(Info.Ctx,
6220 Expr::NPC_NeverValueDependent))
6221 // OK, we will inline appropriately-aligned operations of this size,
6222 // and _Atomic(T) is appropriately-aligned.
6223 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006224
Richard Smith01ba47d2012-04-13 00:45:38 +00006225 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6226 castAs<PointerType>()->getPointeeType();
6227 if (!PointeeType->isIncompleteType() &&
6228 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6229 // OK, we will inline operations on this object.
6230 return Success(1, E);
6231 }
6232 }
6233 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006234
Richard Smith01ba47d2012-04-13 00:45:38 +00006235 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6236 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006237 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006238 }
Chris Lattner7174bf32008-07-12 00:38:25 +00006239}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006240
Richard Smith8b3497e2011-10-31 01:37:14 +00006241static bool HasSameBase(const LValue &A, const LValue &B) {
6242 if (!A.getLValueBase())
6243 return !B.getLValueBase();
6244 if (!B.getLValueBase())
6245 return false;
6246
Richard Smithce40ad62011-11-12 22:28:03 +00006247 if (A.getLValueBase().getOpaqueValue() !=
6248 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006249 const Decl *ADecl = GetLValueBaseDecl(A);
6250 if (!ADecl)
6251 return false;
6252 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00006253 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00006254 return false;
6255 }
6256
6257 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00006258 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00006259}
6260
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006261namespace {
Richard Smith11562c52011-10-28 17:51:58 +00006262
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006263/// \brief Data recursive integer evaluator of certain binary operators.
6264///
6265/// We use a data recursive algorithm for binary operators so that we are able
6266/// to handle extreme cases of chained binary operators without causing stack
6267/// overflow.
6268class DataRecursiveIntBinOpEvaluator {
6269 struct EvalResult {
6270 APValue Val;
6271 bool Failed;
6272
6273 EvalResult() : Failed(false) { }
6274
6275 void swap(EvalResult &RHS) {
6276 Val.swap(RHS.Val);
6277 Failed = RHS.Failed;
6278 RHS.Failed = false;
6279 }
6280 };
6281
6282 struct Job {
6283 const Expr *E;
6284 EvalResult LHSResult; // meaningful only for binary operator expression.
6285 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
6286
6287 Job() : StoredInfo(0) { }
6288 void startSpeculativeEval(EvalInfo &Info) {
6289 OldEvalStatus = Info.EvalStatus;
6290 Info.EvalStatus.Diag = 0;
6291 StoredInfo = &Info;
6292 }
6293 ~Job() {
6294 if (StoredInfo) {
6295 StoredInfo->EvalStatus = OldEvalStatus;
6296 }
6297 }
6298 private:
6299 EvalInfo *StoredInfo; // non-null if status changed.
6300 Expr::EvalStatus OldEvalStatus;
6301 };
6302
6303 SmallVector<Job, 16> Queue;
6304
6305 IntExprEvaluator &IntEval;
6306 EvalInfo &Info;
6307 APValue &FinalResult;
6308
6309public:
6310 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
6311 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
6312
6313 /// \brief True if \param E is a binary operator that we are going to handle
6314 /// data recursively.
6315 /// We handle binary operators that are comma, logical, or that have operands
6316 /// with integral or enumeration type.
6317 static bool shouldEnqueue(const BinaryOperator *E) {
6318 return E->getOpcode() == BO_Comma ||
6319 E->isLogicalOp() ||
6320 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6321 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00006322 }
6323
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006324 bool Traverse(const BinaryOperator *E) {
6325 enqueue(E);
6326 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00006327 while (!Queue.empty())
6328 process(PrevResult);
6329
6330 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006331
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006332 FinalResult.swap(PrevResult.Val);
6333 return true;
6334 }
6335
6336private:
6337 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6338 return IntEval.Success(Value, E, Result);
6339 }
6340 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6341 return IntEval.Success(Value, E, Result);
6342 }
6343 bool Error(const Expr *E) {
6344 return IntEval.Error(E);
6345 }
6346 bool Error(const Expr *E, diag::kind D) {
6347 return IntEval.Error(E, D);
6348 }
6349
6350 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6351 return Info.CCEDiag(E, D);
6352 }
6353
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006354 // \brief Returns true if visiting the RHS is necessary, false otherwise.
6355 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006356 bool &SuppressRHSDiags);
6357
6358 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6359 const BinaryOperator *E, APValue &Result);
6360
6361 void EvaluateExpr(const Expr *E, EvalResult &Result) {
6362 Result.Failed = !Evaluate(Result.Val, Info, E);
6363 if (Result.Failed)
6364 Result.Val = APValue();
6365 }
6366
Richard Trieuba4d0872012-03-21 23:30:30 +00006367 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006368
6369 void enqueue(const Expr *E) {
6370 E = E->IgnoreParens();
6371 Queue.resize(Queue.size()+1);
6372 Queue.back().E = E;
6373 Queue.back().Kind = Job::AnyExprKind;
6374 }
6375};
6376
6377}
6378
6379bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006380 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006381 bool &SuppressRHSDiags) {
6382 if (E->getOpcode() == BO_Comma) {
6383 // Ignore LHS but note if we could not evaluate it.
6384 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00006385 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006386 return true;
6387 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006388
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006389 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006390 bool LHSAsBool;
6391 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006392 // We were able to evaluate the LHS, see if we can get away with not
6393 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00006394 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
6395 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006396 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006397 }
6398 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006399 LHSResult.Failed = true;
6400
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006401 // Since we weren't able to evaluate the left hand side, it
6402 // must have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00006403 if (!Info.noteSideEffect())
6404 return false;
6405
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006406 // We can't evaluate the LHS; however, sometimes the result
6407 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6408 // Don't ignore RHS and suppress diagnostics from this arm.
6409 SuppressRHSDiags = true;
6410 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006411
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006412 return true;
6413 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006414
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006415 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6416 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00006417
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006418 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006419 return false; // Ignore RHS;
6420
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006421 return true;
6422}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006423
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006424bool DataRecursiveIntBinOpEvaluator::
6425 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6426 const BinaryOperator *E, APValue &Result) {
6427 if (E->getOpcode() == BO_Comma) {
6428 if (RHSResult.Failed)
6429 return false;
6430 Result = RHSResult.Val;
6431 return true;
6432 }
6433
6434 if (E->isLogicalOp()) {
6435 bool lhsResult, rhsResult;
6436 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
6437 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
6438
6439 if (LHSIsOK) {
6440 if (RHSIsOK) {
6441 if (E->getOpcode() == BO_LOr)
6442 return Success(lhsResult || rhsResult, E, Result);
6443 else
6444 return Success(lhsResult && rhsResult, E, Result);
6445 }
6446 } else {
6447 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006448 // We can't evaluate the LHS; however, sometimes the result
6449 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6450 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006451 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006452 }
6453 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006454
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006455 return false;
6456 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006457
6458 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6459 E->getRHS()->getType()->isIntegralOrEnumerationType());
6460
6461 if (LHSResult.Failed || RHSResult.Failed)
6462 return false;
6463
6464 const APValue &LHSVal = LHSResult.Val;
6465 const APValue &RHSVal = RHSResult.Val;
6466
6467 // Handle cases like (unsigned long)&a + 4.
6468 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
6469 Result = LHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00006470 CharUnits AdditionalOffset =
6471 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006472 if (E->getOpcode() == BO_Add)
6473 Result.getLValueOffset() += AdditionalOffset;
6474 else
6475 Result.getLValueOffset() -= AdditionalOffset;
6476 return true;
6477 }
6478
6479 // Handle cases like 4 + (unsigned long)&a
6480 if (E->getOpcode() == BO_Add &&
6481 RHSVal.isLValue() && LHSVal.isInt()) {
6482 Result = RHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00006483 Result.getLValueOffset() +=
6484 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006485 return true;
6486 }
6487
6488 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
6489 // Handle (intptr_t)&&A - (intptr_t)&&B.
6490 if (!LHSVal.getLValueOffset().isZero() ||
6491 !RHSVal.getLValueOffset().isZero())
6492 return false;
6493 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
6494 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
6495 if (!LHSExpr || !RHSExpr)
6496 return false;
6497 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6498 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6499 if (!LHSAddrExpr || !RHSAddrExpr)
6500 return false;
6501 // Make sure both labels come from the same function.
6502 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6503 RHSAddrExpr->getLabel()->getDeclContext())
6504 return false;
6505 Result = APValue(LHSAddrExpr, RHSAddrExpr);
6506 return true;
6507 }
Richard Smith43e77732013-05-07 04:50:00 +00006508
6509 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006510 if (!LHSVal.isInt() || !RHSVal.isInt())
6511 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00006512
6513 // Set up the width and signedness manually, in case it can't be deduced
6514 // from the operation we're performing.
6515 // FIXME: Don't do this in the cases where we can deduce it.
6516 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
6517 E->getType()->isUnsignedIntegerOrEnumerationType());
6518 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
6519 RHSVal.getInt(), Value))
6520 return false;
6521 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006522}
6523
Richard Trieuba4d0872012-03-21 23:30:30 +00006524void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006525 Job &job = Queue.back();
6526
6527 switch (job.Kind) {
6528 case Job::AnyExprKind: {
6529 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
6530 if (shouldEnqueue(Bop)) {
6531 job.Kind = Job::BinOpKind;
6532 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006533 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006534 }
6535 }
6536
6537 EvaluateExpr(job.E, Result);
6538 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006539 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006540 }
6541
6542 case Job::BinOpKind: {
6543 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006544 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006545 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006546 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006547 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006548 }
6549 if (SuppressRHSDiags)
6550 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006551 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006552 job.Kind = Job::BinOpVisitedLHSKind;
6553 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006554 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006555 }
6556
6557 case Job::BinOpVisitedLHSKind: {
6558 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6559 EvalResult RHS;
6560 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00006561 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006562 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006563 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006564 }
6565 }
6566
6567 llvm_unreachable("Invalid Job::Kind!");
6568}
6569
6570bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6571 if (E->isAssignmentOp())
6572 return Error(E);
6573
6574 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
6575 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006576
Anders Carlssonacc79812008-11-16 07:17:21 +00006577 QualType LHSTy = E->getLHS()->getType();
6578 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006579
6580 if (LHSTy->isAnyComplexType()) {
6581 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00006582 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006583
Richard Smith253c2a32012-01-27 01:14:48 +00006584 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
6585 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006586 return false;
6587
Richard Smith253c2a32012-01-27 01:14:48 +00006588 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006589 return false;
6590
6591 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00006592 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006593 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00006594 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006595 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
6596
John McCalle3027922010-08-25 11:45:40 +00006597 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006598 return Success((CR_r == APFloat::cmpEqual &&
6599 CR_i == APFloat::cmpEqual), E);
6600 else {
John McCalle3027922010-08-25 11:45:40 +00006601 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006602 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00006603 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006604 CR_r == APFloat::cmpLessThan ||
6605 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00006606 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006607 CR_i == APFloat::cmpLessThan ||
6608 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006609 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006610 } else {
John McCalle3027922010-08-25 11:45:40 +00006611 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006612 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
6613 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
6614 else {
John McCalle3027922010-08-25 11:45:40 +00006615 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006616 "Invalid compex comparison.");
6617 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
6618 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
6619 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006620 }
6621 }
Mike Stump11289f42009-09-09 15:08:12 +00006622
Anders Carlssonacc79812008-11-16 07:17:21 +00006623 if (LHSTy->isRealFloatingType() &&
6624 RHSTy->isRealFloatingType()) {
6625 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00006626
Richard Smith253c2a32012-01-27 01:14:48 +00006627 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
6628 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00006629 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006630
Richard Smith253c2a32012-01-27 01:14:48 +00006631 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00006632 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006633
Anders Carlssonacc79812008-11-16 07:17:21 +00006634 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00006635
Anders Carlssonacc79812008-11-16 07:17:21 +00006636 switch (E->getOpcode()) {
6637 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006638 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00006639 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006640 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00006641 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006642 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00006643 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006644 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006645 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00006646 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006647 E);
John McCalle3027922010-08-25 11:45:40 +00006648 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006649 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006650 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00006651 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00006652 || CR == APFloat::cmpLessThan
6653 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00006654 }
Anders Carlssonacc79812008-11-16 07:17:21 +00006655 }
Mike Stump11289f42009-09-09 15:08:12 +00006656
Eli Friedmana38da572009-04-28 19:17:36 +00006657 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006658 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00006659 LValue LHSValue, RHSValue;
6660
6661 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6662 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006663 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006664
Richard Smith253c2a32012-01-27 01:14:48 +00006665 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006666 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006667
Richard Smith8b3497e2011-10-31 01:37:14 +00006668 // Reject differing bases from the normal codepath; we special-case
6669 // comparisons to null.
6670 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006671 if (E->getOpcode() == BO_Sub) {
6672 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006673 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6674 return false;
6675 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00006676 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006677 if (!LHSExpr || !RHSExpr)
6678 return false;
6679 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6680 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6681 if (!LHSAddrExpr || !RHSAddrExpr)
6682 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006683 // Make sure both labels come from the same function.
6684 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6685 RHSAddrExpr->getLabel()->getDeclContext())
6686 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006687 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006688 return true;
6689 }
Richard Smith83c68212011-10-31 05:11:32 +00006690 // Inequalities and subtractions between unrelated pointers have
6691 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00006692 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006693 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006694 // A constant address may compare equal to the address of a symbol.
6695 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00006696 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006697 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6698 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006699 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006700 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00006701 // distinct addresses. In clang, the result of such a comparison is
6702 // unspecified, so it is not a constant expression. However, we do know
6703 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00006704 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6705 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006706 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006707 // We can't tell whether weak symbols will end up pointing to the same
6708 // object.
6709 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006710 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006711 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00006712 // (Note that clang defaults to -fmerge-all-constants, which can
6713 // lead to inconsistent results for comparisons involving the address
6714 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00006715 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00006716 }
Eli Friedman64004332009-03-23 04:38:34 +00006717
Richard Smith1b470412012-02-01 08:10:20 +00006718 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
6719 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
6720
Richard Smith84f6dcf2012-02-02 01:16:57 +00006721 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
6722 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
6723
John McCalle3027922010-08-25 11:45:40 +00006724 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00006725 // C++11 [expr.add]p6:
6726 // Unless both pointers point to elements of the same array object, or
6727 // one past the last element of the array object, the behavior is
6728 // undefined.
6729 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6730 !AreElementsOfSameArray(getType(LHSValue.Base),
6731 LHSDesignator, RHSDesignator))
6732 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
6733
Chris Lattner882bdf22010-04-20 17:13:14 +00006734 QualType Type = E->getLHS()->getType();
6735 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006736
Richard Smithd62306a2011-11-10 06:34:14 +00006737 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00006738 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00006739 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006740
Richard Smith84c6b3d2013-09-10 21:34:14 +00006741 // As an extension, a type may have zero size (empty struct or union in
6742 // C, array of zero length). Pointer subtraction in such cases has
6743 // undefined behavior, so is not constant.
6744 if (ElementSize.isZero()) {
6745 Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
6746 << ElementType;
6747 return false;
6748 }
6749
Richard Smith1b470412012-02-01 08:10:20 +00006750 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
6751 // and produce incorrect results when it overflows. Such behavior
6752 // appears to be non-conforming, but is common, so perhaps we should
6753 // assume the standard intended for such cases to be undefined behavior
6754 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00006755
Richard Smith1b470412012-02-01 08:10:20 +00006756 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
6757 // overflow in the final conversion to ptrdiff_t.
6758 APSInt LHS(
6759 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
6760 APSInt RHS(
6761 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
6762 APSInt ElemSize(
6763 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
6764 APSInt TrueResult = (LHS - RHS) / ElemSize;
6765 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
6766
6767 if (Result.extend(65) != TrueResult)
6768 HandleOverflow(Info, E, TrueResult, E->getType());
6769 return Success(Result, E);
6770 }
Richard Smithde21b242012-01-31 06:41:30 +00006771
6772 // C++11 [expr.rel]p3:
6773 // Pointers to void (after pointer conversions) can be compared, with a
6774 // result defined as follows: If both pointers represent the same
6775 // address or are both the null pointer value, the result is true if the
6776 // operator is <= or >= and false otherwise; otherwise the result is
6777 // unspecified.
6778 // We interpret this as applying to pointers to *cv* void.
6779 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00006780 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00006781 CCEDiag(E, diag::note_constexpr_void_comparison);
6782
Richard Smith84f6dcf2012-02-02 01:16:57 +00006783 // C++11 [expr.rel]p2:
6784 // - If two pointers point to non-static data members of the same object,
6785 // or to subobjects or array elements fo such members, recursively, the
6786 // pointer to the later declared member compares greater provided the
6787 // two members have the same access control and provided their class is
6788 // not a union.
6789 // [...]
6790 // - Otherwise pointer comparisons are unspecified.
6791 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6792 E->isRelationalOp()) {
6793 bool WasArrayIndex;
6794 unsigned Mismatch =
6795 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
6796 RHSDesignator, WasArrayIndex);
6797 // At the point where the designators diverge, the comparison has a
6798 // specified value if:
6799 // - we are comparing array indices
6800 // - we are comparing fields of a union, or fields with the same access
6801 // Otherwise, the result is unspecified and thus the comparison is not a
6802 // constant expression.
6803 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
6804 Mismatch < RHSDesignator.Entries.size()) {
6805 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
6806 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
6807 if (!LF && !RF)
6808 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
6809 else if (!LF)
6810 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6811 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
6812 << RF->getParent() << RF;
6813 else if (!RF)
6814 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6815 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
6816 << LF->getParent() << LF;
6817 else if (!LF->getParent()->isUnion() &&
6818 LF->getAccess() != RF->getAccess())
6819 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
6820 << LF << LF->getAccess() << RF << RF->getAccess()
6821 << LF->getParent();
6822 }
6823 }
6824
Eli Friedman6c31cb42012-04-16 04:30:08 +00006825 // The comparison here must be unsigned, and performed with the same
6826 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00006827 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
6828 uint64_t CompareLHS = LHSOffset.getQuantity();
6829 uint64_t CompareRHS = RHSOffset.getQuantity();
6830 assert(PtrSize <= 64 && "Unexpected pointer width");
6831 uint64_t Mask = ~0ULL >> (64 - PtrSize);
6832 CompareLHS &= Mask;
6833 CompareRHS &= Mask;
6834
Eli Friedman2f5b7c52012-04-16 19:23:57 +00006835 // If there is a base and this is a relational operator, we can only
6836 // compare pointers within the object in question; otherwise, the result
6837 // depends on where the object is located in memory.
6838 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
6839 QualType BaseTy = getType(LHSValue.Base);
6840 if (BaseTy->isIncompleteType())
6841 return Error(E);
6842 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
6843 uint64_t OffsetLimit = Size.getQuantity();
6844 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
6845 return Error(E);
6846 }
6847
Richard Smith8b3497e2011-10-31 01:37:14 +00006848 switch (E->getOpcode()) {
6849 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00006850 case BO_LT: return Success(CompareLHS < CompareRHS, E);
6851 case BO_GT: return Success(CompareLHS > CompareRHS, E);
6852 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
6853 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
6854 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
6855 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00006856 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006857 }
6858 }
Richard Smith7bb00672012-02-01 01:42:44 +00006859
6860 if (LHSTy->isMemberPointerType()) {
6861 assert(E->isEqualityOp() && "unexpected member pointer operation");
6862 assert(RHSTy->isMemberPointerType() && "invalid comparison");
6863
6864 MemberPtr LHSValue, RHSValue;
6865
6866 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
6867 if (!LHSOK && Info.keepEvaluatingAfterFailure())
6868 return false;
6869
6870 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6871 return false;
6872
6873 // C++11 [expr.eq]p2:
6874 // If both operands are null, they compare equal. Otherwise if only one is
6875 // null, they compare unequal.
6876 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
6877 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
6878 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6879 }
6880
6881 // Otherwise if either is a pointer to a virtual member function, the
6882 // result is unspecified.
6883 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
6884 if (MD->isVirtual())
6885 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6886 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
6887 if (MD->isVirtual())
6888 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6889
6890 // Otherwise they compare equal if and only if they would refer to the
6891 // same member of the same most derived object or the same subobject if
6892 // they were dereferenced with a hypothetical object of the associated
6893 // class type.
6894 bool Equal = LHSValue == RHSValue;
6895 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6896 }
6897
Richard Smithab44d9b2012-02-14 22:35:28 +00006898 if (LHSTy->isNullPtrType()) {
6899 assert(E->isComparisonOp() && "unexpected nullptr operation");
6900 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
6901 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
6902 // are compared, the result is true of the operator is <=, >= or ==, and
6903 // false otherwise.
6904 BinaryOperator::Opcode Opcode = E->getOpcode();
6905 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
6906 }
6907
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006908 assert((!LHSTy->isIntegralOrEnumerationType() ||
6909 !RHSTy->isIntegralOrEnumerationType()) &&
6910 "DataRecursiveIntBinOpEvaluator should have handled integral types");
6911 // We can't continue from here for non-integral types.
6912 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00006913}
6914
Ken Dyck160146e2010-01-27 17:10:57 +00006915CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00006916 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
6917 // result shall be the alignment of the referenced type."
6918 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6919 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00006920
6921 // __alignof is defined to return the preferred alignment.
6922 return Info.Ctx.toCharUnitsFromBits(
6923 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00006924}
6925
Ken Dyck160146e2010-01-27 17:10:57 +00006926CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00006927 E = E->IgnoreParens();
6928
John McCall768439e2013-05-06 07:40:34 +00006929 // The kinds of expressions that we have special-case logic here for
6930 // should be kept up to date with the special checks for those
6931 // expressions in Sema.
6932
Chris Lattner68061312009-01-24 21:53:27 +00006933 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00006934 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00006935 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006936 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6937 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00006938
Chris Lattner68061312009-01-24 21:53:27 +00006939 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006940 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6941 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00006942
Chris Lattner24aeeab2009-01-24 21:09:06 +00006943 return GetAlignOfType(E->getType());
6944}
6945
6946
Peter Collingbournee190dee2011-03-11 19:24:49 +00006947/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
6948/// a result as the expression's type.
6949bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
6950 const UnaryExprOrTypeTraitExpr *E) {
6951 switch(E->getKind()) {
6952 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00006953 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00006954 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006955 else
Ken Dyckdbc01912011-03-11 02:13:43 +00006956 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006957 }
Eli Friedman64004332009-03-23 04:38:34 +00006958
Peter Collingbournee190dee2011-03-11 19:24:49 +00006959 case UETT_VecStep: {
6960 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00006961
Peter Collingbournee190dee2011-03-11 19:24:49 +00006962 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00006963 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00006964
Peter Collingbournee190dee2011-03-11 19:24:49 +00006965 // The vec_step built-in functions that take a 3-component
6966 // vector return 4. (OpenCL 1.1 spec 6.11.12)
6967 if (n == 3)
6968 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00006969
Peter Collingbournee190dee2011-03-11 19:24:49 +00006970 return Success(n, E);
6971 } else
6972 return Success(1, E);
6973 }
6974
6975 case UETT_SizeOf: {
6976 QualType SrcTy = E->getTypeOfArgument();
6977 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
6978 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00006979 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
6980 SrcTy = Ref->getPointeeType();
6981
Richard Smithd62306a2011-11-10 06:34:14 +00006982 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00006983 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00006984 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006985 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006986 }
6987 }
6988
6989 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006990}
6991
Peter Collingbournee9200682011-05-13 03:29:01 +00006992bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00006993 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00006994 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00006995 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006996 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00006997 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00006998 for (unsigned i = 0; i != n; ++i) {
6999 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
7000 switch (ON.getKind()) {
7001 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00007002 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00007003 APSInt IdxResult;
7004 if (!EvaluateInteger(Idx, IdxResult, Info))
7005 return false;
7006 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
7007 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007008 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007009 CurrentType = AT->getElementType();
7010 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
7011 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00007012 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00007013 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007014
Douglas Gregor882211c2010-04-28 22:16:22 +00007015 case OffsetOfExpr::OffsetOfNode::Field: {
7016 FieldDecl *MemberDecl = ON.getField();
7017 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007018 if (!RT)
7019 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007020 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007021 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00007022 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00007023 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00007024 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00007025 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00007026 CurrentType = MemberDecl->getType().getNonReferenceType();
7027 break;
7028 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007029
Douglas Gregor882211c2010-04-28 22:16:22 +00007030 case OffsetOfExpr::OffsetOfNode::Identifier:
7031 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00007032
Douglas Gregord1702062010-04-29 00:18:15 +00007033 case OffsetOfExpr::OffsetOfNode::Base: {
7034 CXXBaseSpecifier *BaseSpec = ON.getBase();
7035 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007036 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007037
7038 // Find the layout of the class whose base we are looking into.
7039 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007040 if (!RT)
7041 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007042 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007043 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00007044 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7045
7046 // Find the base class itself.
7047 CurrentType = BaseSpec->getType();
7048 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7049 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007050 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007051
7052 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00007053 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00007054 break;
7055 }
Douglas Gregor882211c2010-04-28 22:16:22 +00007056 }
7057 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007058 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007059}
7060
Chris Lattnere13042c2008-07-11 19:10:17 +00007061bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007062 switch (E->getOpcode()) {
7063 default:
7064 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7065 // See C99 6.6p3.
7066 return Error(E);
7067 case UO_Extension:
7068 // FIXME: Should extension allow i-c-e extension expressions in its scope?
7069 // If so, we could clear the diagnostic ID.
7070 return Visit(E->getSubExpr());
7071 case UO_Plus:
7072 // The result is just the value.
7073 return Visit(E->getSubExpr());
7074 case UO_Minus: {
7075 if (!Visit(E->getSubExpr()))
7076 return false;
7077 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00007078 const APSInt &Value = Result.getInt();
7079 if (Value.isSigned() && Value.isMinSignedValue())
7080 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7081 E->getType());
7082 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007083 }
7084 case UO_Not: {
7085 if (!Visit(E->getSubExpr()))
7086 return false;
7087 if (!Result.isInt()) return Error(E);
7088 return Success(~Result.getInt(), E);
7089 }
7090 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00007091 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00007092 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00007093 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007094 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007095 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007096 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007097}
Mike Stump11289f42009-09-09 15:08:12 +00007098
Chris Lattner477c4be2008-07-12 01:15:53 +00007099/// HandleCast - This is used to evaluate implicit or explicit casts where the
7100/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00007101bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
7102 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007103 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00007104 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007105
Eli Friedmanc757de22011-03-25 00:43:55 +00007106 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00007107 case CK_BaseToDerived:
7108 case CK_DerivedToBase:
7109 case CK_UncheckedDerivedToBase:
7110 case CK_Dynamic:
7111 case CK_ToUnion:
7112 case CK_ArrayToPointerDecay:
7113 case CK_FunctionToPointerDecay:
7114 case CK_NullToPointer:
7115 case CK_NullToMemberPointer:
7116 case CK_BaseToDerivedMemberPointer:
7117 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00007118 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00007119 case CK_ConstructorConversion:
7120 case CK_IntegralToPointer:
7121 case CK_ToVoid:
7122 case CK_VectorSplat:
7123 case CK_IntegralToFloating:
7124 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007125 case CK_CPointerToObjCPointerCast:
7126 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007127 case CK_AnyPointerToBlockPointerCast:
7128 case CK_ObjCObjectLValueCast:
7129 case CK_FloatingRealToComplex:
7130 case CK_FloatingComplexToReal:
7131 case CK_FloatingComplexCast:
7132 case CK_FloatingComplexToIntegralComplex:
7133 case CK_IntegralRealToComplex:
7134 case CK_IntegralComplexCast:
7135 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00007136 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007137 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007138 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00007139 case CK_AddressSpaceConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007140 llvm_unreachable("invalid cast kind for integral value");
7141
Eli Friedman9faf2f92011-03-25 19:07:11 +00007142 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007143 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007144 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00007145 case CK_ARCProduceObject:
7146 case CK_ARCConsumeObject:
7147 case CK_ARCReclaimReturnedObject:
7148 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007149 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007150 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007151
Richard Smith4ef685b2012-01-17 21:17:26 +00007152 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007153 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007154 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00007155 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007156 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007157
7158 case CK_MemberPointerToBoolean:
7159 case CK_PointerToBoolean:
7160 case CK_IntegralToBoolean:
7161 case CK_FloatingToBoolean:
7162 case CK_FloatingComplexToBoolean:
7163 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007164 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00007165 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00007166 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007167 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007168 }
7169
Eli Friedmanc757de22011-03-25 00:43:55 +00007170 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00007171 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00007172 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00007173
Eli Friedman742421e2009-02-20 01:15:07 +00007174 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007175 // Allow casts of address-of-label differences if they are no-ops
7176 // or narrowing. (The narrowing case isn't actually guaranteed to
7177 // be constant-evaluatable except in some narrow cases which are hard
7178 // to detect here. We let it through on the assumption the user knows
7179 // what they are doing.)
7180 if (Result.isAddrLabelDiff())
7181 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00007182 // Only allow casts of lvalues if they are lossless.
7183 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
7184 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007185
Richard Smith911e1422012-01-30 22:27:01 +00007186 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
7187 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00007188 }
Mike Stump11289f42009-09-09 15:08:12 +00007189
Eli Friedmanc757de22011-03-25 00:43:55 +00007190 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00007191 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7192
John McCall45d55e42010-05-07 21:00:08 +00007193 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00007194 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00007195 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00007196
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007197 if (LV.getLValueBase()) {
7198 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00007199 // FIXME: Allow a larger integer size than the pointer size, and allow
7200 // narrowing back down to pointer width in subsequent integral casts.
7201 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007202 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007203 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007204
Richard Smithcf74da72011-11-16 07:18:12 +00007205 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00007206 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007207 return true;
7208 }
7209
Ken Dyck02990832010-01-15 12:37:54 +00007210 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
7211 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00007212 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007213 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007214
Eli Friedmanc757de22011-03-25 00:43:55 +00007215 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00007216 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007217 if (!EvaluateComplex(SubExpr, C, Info))
7218 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00007219 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007220 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00007221
Eli Friedmanc757de22011-03-25 00:43:55 +00007222 case CK_FloatingToIntegral: {
7223 APFloat F(0.0);
7224 if (!EvaluateFloat(SubExpr, F, Info))
7225 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00007226
Richard Smith357362d2011-12-13 06:39:58 +00007227 APSInt Value;
7228 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7229 return false;
7230 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007231 }
7232 }
Mike Stump11289f42009-09-09 15:08:12 +00007233
Eli Friedmanc757de22011-03-25 00:43:55 +00007234 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00007235}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007236
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007237bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7238 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007239 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007240 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7241 return false;
7242 if (!LV.isComplexInt())
7243 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007244 return Success(LV.getComplexIntReal(), E);
7245 }
7246
7247 return Visit(E->getSubExpr());
7248}
7249
Eli Friedman4e7a2412009-02-27 04:45:43 +00007250bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007251 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007252 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007253 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7254 return false;
7255 if (!LV.isComplexInt())
7256 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007257 return Success(LV.getComplexIntImag(), E);
7258 }
7259
Richard Smith4a678122011-10-24 18:44:57 +00007260 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00007261 return Success(0, E);
7262}
7263
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007264bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
7265 return Success(E->getPackLength(), E);
7266}
7267
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007268bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
7269 return Success(E->getValue(), E);
7270}
7271
Chris Lattner05706e882008-07-11 18:11:29 +00007272//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00007273// Float Evaluation
7274//===----------------------------------------------------------------------===//
7275
7276namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007277class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007278 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00007279 APFloat &Result;
7280public:
7281 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007282 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00007283
Richard Smith2e312c82012-03-03 22:46:17 +00007284 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007285 Result = V.getFloat();
7286 return true;
7287 }
Eli Friedman24c01542008-08-22 00:06:13 +00007288
Richard Smithfddd3842011-12-30 21:15:51 +00007289 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00007290 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
7291 return true;
7292 }
7293
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007294 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007295
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007296 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007297 bool VisitBinaryOperator(const BinaryOperator *E);
7298 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007299 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00007300
John McCallb1fb0d32010-05-07 22:08:54 +00007301 bool VisitUnaryReal(const UnaryOperator *E);
7302 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00007303
Richard Smithfddd3842011-12-30 21:15:51 +00007304 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00007305};
7306} // end anonymous namespace
7307
7308static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007309 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007310 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00007311}
7312
Jay Foad39c79802011-01-12 09:06:06 +00007313static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00007314 QualType ResultTy,
7315 const Expr *Arg,
7316 bool SNaN,
7317 llvm::APFloat &Result) {
7318 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
7319 if (!S) return false;
7320
7321 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
7322
7323 llvm::APInt fill;
7324
7325 // Treat empty strings as if they were zero.
7326 if (S->getString().empty())
7327 fill = llvm::APInt(32, 0);
7328 else if (S->getString().getAsInteger(0, fill))
7329 return false;
7330
7331 if (SNaN)
7332 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7333 else
7334 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7335 return true;
7336}
7337
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007338bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00007339 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007340 default:
7341 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7342
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007343 case Builtin::BI__builtin_huge_val:
7344 case Builtin::BI__builtin_huge_valf:
7345 case Builtin::BI__builtin_huge_vall:
7346 case Builtin::BI__builtin_inf:
7347 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007348 case Builtin::BI__builtin_infl: {
7349 const llvm::fltSemantics &Sem =
7350 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00007351 Result = llvm::APFloat::getInf(Sem);
7352 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007353 }
Mike Stump11289f42009-09-09 15:08:12 +00007354
John McCall16291492010-02-28 13:00:19 +00007355 case Builtin::BI__builtin_nans:
7356 case Builtin::BI__builtin_nansf:
7357 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007358 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7359 true, Result))
7360 return Error(E);
7361 return true;
John McCall16291492010-02-28 13:00:19 +00007362
Chris Lattner0b7282e2008-10-06 06:31:58 +00007363 case Builtin::BI__builtin_nan:
7364 case Builtin::BI__builtin_nanf:
7365 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00007366 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00007367 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00007368 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7369 false, Result))
7370 return Error(E);
7371 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007372
7373 case Builtin::BI__builtin_fabs:
7374 case Builtin::BI__builtin_fabsf:
7375 case Builtin::BI__builtin_fabsl:
7376 if (!EvaluateFloat(E->getArg(0), Result, Info))
7377 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007378
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007379 if (Result.isNegative())
7380 Result.changeSign();
7381 return true;
7382
Richard Smith8889a3d2013-06-13 06:26:32 +00007383 // FIXME: Builtin::BI__builtin_powi
7384 // FIXME: Builtin::BI__builtin_powif
7385 // FIXME: Builtin::BI__builtin_powil
7386
Mike Stump11289f42009-09-09 15:08:12 +00007387 case Builtin::BI__builtin_copysign:
7388 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007389 case Builtin::BI__builtin_copysignl: {
7390 APFloat RHS(0.);
7391 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
7392 !EvaluateFloat(E->getArg(1), RHS, Info))
7393 return false;
7394 Result.copySign(RHS);
7395 return true;
7396 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007397 }
7398}
7399
John McCallb1fb0d32010-05-07 22:08:54 +00007400bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007401 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7402 ComplexValue CV;
7403 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7404 return false;
7405 Result = CV.FloatReal;
7406 return true;
7407 }
7408
7409 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00007410}
7411
7412bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007413 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7414 ComplexValue CV;
7415 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7416 return false;
7417 Result = CV.FloatImag;
7418 return true;
7419 }
7420
Richard Smith4a678122011-10-24 18:44:57 +00007421 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00007422 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
7423 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00007424 return true;
7425}
7426
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007427bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007428 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007429 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007430 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00007431 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00007432 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00007433 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
7434 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007435 Result.changeSign();
7436 return true;
7437 }
7438}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007439
Eli Friedman24c01542008-08-22 00:06:13 +00007440bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007441 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7442 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00007443
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007444 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00007445 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
7446 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00007447 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00007448 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
7449 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00007450}
7451
7452bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
7453 Result = E->getValue();
7454 return true;
7455}
7456
Peter Collingbournee9200682011-05-13 03:29:01 +00007457bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
7458 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00007459
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007460 switch (E->getCastKind()) {
7461 default:
Richard Smith11562c52011-10-28 17:51:58 +00007462 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007463
7464 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007465 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00007466 return EvaluateInteger(SubExpr, IntResult, Info) &&
7467 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
7468 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007469 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007470
7471 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007472 if (!Visit(SubExpr))
7473 return false;
Richard Smith357362d2011-12-13 06:39:58 +00007474 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
7475 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007476 }
John McCalld7646252010-11-14 08:17:51 +00007477
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007478 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00007479 ComplexValue V;
7480 if (!EvaluateComplex(SubExpr, V, Info))
7481 return false;
7482 Result = V.getComplexFloatReal();
7483 return true;
7484 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007485 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007486}
7487
Eli Friedman24c01542008-08-22 00:06:13 +00007488//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007489// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00007490//===----------------------------------------------------------------------===//
7491
7492namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007493class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007494 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00007495 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00007496
Anders Carlsson537969c2008-11-16 20:27:53 +00007497public:
John McCall93d91dc2010-05-07 17:22:02 +00007498 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007499 : ExprEvaluatorBaseTy(info), Result(Result) {}
7500
Richard Smith2e312c82012-03-03 22:46:17 +00007501 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007502 Result.setFrom(V);
7503 return true;
7504 }
Mike Stump11289f42009-09-09 15:08:12 +00007505
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007506 bool ZeroInitialization(const Expr *E);
7507
Anders Carlsson537969c2008-11-16 20:27:53 +00007508 //===--------------------------------------------------------------------===//
7509 // Visitor Methods
7510 //===--------------------------------------------------------------------===//
7511
Peter Collingbournee9200682011-05-13 03:29:01 +00007512 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007513 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00007514 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007515 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007516 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007517};
7518} // end anonymous namespace
7519
John McCall93d91dc2010-05-07 17:22:02 +00007520static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
7521 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007522 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007523 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007524}
7525
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007526bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00007527 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007528 if (ElemTy->isRealFloatingType()) {
7529 Result.makeComplexFloat();
7530 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
7531 Result.FloatReal = Zero;
7532 Result.FloatImag = Zero;
7533 } else {
7534 Result.makeComplexInt();
7535 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
7536 Result.IntReal = Zero;
7537 Result.IntImag = Zero;
7538 }
7539 return true;
7540}
7541
Peter Collingbournee9200682011-05-13 03:29:01 +00007542bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
7543 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007544
7545 if (SubExpr->getType()->isRealFloatingType()) {
7546 Result.makeComplexFloat();
7547 APFloat &Imag = Result.FloatImag;
7548 if (!EvaluateFloat(SubExpr, Imag, Info))
7549 return false;
7550
7551 Result.FloatReal = APFloat(Imag.getSemantics());
7552 return true;
7553 } else {
7554 assert(SubExpr->getType()->isIntegerType() &&
7555 "Unexpected imaginary literal.");
7556
7557 Result.makeComplexInt();
7558 APSInt &Imag = Result.IntImag;
7559 if (!EvaluateInteger(SubExpr, Imag, Info))
7560 return false;
7561
7562 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
7563 return true;
7564 }
7565}
7566
Peter Collingbournee9200682011-05-13 03:29:01 +00007567bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007568
John McCallfcef3cf2010-12-14 17:51:41 +00007569 switch (E->getCastKind()) {
7570 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007571 case CK_BaseToDerived:
7572 case CK_DerivedToBase:
7573 case CK_UncheckedDerivedToBase:
7574 case CK_Dynamic:
7575 case CK_ToUnion:
7576 case CK_ArrayToPointerDecay:
7577 case CK_FunctionToPointerDecay:
7578 case CK_NullToPointer:
7579 case CK_NullToMemberPointer:
7580 case CK_BaseToDerivedMemberPointer:
7581 case CK_DerivedToBaseMemberPointer:
7582 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00007583 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00007584 case CK_ConstructorConversion:
7585 case CK_IntegralToPointer:
7586 case CK_PointerToIntegral:
7587 case CK_PointerToBoolean:
7588 case CK_ToVoid:
7589 case CK_VectorSplat:
7590 case CK_IntegralCast:
7591 case CK_IntegralToBoolean:
7592 case CK_IntegralToFloating:
7593 case CK_FloatingToIntegral:
7594 case CK_FloatingToBoolean:
7595 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007596 case CK_CPointerToObjCPointerCast:
7597 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007598 case CK_AnyPointerToBlockPointerCast:
7599 case CK_ObjCObjectLValueCast:
7600 case CK_FloatingComplexToReal:
7601 case CK_FloatingComplexToBoolean:
7602 case CK_IntegralComplexToReal:
7603 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00007604 case CK_ARCProduceObject:
7605 case CK_ARCConsumeObject:
7606 case CK_ARCReclaimReturnedObject:
7607 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007608 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00007609 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007610 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007611 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00007612 case CK_AddressSpaceConversion:
John McCallfcef3cf2010-12-14 17:51:41 +00007613 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00007614
John McCallfcef3cf2010-12-14 17:51:41 +00007615 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007616 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00007617 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007618 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007619
7620 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007621 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007622 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007623 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007624
7625 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007626 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00007627 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007628 return false;
7629
John McCallfcef3cf2010-12-14 17:51:41 +00007630 Result.makeComplexFloat();
7631 Result.FloatImag = APFloat(Real.getSemantics());
7632 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007633 }
7634
John McCallfcef3cf2010-12-14 17:51:41 +00007635 case CK_FloatingComplexCast: {
7636 if (!Visit(E->getSubExpr()))
7637 return false;
7638
7639 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7640 QualType From
7641 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7642
Richard Smith357362d2011-12-13 06:39:58 +00007643 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
7644 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007645 }
7646
7647 case CK_FloatingComplexToIntegralComplex: {
7648 if (!Visit(E->getSubExpr()))
7649 return false;
7650
7651 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7652 QualType From
7653 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7654 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00007655 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
7656 To, Result.IntReal) &&
7657 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
7658 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007659 }
7660
7661 case CK_IntegralRealToComplex: {
7662 APSInt &Real = Result.IntReal;
7663 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
7664 return false;
7665
7666 Result.makeComplexInt();
7667 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
7668 return true;
7669 }
7670
7671 case CK_IntegralComplexCast: {
7672 if (!Visit(E->getSubExpr()))
7673 return false;
7674
7675 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7676 QualType From
7677 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7678
Richard Smith911e1422012-01-30 22:27:01 +00007679 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7680 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007681 return true;
7682 }
7683
7684 case CK_IntegralComplexToFloatingComplex: {
7685 if (!Visit(E->getSubExpr()))
7686 return false;
7687
Ted Kremenek28831752012-08-23 20:46:57 +00007688 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007689 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00007690 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007691 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00007692 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7693 To, Result.FloatReal) &&
7694 HandleIntToFloatCast(Info, E, From, Result.IntImag,
7695 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007696 }
7697 }
7698
7699 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007700}
7701
John McCall93d91dc2010-05-07 17:22:02 +00007702bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007703 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00007704 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7705
Richard Smith253c2a32012-01-27 01:14:48 +00007706 bool LHSOK = Visit(E->getLHS());
7707 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00007708 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007709
John McCall93d91dc2010-05-07 17:22:02 +00007710 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00007711 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00007712 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007713
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007714 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
7715 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007716 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007717 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007718 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007719 if (Result.isComplexFloat()) {
7720 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
7721 APFloat::rmNearestTiesToEven);
7722 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
7723 APFloat::rmNearestTiesToEven);
7724 } else {
7725 Result.getComplexIntReal() += RHS.getComplexIntReal();
7726 Result.getComplexIntImag() += RHS.getComplexIntImag();
7727 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007728 break;
John McCalle3027922010-08-25 11:45:40 +00007729 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007730 if (Result.isComplexFloat()) {
7731 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
7732 APFloat::rmNearestTiesToEven);
7733 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
7734 APFloat::rmNearestTiesToEven);
7735 } else {
7736 Result.getComplexIntReal() -= RHS.getComplexIntReal();
7737 Result.getComplexIntImag() -= RHS.getComplexIntImag();
7738 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007739 break;
John McCalle3027922010-08-25 11:45:40 +00007740 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007741 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00007742 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007743 APFloat &LHS_r = LHS.getComplexFloatReal();
7744 APFloat &LHS_i = LHS.getComplexFloatImag();
7745 APFloat &RHS_r = RHS.getComplexFloatReal();
7746 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00007747
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007748 APFloat Tmp = LHS_r;
7749 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7750 Result.getComplexFloatReal() = Tmp;
7751 Tmp = LHS_i;
7752 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7753 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
7754
7755 Tmp = LHS_r;
7756 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7757 Result.getComplexFloatImag() = Tmp;
7758 Tmp = LHS_i;
7759 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7760 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
7761 } else {
John McCall93d91dc2010-05-07 17:22:02 +00007762 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00007763 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007764 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
7765 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00007766 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007767 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
7768 LHS.getComplexIntImag() * RHS.getComplexIntReal());
7769 }
7770 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007771 case BO_Div:
7772 if (Result.isComplexFloat()) {
7773 ComplexValue LHS = Result;
7774 APFloat &LHS_r = LHS.getComplexFloatReal();
7775 APFloat &LHS_i = LHS.getComplexFloatImag();
7776 APFloat &RHS_r = RHS.getComplexFloatReal();
7777 APFloat &RHS_i = RHS.getComplexFloatImag();
7778 APFloat &Res_r = Result.getComplexFloatReal();
7779 APFloat &Res_i = Result.getComplexFloatImag();
7780
7781 APFloat Den = RHS_r;
7782 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7783 APFloat Tmp = RHS_i;
7784 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7785 Den.add(Tmp, APFloat::rmNearestTiesToEven);
7786
7787 Res_r = LHS_r;
7788 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7789 Tmp = LHS_i;
7790 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7791 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
7792 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
7793
7794 Res_i = LHS_i;
7795 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7796 Tmp = LHS_r;
7797 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7798 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
7799 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
7800 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007801 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
7802 return Error(E, diag::note_expr_divide_by_zero);
7803
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007804 ComplexValue LHS = Result;
7805 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
7806 RHS.getComplexIntImag() * RHS.getComplexIntImag();
7807 Result.getComplexIntReal() =
7808 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
7809 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
7810 Result.getComplexIntImag() =
7811 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
7812 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
7813 }
7814 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007815 }
7816
John McCall93d91dc2010-05-07 17:22:02 +00007817 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007818}
7819
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007820bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7821 // Get the operand value into 'Result'.
7822 if (!Visit(E->getSubExpr()))
7823 return false;
7824
7825 switch (E->getOpcode()) {
7826 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007827 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007828 case UO_Extension:
7829 return true;
7830 case UO_Plus:
7831 // The result is always just the subexpr.
7832 return true;
7833 case UO_Minus:
7834 if (Result.isComplexFloat()) {
7835 Result.getComplexFloatReal().changeSign();
7836 Result.getComplexFloatImag().changeSign();
7837 }
7838 else {
7839 Result.getComplexIntReal() = -Result.getComplexIntReal();
7840 Result.getComplexIntImag() = -Result.getComplexIntImag();
7841 }
7842 return true;
7843 case UO_Not:
7844 if (Result.isComplexFloat())
7845 Result.getComplexFloatImag().changeSign();
7846 else
7847 Result.getComplexIntImag() = -Result.getComplexIntImag();
7848 return true;
7849 }
7850}
7851
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007852bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7853 if (E->getNumInits() == 2) {
7854 if (E->getType()->isComplexType()) {
7855 Result.makeComplexFloat();
7856 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
7857 return false;
7858 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
7859 return false;
7860 } else {
7861 Result.makeComplexInt();
7862 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
7863 return false;
7864 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
7865 return false;
7866 }
7867 return true;
7868 }
7869 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
7870}
7871
Anders Carlsson537969c2008-11-16 20:27:53 +00007872//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00007873// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
7874// implicit conversion.
7875//===----------------------------------------------------------------------===//
7876
7877namespace {
7878class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00007879 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00007880 APValue &Result;
7881public:
7882 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
7883 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7884
7885 bool Success(const APValue &V, const Expr *E) {
7886 Result = V;
7887 return true;
7888 }
7889
7890 bool ZeroInitialization(const Expr *E) {
7891 ImplicitValueInitExpr VIE(
7892 E->getType()->castAs<AtomicType>()->getValueType());
7893 return Evaluate(Result, Info, &VIE);
7894 }
7895
7896 bool VisitCastExpr(const CastExpr *E) {
7897 switch (E->getCastKind()) {
7898 default:
7899 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7900 case CK_NonAtomicToAtomic:
7901 return Evaluate(Result, Info, E->getSubExpr());
7902 }
7903 }
7904};
7905} // end anonymous namespace
7906
7907static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
7908 assert(E->isRValue() && E->getType()->isAtomicType());
7909 return AtomicExprEvaluator(Info, Result).Visit(E);
7910}
7911
7912//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00007913// Void expression evaluation, primarily for a cast to void on the LHS of a
7914// comma operator
7915//===----------------------------------------------------------------------===//
7916
7917namespace {
7918class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007919 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00007920public:
7921 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
7922
Richard Smith2e312c82012-03-03 22:46:17 +00007923 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00007924
7925 bool VisitCastExpr(const CastExpr *E) {
7926 switch (E->getCastKind()) {
7927 default:
7928 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7929 case CK_ToVoid:
7930 VisitIgnoredValue(E->getSubExpr());
7931 return true;
7932 }
7933 }
7934};
7935} // end anonymous namespace
7936
7937static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
7938 assert(E->isRValue() && E->getType()->isVoidType());
7939 return VoidExprEvaluator(Info).Visit(E);
7940}
7941
7942//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00007943// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00007944//===----------------------------------------------------------------------===//
7945
Richard Smith2e312c82012-03-03 22:46:17 +00007946static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007947 // In C, function designators are not lvalues, but we evaluate them as if they
7948 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00007949 QualType T = E->getType();
7950 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00007951 LValue LV;
7952 if (!EvaluateLValue(E, LV, Info))
7953 return false;
7954 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007955 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007956 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007957 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007958 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007959 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007960 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007961 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00007962 LValue LV;
7963 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007964 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007965 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007966 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00007967 llvm::APFloat F(0.0);
7968 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007969 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007970 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00007971 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00007972 ComplexValue C;
7973 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007974 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007975 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007976 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00007977 MemberPtr P;
7978 if (!EvaluateMemberPointer(E, P, Info))
7979 return false;
7980 P.moveInto(Result);
7981 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00007982 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007983 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007984 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00007985 APValue &Value = Info.CurrentCall->createTemporary(E, false);
7986 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00007987 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00007988 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00007989 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007990 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007991 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00007992 APValue &Value = Info.CurrentCall->createTemporary(E, false);
7993 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00007994 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00007995 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00007996 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007997 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007998 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00007999 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00008000 if (!EvaluateVoid(E, Info))
8001 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008002 } else if (T->isAtomicType()) {
8003 if (!EvaluateAtomic(E, Result, Info))
8004 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008005 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008006 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00008007 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008008 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008009 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00008010 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008011 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008012
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00008013 return true;
8014}
8015
Richard Smithb228a862012-02-15 02:18:13 +00008016/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
8017/// cases, the in-place evaluation is essential, since later initializers for
8018/// an object can indirectly refer to subobjects which were initialized earlier.
8019static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00008020 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00008021 assert(!E->isValueDependent());
8022
Richard Smith7525ff62013-05-09 07:14:00 +00008023 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00008024 return false;
8025
8026 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00008027 // Evaluate arrays and record types in-place, so that later initializers can
8028 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00008029 if (E->getType()->isArrayType())
8030 return EvaluateArray(E, This, Result, Info);
8031 else if (E->getType()->isRecordType())
8032 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00008033 }
8034
8035 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00008036 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00008037}
8038
Richard Smithf57d8cb2011-12-09 22:58:01 +00008039/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
8040/// lvalue-to-rvalue cast if it is an lvalue.
8041static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00008042 if (!CheckLiteralType(Info, E))
8043 return false;
8044
Richard Smith2e312c82012-03-03 22:46:17 +00008045 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008046 return false;
8047
8048 if (E->isGLValue()) {
8049 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00008050 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00008051 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008052 return false;
8053 }
8054
Richard Smith2e312c82012-03-03 22:46:17 +00008055 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00008056 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008057}
Richard Smith11562c52011-10-28 17:51:58 +00008058
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008059static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
8060 const ASTContext &Ctx, bool &IsConst) {
8061 // Fast-path evaluations of integer literals, since we sometimes see files
8062 // containing vast quantities of these.
8063 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
8064 Result.Val = APValue(APSInt(L->getValue(),
8065 L->getType()->isUnsignedIntegerType()));
8066 IsConst = true;
8067 return true;
8068 }
8069
8070 // FIXME: Evaluating values of large array and record types can cause
8071 // performance problems. Only do so in C++11 for now.
8072 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
8073 Exp->getType()->isRecordType()) &&
8074 !Ctx.getLangOpts().CPlusPlus11) {
8075 IsConst = false;
8076 return true;
8077 }
8078 return false;
8079}
8080
8081
Richard Smith7b553f12011-10-29 00:50:52 +00008082/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00008083/// any crazy technique (that has nothing to do with language standards) that
8084/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00008085/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
8086/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00008087bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008088 bool IsConst;
8089 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
8090 return IsConst;
8091
Richard Smith6d4c6582013-11-05 22:18:15 +00008092 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008093 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00008094}
8095
Jay Foad39c79802011-01-12 09:06:06 +00008096bool Expr::EvaluateAsBooleanCondition(bool &Result,
8097 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00008098 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00008099 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00008100 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00008101}
8102
Richard Smith5fab0c92011-12-28 19:48:30 +00008103bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
8104 SideEffectsKind AllowSideEffects) const {
8105 if (!getType()->isIntegralOrEnumerationType())
8106 return false;
8107
Richard Smith11562c52011-10-28 17:51:58 +00008108 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00008109 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
8110 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00008111 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008112
Richard Smith11562c52011-10-28 17:51:58 +00008113 Result = ExprResult.Val.getInt();
8114 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00008115}
8116
Jay Foad39c79802011-01-12 09:06:06 +00008117bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00008118 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00008119
John McCall45d55e42010-05-07 21:00:08 +00008120 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008121 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
8122 !CheckLValueConstantExpression(Info, getExprLoc(),
8123 Ctx.getLValueReferenceType(getType()), LV))
8124 return false;
8125
Richard Smith2e312c82012-03-03 22:46:17 +00008126 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00008127 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00008128}
8129
Richard Smithd0b4dd62011-12-19 06:19:21 +00008130bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
8131 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008132 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00008133 // FIXME: Evaluating initializers for large array and record types can cause
8134 // performance problems. Only do so in C++11 for now.
8135 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008136 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00008137 return false;
8138
Richard Smithd0b4dd62011-12-19 06:19:21 +00008139 Expr::EvalStatus EStatus;
8140 EStatus.Diag = &Notes;
8141
Richard Smith6d4c6582013-11-05 22:18:15 +00008142 EvalInfo InitInfo(Ctx, EStatus, EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008143 InitInfo.setEvaluatingDecl(VD, Value);
8144
8145 LValue LVal;
8146 LVal.set(VD);
8147
Richard Smithfddd3842011-12-30 21:15:51 +00008148 // C++11 [basic.start.init]p2:
8149 // Variables with static storage duration or thread storage duration shall be
8150 // zero-initialized before any other initialization takes place.
8151 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008152 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00008153 !VD->getType()->isReferenceType()) {
8154 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00008155 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00008156 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00008157 return false;
8158 }
8159
Richard Smith7525ff62013-05-09 07:14:00 +00008160 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
8161 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00008162 EStatus.HasSideEffects)
8163 return false;
8164
8165 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
8166 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008167}
8168
Richard Smith7b553f12011-10-29 00:50:52 +00008169/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
8170/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00008171bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00008172 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00008173 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00008174}
Anders Carlsson59689ed2008-11-22 21:04:56 +00008175
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008176APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008177 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008178 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008179 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00008180 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00008181 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00008182 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008183 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00008184
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008185 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00008186}
John McCall864e3962010-05-07 05:32:02 +00008187
Richard Smithe9ff7702013-11-05 22:23:30 +00008188void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008189 bool IsConst;
8190 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008191 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00008192 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008193 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
8194 }
8195}
8196
Richard Smithe6c01442013-06-05 00:46:14 +00008197bool Expr::EvalResult::isGlobalLValue() const {
8198 assert(Val.isLValue());
8199 return IsGlobalLValue(Val.getLValueBase());
8200}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00008201
8202
John McCall864e3962010-05-07 05:32:02 +00008203/// isIntegerConstantExpr - this recursive routine will test if an expression is
8204/// an integer constant expression.
8205
8206/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
8207/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00008208
8209// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00008210// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
8211// and a (possibly null) SourceLocation indicating the location of the problem.
8212//
John McCall864e3962010-05-07 05:32:02 +00008213// Note that to reduce code duplication, this helper does no evaluation
8214// itself; the caller checks whether the expression is evaluatable, and
8215// in the rare cases where CheckICE actually cares about the evaluated
8216// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00008217
Dan Gohman28ade552010-07-26 21:25:24 +00008218namespace {
8219
Richard Smith9e575da2012-12-28 13:25:52 +00008220enum ICEKind {
8221 /// This expression is an ICE.
8222 IK_ICE,
8223 /// This expression is not an ICE, but if it isn't evaluated, it's
8224 /// a legal subexpression for an ICE. This return value is used to handle
8225 /// the comma operator in C99 mode, and non-constant subexpressions.
8226 IK_ICEIfUnevaluated,
8227 /// This expression is not an ICE, and is not a legal subexpression for one.
8228 IK_NotICE
8229};
8230
John McCall864e3962010-05-07 05:32:02 +00008231struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00008232 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00008233 SourceLocation Loc;
8234
Richard Smith9e575da2012-12-28 13:25:52 +00008235 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00008236};
8237
Dan Gohman28ade552010-07-26 21:25:24 +00008238}
8239
Richard Smith9e575da2012-12-28 13:25:52 +00008240static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
8241
8242static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00008243
Craig Toppera31a8822013-08-22 07:09:37 +00008244static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008245 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00008246 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00008247 !EVResult.Val.isInt())
8248 return ICEDiag(IK_NotICE, E->getLocStart());
8249
John McCall864e3962010-05-07 05:32:02 +00008250 return NoDiag();
8251}
8252
Craig Toppera31a8822013-08-22 07:09:37 +00008253static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008254 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00008255 if (!E->getType()->isIntegralOrEnumerationType())
8256 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008257
8258 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00008259#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00008260#define STMT(Node, Base) case Expr::Node##Class:
8261#define EXPR(Node, Base)
8262#include "clang/AST/StmtNodes.inc"
8263 case Expr::PredefinedExprClass:
8264 case Expr::FloatingLiteralClass:
8265 case Expr::ImaginaryLiteralClass:
8266 case Expr::StringLiteralClass:
8267 case Expr::ArraySubscriptExprClass:
8268 case Expr::MemberExprClass:
8269 case Expr::CompoundAssignOperatorClass:
8270 case Expr::CompoundLiteralExprClass:
8271 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00008272 case Expr::DesignatedInitExprClass:
8273 case Expr::ImplicitValueInitExprClass:
8274 case Expr::ParenListExprClass:
8275 case Expr::VAArgExprClass:
8276 case Expr::AddrLabelExprClass:
8277 case Expr::StmtExprClass:
8278 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00008279 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00008280 case Expr::CXXDynamicCastExprClass:
8281 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00008282 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00008283 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008284 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00008285 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008286 case Expr::CXXThisExprClass:
8287 case Expr::CXXThrowExprClass:
8288 case Expr::CXXNewExprClass:
8289 case Expr::CXXDeleteExprClass:
8290 case Expr::CXXPseudoDestructorExprClass:
8291 case Expr::UnresolvedLookupExprClass:
8292 case Expr::DependentScopeDeclRefExprClass:
8293 case Expr::CXXConstructExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00008294 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00008295 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00008296 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00008297 case Expr::CXXTemporaryObjectExprClass:
8298 case Expr::CXXUnresolvedConstructExprClass:
8299 case Expr::CXXDependentScopeMemberExprClass:
8300 case Expr::UnresolvedMemberExprClass:
8301 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00008302 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008303 case Expr::ObjCArrayLiteralClass:
8304 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008305 case Expr::ObjCEncodeExprClass:
8306 case Expr::ObjCMessageExprClass:
8307 case Expr::ObjCSelectorExprClass:
8308 case Expr::ObjCProtocolExprClass:
8309 case Expr::ObjCIvarRefExprClass:
8310 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008311 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008312 case Expr::ObjCIsaExprClass:
8313 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00008314 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +00008315 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00008316 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00008317 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00008318 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00008319 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00008320 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00008321 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00008322 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00008323 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00008324 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00008325 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00008326 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00008327 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00008328
Richard Smithf137f932014-01-25 20:50:08 +00008329 case Expr::InitListExprClass: {
8330 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
8331 // form "T x = { a };" is equivalent to "T x = a;".
8332 // Unless we're initializing a reference, T is a scalar as it is known to be
8333 // of integral or enumeration type.
8334 if (E->isRValue())
8335 if (cast<InitListExpr>(E)->getNumInits() == 1)
8336 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
8337 return ICEDiag(IK_NotICE, E->getLocStart());
8338 }
8339
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008340 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00008341 case Expr::GNUNullExprClass:
8342 // GCC considers the GNU __null value to be an integral constant expression.
8343 return NoDiag();
8344
John McCall7c454bb2011-07-15 05:09:51 +00008345 case Expr::SubstNonTypeTemplateParmExprClass:
8346 return
8347 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
8348
John McCall864e3962010-05-07 05:32:02 +00008349 case Expr::ParenExprClass:
8350 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00008351 case Expr::GenericSelectionExprClass:
8352 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008353 case Expr::IntegerLiteralClass:
8354 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008355 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00008356 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00008357 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00008358 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00008359 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00008360 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00008361 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00008362 return NoDiag();
8363 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00008364 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00008365 // C99 6.6/3 allows function calls within unevaluated subexpressions of
8366 // constant expressions, but they can never be ICEs because an ICE cannot
8367 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00008368 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +00008369 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +00008370 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008371 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008372 }
Richard Smith6365c912012-02-24 22:12:32 +00008373 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008374 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
8375 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00008376 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008377 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00008378 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00008379 // Parameter variables are never constants. Without this check,
8380 // getAnyInitializer() can find a default argument, which leads
8381 // to chaos.
8382 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00008383 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008384
8385 // C++ 7.1.5.1p2
8386 // A variable of non-volatile const-qualified integral or enumeration
8387 // type initialized by an ICE can be used in ICEs.
8388 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00008389 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00008390 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00008391
Richard Smithd0b4dd62011-12-19 06:19:21 +00008392 const VarDecl *VD;
8393 // Look for a declaration of this variable that has an initializer, and
8394 // check whether it is an ICE.
8395 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
8396 return NoDiag();
8397 else
Richard Smith9e575da2012-12-28 13:25:52 +00008398 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008399 }
8400 }
Richard Smith9e575da2012-12-28 13:25:52 +00008401 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00008402 }
John McCall864e3962010-05-07 05:32:02 +00008403 case Expr::UnaryOperatorClass: {
8404 const UnaryOperator *Exp = cast<UnaryOperator>(E);
8405 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008406 case UO_PostInc:
8407 case UO_PostDec:
8408 case UO_PreInc:
8409 case UO_PreDec:
8410 case UO_AddrOf:
8411 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00008412 // C99 6.6/3 allows increment and decrement within unevaluated
8413 // subexpressions of constant expressions, but they can never be ICEs
8414 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008415 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00008416 case UO_Extension:
8417 case UO_LNot:
8418 case UO_Plus:
8419 case UO_Minus:
8420 case UO_Not:
8421 case UO_Real:
8422 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00008423 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008424 }
Richard Smith9e575da2012-12-28 13:25:52 +00008425
John McCall864e3962010-05-07 05:32:02 +00008426 // OffsetOf falls through here.
8427 }
8428 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00008429 // Note that per C99, offsetof must be an ICE. And AFAIK, using
8430 // EvaluateAsRValue matches the proposed gcc behavior for cases like
8431 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
8432 // compliance: we should warn earlier for offsetof expressions with
8433 // array subscripts that aren't ICEs, and if the array subscripts
8434 // are ICEs, the value of the offsetof must be an integer constant.
8435 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008436 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00008437 case Expr::UnaryExprOrTypeTraitExprClass: {
8438 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
8439 if ((Exp->getKind() == UETT_SizeOf) &&
8440 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00008441 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008442 return NoDiag();
8443 }
8444 case Expr::BinaryOperatorClass: {
8445 const BinaryOperator *Exp = cast<BinaryOperator>(E);
8446 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008447 case BO_PtrMemD:
8448 case BO_PtrMemI:
8449 case BO_Assign:
8450 case BO_MulAssign:
8451 case BO_DivAssign:
8452 case BO_RemAssign:
8453 case BO_AddAssign:
8454 case BO_SubAssign:
8455 case BO_ShlAssign:
8456 case BO_ShrAssign:
8457 case BO_AndAssign:
8458 case BO_XorAssign:
8459 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00008460 // C99 6.6/3 allows assignments within unevaluated subexpressions of
8461 // constant expressions, but they can never be ICEs because an ICE cannot
8462 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008463 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008464
John McCalle3027922010-08-25 11:45:40 +00008465 case BO_Mul:
8466 case BO_Div:
8467 case BO_Rem:
8468 case BO_Add:
8469 case BO_Sub:
8470 case BO_Shl:
8471 case BO_Shr:
8472 case BO_LT:
8473 case BO_GT:
8474 case BO_LE:
8475 case BO_GE:
8476 case BO_EQ:
8477 case BO_NE:
8478 case BO_And:
8479 case BO_Xor:
8480 case BO_Or:
8481 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00008482 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8483 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00008484 if (Exp->getOpcode() == BO_Div ||
8485 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00008486 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00008487 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00008488 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00008489 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008490 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00008491 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008492 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00008493 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008494 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00008495 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008496 }
8497 }
8498 }
John McCalle3027922010-08-25 11:45:40 +00008499 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008500 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00008501 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
8502 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00008503 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
8504 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008505 } else {
8506 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00008507 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008508 }
8509 }
Richard Smith9e575da2012-12-28 13:25:52 +00008510 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008511 }
John McCalle3027922010-08-25 11:45:40 +00008512 case BO_LAnd:
8513 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00008514 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8515 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008516 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00008517 // Rare case where the RHS has a comma "side-effect"; we need
8518 // to actually check the condition to see whether the side
8519 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00008520 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00008521 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00008522 return RHSResult;
8523 return NoDiag();
8524 }
8525
Richard Smith9e575da2012-12-28 13:25:52 +00008526 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008527 }
8528 }
8529 }
8530 case Expr::ImplicitCastExprClass:
8531 case Expr::CStyleCastExprClass:
8532 case Expr::CXXFunctionalCastExprClass:
8533 case Expr::CXXStaticCastExprClass:
8534 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00008535 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00008536 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008537 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00008538 if (isa<ExplicitCastExpr>(E)) {
8539 if (const FloatingLiteral *FL
8540 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
8541 unsigned DestWidth = Ctx.getIntWidth(E->getType());
8542 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
8543 APSInt IgnoredVal(DestWidth, !DestSigned);
8544 bool Ignored;
8545 // If the value does not fit in the destination type, the behavior is
8546 // undefined, so we are not required to treat it as a constant
8547 // expression.
8548 if (FL->getValue().convertToInteger(IgnoredVal,
8549 llvm::APFloat::rmTowardZero,
8550 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00008551 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00008552 return NoDiag();
8553 }
8554 }
Eli Friedman76d4e432011-09-29 21:49:34 +00008555 switch (cast<CastExpr>(E)->getCastKind()) {
8556 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008557 case CK_AtomicToNonAtomic:
8558 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00008559 case CK_NoOp:
8560 case CK_IntegralToBoolean:
8561 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00008562 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00008563 default:
Richard Smith9e575da2012-12-28 13:25:52 +00008564 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00008565 }
John McCall864e3962010-05-07 05:32:02 +00008566 }
John McCallc07a0c72011-02-17 10:25:35 +00008567 case Expr::BinaryConditionalOperatorClass: {
8568 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
8569 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008570 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00008571 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008572 if (FalseResult.Kind == IK_NotICE) return FalseResult;
8573 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
8574 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00008575 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00008576 return FalseResult;
8577 }
John McCall864e3962010-05-07 05:32:02 +00008578 case Expr::ConditionalOperatorClass: {
8579 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
8580 // If the condition (ignoring parens) is a __builtin_constant_p call,
8581 // then only the true side is actually considered in an integer constant
8582 // expression, and it is fully evaluated. This is an important GNU
8583 // extension. See GCC PR38377 for discussion.
8584 if (const CallExpr *CallCE
8585 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00008586 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +00008587 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008588 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008589 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008590 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008591
Richard Smithf57d8cb2011-12-09 22:58:01 +00008592 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
8593 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008594
Richard Smith9e575da2012-12-28 13:25:52 +00008595 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008596 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008597 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008598 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008599 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00008600 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008601 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00008602 return NoDiag();
8603 // Rare case where the diagnostics depend on which side is evaluated
8604 // Note that if we get here, CondResult is 0, and at least one of
8605 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00008606 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00008607 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00008608 return TrueResult;
8609 }
8610 case Expr::CXXDefaultArgExprClass:
8611 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00008612 case Expr::CXXDefaultInitExprClass:
8613 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008614 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +00008615 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008616 }
8617 }
8618
David Blaikiee4d798f2012-01-20 21:50:17 +00008619 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00008620}
8621
Richard Smithf57d8cb2011-12-09 22:58:01 +00008622/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +00008623static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00008624 const Expr *E,
8625 llvm::APSInt *Value,
8626 SourceLocation *Loc) {
8627 if (!E->getType()->isIntegralOrEnumerationType()) {
8628 if (Loc) *Loc = E->getExprLoc();
8629 return false;
8630 }
8631
Richard Smith66e05fe2012-01-18 05:21:49 +00008632 APValue Result;
8633 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00008634 return false;
8635
Richard Smith66e05fe2012-01-18 05:21:49 +00008636 assert(Result.isInt() && "pointer cast to int is not an ICE");
8637 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00008638 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008639}
8640
Craig Toppera31a8822013-08-22 07:09:37 +00008641bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
8642 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008643 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008644 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
8645
Richard Smith9e575da2012-12-28 13:25:52 +00008646 ICEDiag D = CheckICE(this, Ctx);
8647 if (D.Kind != IK_ICE) {
8648 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00008649 return false;
8650 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008651 return true;
8652}
8653
Craig Toppera31a8822013-08-22 07:09:37 +00008654bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00008655 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008656 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008657 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
8658
8659 if (!isIntegerConstantExpr(Ctx, Loc))
8660 return false;
8661 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00008662 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00008663 return true;
8664}
Richard Smith66e05fe2012-01-18 05:21:49 +00008665
Craig Toppera31a8822013-08-22 07:09:37 +00008666bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00008667 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00008668}
8669
Craig Toppera31a8822013-08-22 07:09:37 +00008670bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +00008671 SourceLocation *Loc) const {
8672 // We support this checking in C++98 mode in order to diagnose compatibility
8673 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008674 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00008675
Richard Smith98a0a492012-02-14 21:38:30 +00008676 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00008677 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008678 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00008679 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +00008680 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +00008681
8682 APValue Scratch;
8683 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
8684
8685 if (!Diags.empty()) {
8686 IsConstExpr = false;
8687 if (Loc) *Loc = Diags[0].first;
8688 } else if (!IsConstExpr) {
8689 // FIXME: This shouldn't happen.
8690 if (Loc) *Loc = getExprLoc();
8691 }
8692
8693 return IsConstExpr;
8694}
Richard Smith253c2a32012-01-27 01:14:48 +00008695
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008696bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
8697 const FunctionDecl *Callee,
8698 llvm::ArrayRef<const Expr*> Args) const {
8699 Expr::EvalStatus Status;
8700 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
8701
8702 ArgVector ArgValues(Args.size());
8703 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
8704 I != E; ++I) {
8705 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
8706 // If evaluation fails, throw away the argument entirely.
8707 ArgValues[I - Args.begin()] = APValue();
8708 if (Info.EvalStatus.HasSideEffects)
8709 return false;
8710 }
8711
8712 // Build fake call to Callee.
8713 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/0,
8714 ArgValues.data());
8715 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
8716}
8717
Richard Smith253c2a32012-01-27 01:14:48 +00008718bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008719 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00008720 PartialDiagnosticAt> &Diags) {
8721 // FIXME: It would be useful to check constexpr function templates, but at the
8722 // moment the constant expression evaluator cannot cope with the non-rigorous
8723 // ASTs which we build for dependent expressions.
8724 if (FD->isDependentContext())
8725 return true;
8726
8727 Expr::EvalStatus Status;
8728 Status.Diag = &Diags;
8729
Richard Smith6d4c6582013-11-05 22:18:15 +00008730 EvalInfo Info(FD->getASTContext(), Status,
8731 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +00008732
8733 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8734 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
8735
Richard Smith7525ff62013-05-09 07:14:00 +00008736 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00008737 // is a temporary being used as the 'this' pointer.
8738 LValue This;
8739 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00008740 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00008741
Richard Smith253c2a32012-01-27 01:14:48 +00008742 ArrayRef<const Expr*> Args;
8743
8744 SourceLocation Loc = FD->getLocation();
8745
Richard Smith2e312c82012-03-03 22:46:17 +00008746 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00008747 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
8748 // Evaluate the call as a constant initializer, to allow the construction
8749 // of objects of non-literal types.
8750 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00008751 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00008752 } else
Richard Smith253c2a32012-01-27 01:14:48 +00008753 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
8754 Args, FD->getBody(), Info, Scratch);
8755
8756 return Diags.empty();
8757}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008758
8759bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
8760 const FunctionDecl *FD,
8761 SmallVectorImpl<
8762 PartialDiagnosticAt> &Diags) {
8763 Expr::EvalStatus Status;
8764 Status.Diag = &Diags;
8765
8766 EvalInfo Info(FD->getASTContext(), Status,
8767 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
8768
8769 // Fabricate a call stack frame to give the arguments a plausible cover story.
8770 ArrayRef<const Expr*> Args;
8771 ArgVector ArgValues(0);
8772 bool Success = EvaluateArgs(Args, ArgValues, Info);
8773 (void)Success;
8774 assert(Success &&
8775 "Failed to set up arguments for potential constant evaluation");
8776 CallStackFrame Frame(Info, SourceLocation(), FD, 0, ArgValues.data());
8777
8778 APValue ResultScratch;
8779 Evaluate(ResultScratch, Info, E);
8780 return Diags.empty();
8781}