blob: 9df53cd5bf0d3803b7d0b81a5887904a8f13fcb0 [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//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner60f36222009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump2346cd22009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlsson7a241ba2008-07-03 04:20:39 +000027using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000030
Chris Lattnercdf34e72008-07-11 22:52:41 +000031/// EvalInfo - This is a private struct used by the evaluator to capture
32/// information about a subexpression as it is folded. It retains information
33/// about the AST context, but also maintains information about the folded
34/// expression.
35///
36/// If an expression could be evaluated, it is still possible it is not a C
37/// "integer constant expression" or constant expression. If not, this struct
38/// captures information about how and why not.
39///
40/// One bit of information passed *into* the request for constant folding
41/// indicates whether the subexpression is "evaluated" or not according to C
42/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
43/// evaluate the expression regardless of what the RHS is, but C only allows
44/// certain things in certain situations.
John McCall93d91dc2010-05-07 17:22:02 +000045namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000046 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000047 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000048 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000049
Richard Smithce40ad62011-11-12 22:28:03 +000050 QualType getType(APValue::LValueBase B) {
51 if (!B) return QualType();
52 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
53 return D->getType();
54 return B.get<const Expr*>()->getType();
55 }
56
Richard Smithd62306a2011-11-10 06:34:14 +000057 /// Get an LValue path entry, which is known to not be an array index, as a
58 /// field declaration.
59 const FieldDecl *getAsField(APValue::LValuePathEntry E) {
60 APValue::BaseOrMemberType Value;
61 Value.setFromOpaqueValue(E.BaseOrMember);
62 return dyn_cast<FieldDecl>(Value.getPointer());
63 }
64 /// Get an LValue path entry, which is known to not be an array index, as a
65 /// base class declaration.
66 const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
67 APValue::BaseOrMemberType Value;
68 Value.setFromOpaqueValue(E.BaseOrMember);
69 return dyn_cast<CXXRecordDecl>(Value.getPointer());
70 }
71 /// Determine whether this LValue path entry for a base class names a virtual
72 /// base class.
73 bool isVirtualBaseClass(APValue::LValuePathEntry E) {
74 APValue::BaseOrMemberType Value;
75 Value.setFromOpaqueValue(E.BaseOrMember);
76 return Value.getInt();
77 }
78
Richard Smitha8105bc2012-01-06 16:39:00 +000079 /// Find the path length and type of the most-derived subobject in the given
80 /// path, and find the size of the containing array, if any.
81 static
82 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
83 ArrayRef<APValue::LValuePathEntry> Path,
84 uint64_t &ArraySize, QualType &Type) {
85 unsigned MostDerivedLength = 0;
86 Type = Base;
Richard Smith80815602011-11-07 05:07:52 +000087 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smitha8105bc2012-01-06 16:39:00 +000088 if (Type->isArrayType()) {
89 const ConstantArrayType *CAT =
90 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
91 Type = CAT->getElementType();
92 ArraySize = CAT->getSize().getZExtValue();
93 MostDerivedLength = I + 1;
94 } else if (const FieldDecl *FD = getAsField(Path[I])) {
95 Type = FD->getType();
96 ArraySize = 0;
97 MostDerivedLength = I + 1;
98 } else {
Richard Smith80815602011-11-07 05:07:52 +000099 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000100 ArraySize = 0;
101 }
Richard Smith80815602011-11-07 05:07:52 +0000102 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000103 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000104 }
105
Richard Smitha8105bc2012-01-06 16:39:00 +0000106 // The order of this enum is important for diagnostics.
107 enum CheckSubobjectKind {
108 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex
109 };
110
Richard Smith96e0c102011-11-04 02:25:55 +0000111 /// A path from a glvalue to a subobject of that glvalue.
112 struct SubobjectDesignator {
113 /// True if the subobject was named in a manner not supported by C++11. Such
114 /// lvalues can still be folded, but they are not core constant expressions
115 /// and we cannot perform lvalue-to-rvalue conversions on them.
116 bool Invalid : 1;
117
Richard Smitha8105bc2012-01-06 16:39:00 +0000118 /// Is this a pointer one past the end of an object?
119 bool IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000120
Richard Smitha8105bc2012-01-06 16:39:00 +0000121 /// The length of the path to the most-derived object of which this is a
122 /// subobject.
123 unsigned MostDerivedPathLength : 30;
124
125 /// The size of the array of which the most-derived object is an element, or
126 /// 0 if the most-derived object is not an array element.
127 uint64_t MostDerivedArraySize;
128
129 /// The type of the most derived object referred to by this address.
130 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000131
Richard Smith80815602011-11-07 05:07:52 +0000132 typedef APValue::LValuePathEntry PathEntry;
133
Richard Smith96e0c102011-11-04 02:25:55 +0000134 /// The entries on the path from the glvalue to the designated subobject.
135 SmallVector<PathEntry, 8> Entries;
136
Richard Smitha8105bc2012-01-06 16:39:00 +0000137 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000138
Richard Smitha8105bc2012-01-06 16:39:00 +0000139 explicit SubobjectDesignator(QualType T)
140 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
141 MostDerivedArraySize(0), MostDerivedType(T) {}
142
143 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
144 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
145 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith80815602011-11-07 05:07:52 +0000146 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000147 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000148 ArrayRef<PathEntry> VEntries = V.getLValuePath();
149 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
150 if (V.getLValueBase())
Richard Smitha8105bc2012-01-06 16:39:00 +0000151 MostDerivedPathLength =
152 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
153 V.getLValuePath(), MostDerivedArraySize,
154 MostDerivedType);
Richard Smith80815602011-11-07 05:07:52 +0000155 }
156 }
157
Richard Smith96e0c102011-11-04 02:25:55 +0000158 void setInvalid() {
159 Invalid = true;
160 Entries.clear();
161 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000162
163 /// Determine whether this is a one-past-the-end pointer.
164 bool isOnePastTheEnd() const {
165 if (IsOnePastTheEnd)
166 return true;
167 if (MostDerivedArraySize &&
168 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
169 return true;
170 return false;
171 }
172
173 /// Check that this refers to a valid subobject.
174 bool isValidSubobject() const {
175 if (Invalid)
176 return false;
177 return !isOnePastTheEnd();
178 }
179 /// Check that this refers to a valid subobject, and if not, produce a
180 /// relevant diagnostic and set the designator as invalid.
181 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
182
183 /// Update this designator to refer to the first element within this array.
184 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000185 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000186 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000187 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000188
189 // This is a most-derived object.
190 MostDerivedType = CAT->getElementType();
191 MostDerivedArraySize = CAT->getSize().getZExtValue();
192 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000193 }
194 /// Update this designator to refer to the given base or member of this
195 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000196 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000197 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000198 APValue::BaseOrMemberType Value(D, Virtual);
199 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000200 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000201
202 // If this isn't a base class, it's a new most-derived object.
203 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
204 MostDerivedType = FD->getType();
205 MostDerivedArraySize = 0;
206 MostDerivedPathLength = Entries.size();
207 }
Richard Smith96e0c102011-11-04 02:25:55 +0000208 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000209 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith96e0c102011-11-04 02:25:55 +0000210 /// Add N to the address of this subobject.
Richard Smitha8105bc2012-01-06 16:39:00 +0000211 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith96e0c102011-11-04 02:25:55 +0000212 if (Invalid) return;
Richard Smitha8105bc2012-01-06 16:39:00 +0000213 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith80815602011-11-07 05:07:52 +0000214 Entries.back().ArrayIndex += N;
Richard Smitha8105bc2012-01-06 16:39:00 +0000215 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
216 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
217 setInvalid();
218 }
Richard Smith96e0c102011-11-04 02:25:55 +0000219 return;
220 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000221 // [expr.add]p4: For the purposes of these operators, a pointer to a
222 // nonarray object behaves the same as a pointer to the first element of
223 // an array of length one with the type of the object as its element type.
224 if (IsOnePastTheEnd && N == (uint64_t)-1)
225 IsOnePastTheEnd = false;
226 else if (!IsOnePastTheEnd && N == 1)
227 IsOnePastTheEnd = true;
228 else if (N != 0) {
229 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith96e0c102011-11-04 02:25:55 +0000230 setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000231 }
Richard Smith96e0c102011-11-04 02:25:55 +0000232 }
233 };
234
Richard Smith0b0a0b62011-10-29 20:57:55 +0000235 /// A core constant value. This can be the value of any constant expression,
236 /// or a pointer or reference to a non-static object or function parameter.
Richard Smith027bf112011-11-17 22:56:20 +0000237 ///
238 /// For an LValue, the base and offset are stored in the APValue subobject,
239 /// but the other information is stored in the SubobjectDesignator. For all
240 /// other value kinds, the value is stored directly in the APValue subobject.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000241 class CCValue : public APValue {
242 typedef llvm::APSInt APSInt;
243 typedef llvm::APFloat APFloat;
Richard Smithfec09922011-11-01 16:57:24 +0000244 /// If the value is a reference or pointer into a parameter or temporary,
245 /// this is the corresponding call stack frame.
246 CallStackFrame *CallFrame;
Richard Smith96e0c102011-11-04 02:25:55 +0000247 /// If the value is a reference or pointer, this is a description of how the
248 /// subobject was specified.
249 SubobjectDesignator Designator;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000250 public:
Richard Smithfec09922011-11-01 16:57:24 +0000251 struct GlobalValue {};
252
Richard Smith0b0a0b62011-10-29 20:57:55 +0000253 CCValue() {}
254 explicit CCValue(const APSInt &I) : APValue(I) {}
255 explicit CCValue(const APFloat &F) : APValue(F) {}
256 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
257 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
258 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smithfec09922011-11-01 16:57:24 +0000259 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smithce40ad62011-11-12 22:28:03 +0000260 CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F,
Richard Smith96e0c102011-11-04 02:25:55 +0000261 const SubobjectDesignator &D) :
Richard Smith80815602011-11-07 05:07:52 +0000262 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000263 CCValue(ASTContext &Ctx, const APValue &V, GlobalValue) :
264 APValue(V), CallFrame(0), Designator(Ctx, V) {}
Richard Smith027bf112011-11-17 22:56:20 +0000265 CCValue(const ValueDecl *D, bool IsDerivedMember,
266 ArrayRef<const CXXRecordDecl*> Path) :
267 APValue(D, IsDerivedMember, Path) {}
Eli Friedmanfd5e54d2012-01-04 23:13:47 +0000268 CCValue(const AddrLabelExpr* LHSExpr, const AddrLabelExpr* RHSExpr) :
269 APValue(LHSExpr, RHSExpr) {}
Richard Smith0b0a0b62011-10-29 20:57:55 +0000270
Richard Smithfec09922011-11-01 16:57:24 +0000271 CallStackFrame *getLValueFrame() const {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000272 assert(getKind() == LValue);
Richard Smithfec09922011-11-01 16:57:24 +0000273 return CallFrame;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000274 }
Richard Smith96e0c102011-11-04 02:25:55 +0000275 SubobjectDesignator &getLValueDesignator() {
276 assert(getKind() == LValue);
277 return Designator;
278 }
279 const SubobjectDesignator &getLValueDesignator() const {
280 return const_cast<CCValue*>(this)->getLValueDesignator();
281 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000282 };
283
Richard Smith254a73d2011-10-28 22:34:42 +0000284 /// A stack frame in the constexpr call stack.
285 struct CallStackFrame {
286 EvalInfo &Info;
287
288 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000289 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000290
Richard Smithf6f003a2011-12-16 19:06:07 +0000291 /// CallLoc - The location of the call expression for this call.
292 SourceLocation CallLoc;
293
294 /// Callee - The function which was called.
295 const FunctionDecl *Callee;
296
Richard Smithd62306a2011-11-10 06:34:14 +0000297 /// This - The binding for the this pointer in this call, if any.
298 const LValue *This;
299
Richard Smith254a73d2011-10-28 22:34:42 +0000300 /// ParmBindings - Parameter bindings for this function call, indexed by
301 /// parameters' function scope indices.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000302 const CCValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000303
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000304 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
305 typedef MapTy::const_iterator temp_iterator;
306 /// Temporaries - Temporary lvalues materialized within this stack frame.
307 MapTy Temporaries;
308
Richard Smithf6f003a2011-12-16 19:06:07 +0000309 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
310 const FunctionDecl *Callee, const LValue *This,
Richard Smithd62306a2011-11-10 06:34:14 +0000311 const CCValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000312 ~CallStackFrame();
Richard Smith254a73d2011-10-28 22:34:42 +0000313 };
314
Richard Smith92b1ce02011-12-12 09:28:41 +0000315 /// A partial diagnostic which we might know in advance that we are not going
316 /// to emit.
317 class OptionalDiagnostic {
318 PartialDiagnostic *Diag;
319
320 public:
321 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
322
323 template<typename T>
324 OptionalDiagnostic &operator<<(const T &v) {
325 if (Diag)
326 *Diag << v;
327 return *this;
328 }
329 };
330
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000331 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000332 ASTContext &Ctx;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000333
334 /// EvalStatus - Contains information about the evaluation.
335 Expr::EvalStatus &EvalStatus;
336
337 /// CurrentCall - The top of the constexpr call stack.
338 CallStackFrame *CurrentCall;
339
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000340 /// CallStackDepth - The number of calls in the call stack right now.
341 unsigned CallStackDepth;
342
343 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
344 /// OpaqueValues - Values used as the common expression in a
345 /// BinaryConditionalOperator.
346 MapTy OpaqueValues;
347
348 /// BottomFrame - The frame in which evaluation started. This must be
349 /// initialized last.
350 CallStackFrame BottomFrame;
351
Richard Smithd62306a2011-11-10 06:34:14 +0000352 /// EvaluatingDecl - This is the declaration whose initializer is being
353 /// evaluated, if any.
354 const VarDecl *EvaluatingDecl;
355
356 /// EvaluatingDeclValue - This is the value being constructed for the
357 /// declaration whose initializer is being evaluated, if any.
358 APValue *EvaluatingDeclValue;
359
Richard Smith357362d2011-12-13 06:39:58 +0000360 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
361 /// notes attached to it will also be stored, otherwise they will not be.
362 bool HasActiveDiagnostic;
363
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000364
365 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smith92b1ce02011-12-12 09:28:41 +0000366 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smithf6f003a2011-12-16 19:06:07 +0000367 CallStackDepth(0), BottomFrame(*this, SourceLocation(), 0, 0, 0),
368 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000369
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000370 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
371 MapTy::const_iterator i = OpaqueValues.find(e);
372 if (i == OpaqueValues.end()) return 0;
373 return &i->second;
374 }
375
Richard Smithd62306a2011-11-10 06:34:14 +0000376 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
377 EvaluatingDecl = VD;
378 EvaluatingDeclValue = &Value;
379 }
380
Richard Smith9a568822011-11-21 19:36:32 +0000381 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
382
Richard Smith357362d2011-12-13 06:39:58 +0000383 bool CheckCallLimit(SourceLocation Loc) {
384 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
385 return true;
386 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
387 << getLangOpts().ConstexprCallDepth;
388 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000389 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000390
Richard Smith357362d2011-12-13 06:39:58 +0000391 private:
392 /// Add a diagnostic to the diagnostics list.
393 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
394 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
395 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
396 return EvalStatus.Diag->back().second;
397 }
398
Richard Smithf6f003a2011-12-16 19:06:07 +0000399 /// Add notes containing a call stack to the current point of evaluation.
400 void addCallStack(unsigned Limit);
401
Richard Smith357362d2011-12-13 06:39:58 +0000402 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000403 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000404 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
405 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000406 unsigned ExtraNotes = 0) {
Richard Smithf57d8cb2011-12-09 22:58:01 +0000407 // If we have a prior diagnostic, it will be noting that the expression
408 // isn't a constant expression. This diagnostic is more important.
409 // FIXME: We might want to show both diagnostics to the user.
Richard Smith92b1ce02011-12-12 09:28:41 +0000410 if (EvalStatus.Diag) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000411 unsigned CallStackNotes = CallStackDepth - 1;
412 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
413 if (Limit)
414 CallStackNotes = std::min(CallStackNotes, Limit + 1);
415
Richard Smith357362d2011-12-13 06:39:58 +0000416 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000417 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000418 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
419 addDiag(Loc, DiagId);
420 addCallStack(Limit);
421 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000422 }
Richard Smith357362d2011-12-13 06:39:58 +0000423 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000424 return OptionalDiagnostic();
425 }
426
427 /// Diagnose that the evaluation does not produce a C++11 core constant
428 /// expression.
Richard Smithf2b681b2011-12-21 05:04:46 +0000429 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
430 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000431 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000432 // Don't override a previous diagnostic.
433 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
434 return OptionalDiagnostic();
Richard Smith357362d2011-12-13 06:39:58 +0000435 return Diag(Loc, DiagId, ExtraNotes);
436 }
437
438 /// Add a note to a prior diagnostic.
439 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
440 if (!HasActiveDiagnostic)
441 return OptionalDiagnostic();
442 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000443 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000444
445 /// Add a stack of notes to a prior diagnostic.
446 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
447 if (HasActiveDiagnostic) {
448 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
449 Diags.begin(), Diags.end());
450 }
451 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000452 };
Richard Smithf6f003a2011-12-16 19:06:07 +0000453}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000454
Richard Smitha8105bc2012-01-06 16:39:00 +0000455bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
456 CheckSubobjectKind CSK) {
457 if (Invalid)
458 return false;
459 if (isOnePastTheEnd()) {
460 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_past_end_subobject)
461 << CSK;
462 setInvalid();
463 return false;
464 }
465 return true;
466}
467
468void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
469 const Expr *E, uint64_t N) {
470 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
471 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
472 << static_cast<int>(N) << /*array*/ 0
473 << static_cast<unsigned>(MostDerivedArraySize);
474 else
475 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
476 << static_cast<int>(N) << /*non-array*/ 1;
477 setInvalid();
478}
479
Richard Smithf6f003a2011-12-16 19:06:07 +0000480CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
481 const FunctionDecl *Callee, const LValue *This,
482 const CCValue *Arguments)
483 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
484 This(This), Arguments(Arguments) {
485 Info.CurrentCall = this;
486 ++Info.CallStackDepth;
487}
488
489CallStackFrame::~CallStackFrame() {
490 assert(Info.CurrentCall == this && "calls retired out of order");
491 --Info.CallStackDepth;
492 Info.CurrentCall = Caller;
493}
494
495/// Produce a string describing the given constexpr call.
496static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
497 unsigned ArgIndex = 0;
498 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
499 !isa<CXXConstructorDecl>(Frame->Callee);
500
501 if (!IsMemberCall)
502 Out << *Frame->Callee << '(';
503
504 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
505 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
506 if (ArgIndex > IsMemberCall)
507 Out << ", ";
508
509 const ParmVarDecl *Param = *I;
510 const CCValue &Arg = Frame->Arguments[ArgIndex];
511 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
512 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
513 else {
514 // Deliberately slice off the frame to form an APValue we can print.
515 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
516 Arg.getLValueDesignator().Entries,
Richard Smitha8105bc2012-01-06 16:39:00 +0000517 Arg.getLValueDesignator().IsOnePastTheEnd);
Richard Smithf6f003a2011-12-16 19:06:07 +0000518 Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
519 }
520
521 if (ArgIndex == 0 && IsMemberCall)
522 Out << "->" << *Frame->Callee << '(';
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000523 }
524
Richard Smithf6f003a2011-12-16 19:06:07 +0000525 Out << ')';
526}
527
528void EvalInfo::addCallStack(unsigned Limit) {
529 // Determine which calls to skip, if any.
530 unsigned ActiveCalls = CallStackDepth - 1;
531 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
532 if (Limit && Limit < ActiveCalls) {
533 SkipStart = Limit / 2 + Limit % 2;
534 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000535 }
536
Richard Smithf6f003a2011-12-16 19:06:07 +0000537 // Walk the call stack and add the diagnostics.
538 unsigned CallIdx = 0;
539 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
540 Frame = Frame->Caller, ++CallIdx) {
541 // Skip this call?
542 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
543 if (CallIdx == SkipStart) {
544 // Note that we're skipping calls.
545 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
546 << unsigned(ActiveCalls - Limit);
547 }
548 continue;
549 }
550
551 llvm::SmallVector<char, 128> Buffer;
552 llvm::raw_svector_ostream Out(Buffer);
553 describeCall(Frame, Out);
554 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
555 }
556}
557
558namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000559 struct ComplexValue {
560 private:
561 bool IsInt;
562
563 public:
564 APSInt IntReal, IntImag;
565 APFloat FloatReal, FloatImag;
566
567 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
568
569 void makeComplexFloat() { IsInt = false; }
570 bool isComplexFloat() const { return !IsInt; }
571 APFloat &getComplexFloatReal() { return FloatReal; }
572 APFloat &getComplexFloatImag() { return FloatImag; }
573
574 void makeComplexInt() { IsInt = true; }
575 bool isComplexInt() const { return IsInt; }
576 APSInt &getComplexIntReal() { return IntReal; }
577 APSInt &getComplexIntImag() { return IntImag; }
578
Richard Smith0b0a0b62011-10-29 20:57:55 +0000579 void moveInto(CCValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000580 if (isComplexFloat())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000581 v = CCValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000582 else
Richard Smith0b0a0b62011-10-29 20:57:55 +0000583 v = CCValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000584 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000585 void setFrom(const CCValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000586 assert(v.isComplexFloat() || v.isComplexInt());
587 if (v.isComplexFloat()) {
588 makeComplexFloat();
589 FloatReal = v.getComplexFloatReal();
590 FloatImag = v.getComplexFloatImag();
591 } else {
592 makeComplexInt();
593 IntReal = v.getComplexIntReal();
594 IntImag = v.getComplexIntImag();
595 }
596 }
John McCall93d91dc2010-05-07 17:22:02 +0000597 };
John McCall45d55e42010-05-07 21:00:08 +0000598
599 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000600 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000601 CharUnits Offset;
Richard Smithfec09922011-11-01 16:57:24 +0000602 CallStackFrame *Frame;
Richard Smith96e0c102011-11-04 02:25:55 +0000603 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000604
Richard Smithce40ad62011-11-12 22:28:03 +0000605 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000606 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000607 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithfec09922011-11-01 16:57:24 +0000608 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith96e0c102011-11-04 02:25:55 +0000609 SubobjectDesignator &getLValueDesignator() { return Designator; }
610 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000611
Richard Smith0b0a0b62011-10-29 20:57:55 +0000612 void moveInto(CCValue &V) const {
Richard Smith96e0c102011-11-04 02:25:55 +0000613 V = CCValue(Base, Offset, Frame, Designator);
John McCall45d55e42010-05-07 21:00:08 +0000614 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000615 void setFrom(const CCValue &V) {
616 assert(V.isLValue());
617 Base = V.getLValueBase();
618 Offset = V.getLValueOffset();
Richard Smithfec09922011-11-01 16:57:24 +0000619 Frame = V.getLValueFrame();
Richard Smith96e0c102011-11-04 02:25:55 +0000620 Designator = V.getLValueDesignator();
621 }
622
Richard Smithce40ad62011-11-12 22:28:03 +0000623 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
624 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000625 Offset = CharUnits::Zero();
626 Frame = F;
Richard Smitha8105bc2012-01-06 16:39:00 +0000627 Designator = SubobjectDesignator(getType(B));
628 }
629
630 // Check that this LValue is not based on a null pointer. If it is, produce
631 // a diagnostic and mark the designator as invalid.
632 bool checkNullPointer(EvalInfo &Info, const Expr *E,
633 CheckSubobjectKind CSK) {
634 if (Designator.Invalid)
635 return false;
636 if (!Base) {
637 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_null_subobject)
638 << CSK;
639 Designator.setInvalid();
640 return false;
641 }
642 return true;
643 }
644
645 // Check this LValue refers to an object. If not, set the designator to be
646 // invalid and emit a diagnostic.
647 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
648 return checkNullPointer(Info, E, CSK) &&
649 Designator.checkSubobject(Info, E, CSK);
650 }
651
652 void addDecl(EvalInfo &Info, const Expr *E,
653 const Decl *D, bool Virtual = false) {
654 checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base);
655 Designator.addDeclUnchecked(D, Virtual);
656 }
657 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
658 checkSubobject(Info, E, CSK_ArrayToPointer);
659 Designator.addArrayUnchecked(CAT);
660 }
661 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
662 if (!checkNullPointer(Info, E, CSK_ArrayIndex))
663 return;
664 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +0000665 }
John McCall45d55e42010-05-07 21:00:08 +0000666 };
Richard Smith027bf112011-11-17 22:56:20 +0000667
668 struct MemberPtr {
669 MemberPtr() {}
670 explicit MemberPtr(const ValueDecl *Decl) :
671 DeclAndIsDerivedMember(Decl, false), Path() {}
672
673 /// The member or (direct or indirect) field referred to by this member
674 /// pointer, or 0 if this is a null member pointer.
675 const ValueDecl *getDecl() const {
676 return DeclAndIsDerivedMember.getPointer();
677 }
678 /// Is this actually a member of some type derived from the relevant class?
679 bool isDerivedMember() const {
680 return DeclAndIsDerivedMember.getInt();
681 }
682 /// Get the class which the declaration actually lives in.
683 const CXXRecordDecl *getContainingRecord() const {
684 return cast<CXXRecordDecl>(
685 DeclAndIsDerivedMember.getPointer()->getDeclContext());
686 }
687
688 void moveInto(CCValue &V) const {
689 V = CCValue(getDecl(), isDerivedMember(), Path);
690 }
691 void setFrom(const CCValue &V) {
692 assert(V.isMemberPointer());
693 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
694 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
695 Path.clear();
696 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
697 Path.insert(Path.end(), P.begin(), P.end());
698 }
699
700 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
701 /// whether the member is a member of some class derived from the class type
702 /// of the member pointer.
703 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
704 /// Path - The path of base/derived classes from the member declaration's
705 /// class (exclusive) to the class type of the member pointer (inclusive).
706 SmallVector<const CXXRecordDecl*, 4> Path;
707
708 /// Perform a cast towards the class of the Decl (either up or down the
709 /// hierarchy).
710 bool castBack(const CXXRecordDecl *Class) {
711 assert(!Path.empty());
712 const CXXRecordDecl *Expected;
713 if (Path.size() >= 2)
714 Expected = Path[Path.size() - 2];
715 else
716 Expected = getContainingRecord();
717 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
718 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
719 // if B does not contain the original member and is not a base or
720 // derived class of the class containing the original member, the result
721 // of the cast is undefined.
722 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
723 // (D::*). We consider that to be a language defect.
724 return false;
725 }
726 Path.pop_back();
727 return true;
728 }
729 /// Perform a base-to-derived member pointer cast.
730 bool castToDerived(const CXXRecordDecl *Derived) {
731 if (!getDecl())
732 return true;
733 if (!isDerivedMember()) {
734 Path.push_back(Derived);
735 return true;
736 }
737 if (!castBack(Derived))
738 return false;
739 if (Path.empty())
740 DeclAndIsDerivedMember.setInt(false);
741 return true;
742 }
743 /// Perform a derived-to-base member pointer cast.
744 bool castToBase(const CXXRecordDecl *Base) {
745 if (!getDecl())
746 return true;
747 if (Path.empty())
748 DeclAndIsDerivedMember.setInt(true);
749 if (isDerivedMember()) {
750 Path.push_back(Base);
751 return true;
752 }
753 return castBack(Base);
754 }
755 };
Richard Smith357362d2011-12-13 06:39:58 +0000756
757 /// Kinds of constant expression checking, for diagnostics.
758 enum CheckConstantExpressionKind {
759 CCEK_Constant, ///< A normal constant.
760 CCEK_ReturnValue, ///< A constexpr function return value.
761 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
762 };
John McCall93d91dc2010-05-07 17:22:02 +0000763}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000764
Richard Smith0b0a0b62011-10-29 20:57:55 +0000765static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithed5165f2011-11-04 05:33:44 +0000766static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smith357362d2011-12-13 06:39:58 +0000767 const LValue &This, const Expr *E,
768 CheckConstantExpressionKind CCEK
769 = CCEK_Constant);
John McCall45d55e42010-05-07 21:00:08 +0000770static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
771static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +0000772static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
773 EvalInfo &Info);
774static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000775static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000776static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000777 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000778static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000779static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000780
781//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000782// Misc utilities
783//===----------------------------------------------------------------------===//
784
Richard Smithd62306a2011-11-10 06:34:14 +0000785/// Should this call expression be treated as a string literal?
786static bool IsStringLiteralCall(const CallExpr *E) {
787 unsigned Builtin = E->isBuiltinCall();
788 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
789 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
790}
791
Richard Smithce40ad62011-11-12 22:28:03 +0000792static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +0000793 // C++11 [expr.const]p3 An address constant expression is a prvalue core
794 // constant expression of pointer type that evaluates to...
795
796 // ... a null pointer value, or a prvalue core constant expression of type
797 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +0000798 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +0000799
Richard Smithce40ad62011-11-12 22:28:03 +0000800 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
801 // ... the address of an object with static storage duration,
802 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
803 return VD->hasGlobalStorage();
804 // ... the address of a function,
805 return isa<FunctionDecl>(D);
806 }
807
808 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +0000809 switch (E->getStmtClass()) {
810 default:
811 return false;
Richard Smithd62306a2011-11-10 06:34:14 +0000812 case Expr::CompoundLiteralExprClass:
813 return cast<CompoundLiteralExpr>(E)->isFileScope();
814 // A string literal has static storage duration.
815 case Expr::StringLiteralClass:
816 case Expr::PredefinedExprClass:
817 case Expr::ObjCStringLiteralClass:
818 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +0000819 case Expr::CXXTypeidExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +0000820 return true;
821 case Expr::CallExprClass:
822 return IsStringLiteralCall(cast<CallExpr>(E));
823 // For GCC compatibility, &&label has static storage duration.
824 case Expr::AddrLabelExprClass:
825 return true;
826 // A Block literal expression may be used as the initialization value for
827 // Block variables at global or local static scope.
828 case Expr::BlockExprClass:
829 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
830 }
John McCall95007602010-05-10 23:27:23 +0000831}
832
Richard Smith80815602011-11-07 05:07:52 +0000833/// Check that this reference or pointer core constant expression is a valid
Richard Smitha8105bc2012-01-06 16:39:00 +0000834/// value for an address or reference constant expression. Type T should be
Richard Smith02ab9c22012-01-12 06:08:57 +0000835/// either LValue or CCValue. Return true if we can fold this expression,
836/// whether or not it's a constant expression.
Richard Smith80815602011-11-07 05:07:52 +0000837template<typename T>
Richard Smithf57d8cb2011-12-09 22:58:01 +0000838static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +0000839 const T &LVal, APValue &Value,
840 CheckConstantExpressionKind CCEK) {
841 APValue::LValueBase Base = LVal.getLValueBase();
842 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
843
844 if (!IsGlobalLValue(Base)) {
845 if (Info.getLangOpts().CPlusPlus0x) {
846 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
847 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
848 << E->isGLValue() << !Designator.Entries.empty()
849 << !!VD << CCEK << VD;
850 if (VD)
851 Info.Note(VD->getLocation(), diag::note_declared_at);
852 else
853 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
854 diag::note_constexpr_temporary_here);
855 } else {
Richard Smithf2b681b2011-12-21 05:04:46 +0000856 Info.Diag(E->getExprLoc());
Richard Smith357362d2011-12-13 06:39:58 +0000857 }
Richard Smith02ab9c22012-01-12 06:08:57 +0000858 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +0000859 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000860 }
Richard Smith80815602011-11-07 05:07:52 +0000861
Richard Smitha8105bc2012-01-06 16:39:00 +0000862 bool IsReferenceType = E->isGLValue();
863
864 if (Designator.Invalid) {
Richard Smith02ab9c22012-01-12 06:08:57 +0000865 // This is not a core constant expression. An appropriate diagnostic will
866 // have already been produced.
Richard Smith80815602011-11-07 05:07:52 +0000867 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
868 APValue::NoLValuePath());
869 return true;
870 }
871
Richard Smitha8105bc2012-01-06 16:39:00 +0000872 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
873 Designator.Entries, Designator.IsOnePastTheEnd);
874
875 // Allow address constant expressions to be past-the-end pointers. This is
876 // an extension: the standard requires them to point to an object.
877 if (!IsReferenceType)
878 return true;
879
880 // A reference constant expression must refer to an object.
881 if (!Base) {
882 // FIXME: diagnostic
883 Info.CCEDiag(E->getExprLoc());
Richard Smith02ab9c22012-01-12 06:08:57 +0000884 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000885 }
886
Richard Smith357362d2011-12-13 06:39:58 +0000887 // Does this refer one past the end of some object?
Richard Smitha8105bc2012-01-06 16:39:00 +0000888 if (Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +0000889 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
890 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
891 << !Designator.Entries.empty() << !!VD << VD;
892 if (VD)
893 Info.Note(VD->getLocation(), diag::note_declared_at);
894 else
895 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
896 diag::note_constexpr_temporary_here);
Richard Smith357362d2011-12-13 06:39:58 +0000897 }
898
Richard Smith80815602011-11-07 05:07:52 +0000899 return true;
900}
901
Richard Smithfddd3842011-12-30 21:15:51 +0000902/// Check that this core constant expression is of literal type, and if not,
903/// produce an appropriate diagnostic.
904static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
905 if (!E->isRValue() || E->getType()->isLiteralType())
906 return true;
907
908 // Prvalue constant expressions must be of literal types.
909 if (Info.getLangOpts().CPlusPlus0x)
910 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
911 << E->getType();
912 else
913 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
914 return false;
915}
916
Richard Smith0b0a0b62011-10-29 20:57:55 +0000917/// Check that this core constant expression value is a valid value for a
Richard Smithed5165f2011-11-04 05:33:44 +0000918/// constant expression, and if it is, produce the corresponding constant value.
Richard Smithfddd3842011-12-30 21:15:51 +0000919/// If not, report an appropriate diagnostic. Does not check that the expression
920/// is of literal type.
Richard Smithf57d8cb2011-12-09 22:58:01 +0000921static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +0000922 const CCValue &CCValue, APValue &Value,
923 CheckConstantExpressionKind CCEK
924 = CCEK_Constant) {
Richard Smith80815602011-11-07 05:07:52 +0000925 if (!CCValue.isLValue()) {
926 Value = CCValue;
927 return true;
928 }
Richard Smith357362d2011-12-13 06:39:58 +0000929 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000930}
931
Richard Smith83c68212011-10-31 05:11:32 +0000932const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +0000933 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +0000934}
935
936static bool IsLiteralLValue(const LValue &Value) {
Richard Smithce40ad62011-11-12 22:28:03 +0000937 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith83c68212011-10-31 05:11:32 +0000938}
939
Richard Smithcecf1842011-11-01 21:06:14 +0000940static bool IsWeakLValue(const LValue &Value) {
941 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +0000942 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +0000943}
944
Richard Smith027bf112011-11-17 22:56:20 +0000945static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +0000946 // A null base expression indicates a null pointer. These are always
947 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +0000948 if (!Value.getLValueBase()) {
949 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +0000950 return true;
951 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000952
John McCall95007602010-05-10 23:27:23 +0000953 // Require the base expression to be a global l-value.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000954 // FIXME: C++11 requires such conversions. Remove this check.
Richard Smith027bf112011-11-17 22:56:20 +0000955 if (!IsGlobalLValue(Value.getLValueBase())) return false;
John McCall95007602010-05-10 23:27:23 +0000956
Richard Smith027bf112011-11-17 22:56:20 +0000957 // We have a non-null base. These are generally known to be true, but if it's
958 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000959 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +0000960 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +0000961 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +0000962}
963
Richard Smith0b0a0b62011-10-29 20:57:55 +0000964static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +0000965 switch (Val.getKind()) {
966 case APValue::Uninitialized:
967 return false;
968 case APValue::Int:
969 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000970 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000971 case APValue::Float:
972 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000973 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000974 case APValue::ComplexInt:
975 Result = Val.getComplexIntReal().getBoolValue() ||
976 Val.getComplexIntImag().getBoolValue();
977 return true;
978 case APValue::ComplexFloat:
979 Result = !Val.getComplexFloatReal().isZero() ||
980 !Val.getComplexFloatImag().isZero();
981 return true;
Richard Smith027bf112011-11-17 22:56:20 +0000982 case APValue::LValue:
983 return EvalPointerValueAsBool(Val, Result);
984 case APValue::MemberPointer:
985 Result = Val.getMemberPointerDecl();
986 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000987 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +0000988 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +0000989 case APValue::Struct:
990 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +0000991 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +0000992 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000993 }
994
Richard Smith11562c52011-10-28 17:51:58 +0000995 llvm_unreachable("unknown APValue kind");
996}
997
998static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
999 EvalInfo &Info) {
1000 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001001 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +00001002 if (!Evaluate(Val, Info, E))
1003 return false;
1004 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001005}
1006
Richard Smith357362d2011-12-13 06:39:58 +00001007template<typename T>
1008static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1009 const T &SrcValue, QualType DestType) {
1010 llvm::SmallVector<char, 32> Buffer;
1011 SrcValue.toString(Buffer);
1012 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
1013 << StringRef(Buffer.data(), Buffer.size()) << DestType;
1014 return false;
1015}
1016
1017static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1018 QualType SrcType, const APFloat &Value,
1019 QualType DestType, APSInt &Result) {
1020 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001021 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001022 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001023
Richard Smith357362d2011-12-13 06:39:58 +00001024 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001025 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001026 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1027 & APFloat::opInvalidOp)
1028 return HandleOverflow(Info, E, Value, DestType);
1029 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001030}
1031
Richard Smith357362d2011-12-13 06:39:58 +00001032static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1033 QualType SrcType, QualType DestType,
1034 APFloat &Result) {
1035 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001036 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001037 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1038 APFloat::rmNearestTiesToEven, &ignored)
1039 & APFloat::opOverflow)
1040 return HandleOverflow(Info, E, Value, DestType);
1041 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001042}
1043
Mike Stump11289f42009-09-09 15:08:12 +00001044static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +00001045 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001046 unsigned DestWidth = Ctx.getIntWidth(DestType);
1047 APSInt Result = Value;
1048 // Figure out if this is a truncate, extend or noop cast.
1049 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001050 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001051 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001052 return Result;
1053}
1054
Richard Smith357362d2011-12-13 06:39:58 +00001055static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1056 QualType SrcType, const APSInt &Value,
1057 QualType DestType, APFloat &Result) {
1058 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1059 if (Result.convertFromAPInt(Value, Value.isSigned(),
1060 APFloat::rmNearestTiesToEven)
1061 & APFloat::opOverflow)
1062 return HandleOverflow(Info, E, Value, DestType);
1063 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001064}
1065
Eli Friedman803acb32011-12-22 03:51:45 +00001066static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1067 llvm::APInt &Res) {
1068 CCValue SVal;
1069 if (!Evaluate(SVal, Info, E))
1070 return false;
1071 if (SVal.isInt()) {
1072 Res = SVal.getInt();
1073 return true;
1074 }
1075 if (SVal.isFloat()) {
1076 Res = SVal.getFloat().bitcastToAPInt();
1077 return true;
1078 }
1079 if (SVal.isVector()) {
1080 QualType VecTy = E->getType();
1081 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1082 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1083 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1084 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1085 Res = llvm::APInt::getNullValue(VecSize);
1086 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1087 APValue &Elt = SVal.getVectorElt(i);
1088 llvm::APInt EltAsInt;
1089 if (Elt.isInt()) {
1090 EltAsInt = Elt.getInt();
1091 } else if (Elt.isFloat()) {
1092 EltAsInt = Elt.getFloat().bitcastToAPInt();
1093 } else {
1094 // Don't try to handle vectors of anything other than int or float
1095 // (not sure if it's possible to hit this case).
1096 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1097 return false;
1098 }
1099 unsigned BaseEltSize = EltAsInt.getBitWidth();
1100 if (BigEndian)
1101 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1102 else
1103 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1104 }
1105 return true;
1106 }
1107 // Give up if the input isn't an int, float, or vector. For example, we
1108 // reject "(v4i16)(intptr_t)&a".
1109 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1110 return false;
1111}
1112
Richard Smitha8105bc2012-01-06 16:39:00 +00001113/// Cast an lvalue referring to a base subobject to a derived class, by
1114/// truncating the lvalue's path to the given length.
1115static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1116 const RecordDecl *TruncatedType,
1117 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001118 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001119
1120 // Check we actually point to a derived class object.
1121 if (TruncatedElements == D.Entries.size())
1122 return true;
1123 assert(TruncatedElements >= D.MostDerivedPathLength &&
1124 "not casting to a derived class");
1125 if (!Result.checkSubobject(Info, E, CSK_Derived))
1126 return false;
1127
1128 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001129 const RecordDecl *RD = TruncatedType;
1130 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smithd62306a2011-11-10 06:34:14 +00001131 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1132 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001133 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001134 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001135 else
Richard Smithd62306a2011-11-10 06:34:14 +00001136 Result.Offset -= Layout.getBaseClassOffset(Base);
1137 RD = Base;
1138 }
Richard Smith027bf112011-11-17 22:56:20 +00001139 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001140 return true;
1141}
1142
Richard Smitha8105bc2012-01-06 16:39:00 +00001143static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001144 const CXXRecordDecl *Derived,
1145 const CXXRecordDecl *Base,
1146 const ASTRecordLayout *RL = 0) {
1147 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1148 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001149 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
Richard Smithd62306a2011-11-10 06:34:14 +00001150}
1151
Richard Smitha8105bc2012-01-06 16:39:00 +00001152static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001153 const CXXRecordDecl *DerivedDecl,
1154 const CXXBaseSpecifier *Base) {
1155 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1156
1157 if (!Base->isVirtual()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001158 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001159 return true;
1160 }
1161
Richard Smitha8105bc2012-01-06 16:39:00 +00001162 SubobjectDesignator &D = Obj.Designator;
1163 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001164 return false;
1165
Richard Smitha8105bc2012-01-06 16:39:00 +00001166 // Extract most-derived object and corresponding type.
1167 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1168 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1169 return false;
1170
1171 // Find the virtual base class.
Richard Smithd62306a2011-11-10 06:34:14 +00001172 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1173 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001174 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001175 return true;
1176}
1177
1178/// Update LVal to refer to the given field, which must be a member of the type
1179/// currently described by LVal.
Richard Smitha8105bc2012-01-06 16:39:00 +00001180static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001181 const FieldDecl *FD,
1182 const ASTRecordLayout *RL = 0) {
1183 if (!RL)
1184 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1185
1186 unsigned I = FD->getFieldIndex();
1187 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001188 LVal.addDecl(Info, E, FD);
Richard Smithd62306a2011-11-10 06:34:14 +00001189}
1190
1191/// Get the size of the given type in char units.
1192static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1193 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1194 // extension.
1195 if (Type->isVoidType() || Type->isFunctionType()) {
1196 Size = CharUnits::One();
1197 return true;
1198 }
1199
1200 if (!Type->isConstantSizeType()) {
1201 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smitha8105bc2012-01-06 16:39:00 +00001202 // FIXME: Diagnostic.
Richard Smithd62306a2011-11-10 06:34:14 +00001203 return false;
1204 }
1205
1206 Size = Info.Ctx.getTypeSizeInChars(Type);
1207 return true;
1208}
1209
1210/// Update a pointer value to model pointer arithmetic.
1211/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001212/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001213/// \param LVal - The pointer value to be updated.
1214/// \param EltTy - The pointee type represented by LVal.
1215/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001216static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1217 LValue &LVal, QualType EltTy,
1218 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001219 CharUnits SizeOfPointee;
1220 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1221 return false;
1222
1223 // Compute the new offset in the appropriate width.
1224 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001225 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001226 return true;
1227}
1228
Richard Smith27908702011-10-24 17:54:18 +00001229/// Try to evaluate the initializer for a variable declaration.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001230static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1231 const VarDecl *VD,
Richard Smithfec09922011-11-01 16:57:24 +00001232 CallStackFrame *Frame, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001233 // If this is a parameter to an active constexpr function call, perform
1234 // argument substitution.
1235 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001236 if (!Frame || !Frame->Arguments) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001237 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001238 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001239 }
Richard Smithfec09922011-11-01 16:57:24 +00001240 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1241 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001242 }
Richard Smith27908702011-10-24 17:54:18 +00001243
Richard Smithd0b4dd62011-12-19 06:19:21 +00001244 // Dig out the initializer, and use the declaration which it's attached to.
1245 const Expr *Init = VD->getAnyInitializer(VD);
1246 if (!Init || Init->isValueDependent()) {
1247 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1248 return false;
1249 }
1250
Richard Smithd62306a2011-11-10 06:34:14 +00001251 // If we're currently evaluating the initializer of this declaration, use that
1252 // in-flight value.
1253 if (Info.EvaluatingDecl == VD) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001254 Result = CCValue(Info.Ctx, *Info.EvaluatingDeclValue,
1255 CCValue::GlobalValue());
Richard Smithd62306a2011-11-10 06:34:14 +00001256 return !Result.isUninit();
1257 }
1258
Richard Smithcecf1842011-11-01 21:06:14 +00001259 // Never evaluate the initializer of a weak variable. We can't be sure that
1260 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001261 if (VD->isWeak()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001262 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001263 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001264 }
Richard Smithcecf1842011-11-01 21:06:14 +00001265
Richard Smithd0b4dd62011-12-19 06:19:21 +00001266 // Check that we can fold the initializer. In C++, we will have already done
1267 // this in the cases where it matters for conformance.
1268 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1269 if (!VD->evaluateValue(Notes)) {
1270 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1271 Notes.size() + 1) << VD;
1272 Info.Note(VD->getLocation(), diag::note_declared_at);
1273 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001274 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001275 } else if (!VD->checkInitIsICE()) {
1276 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1277 Notes.size() + 1) << VD;
1278 Info.Note(VD->getLocation(), diag::note_declared_at);
1279 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001280 }
Richard Smith27908702011-10-24 17:54:18 +00001281
Richard Smitha8105bc2012-01-06 16:39:00 +00001282 Result = CCValue(Info.Ctx, *VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +00001283 return true;
Richard Smith27908702011-10-24 17:54:18 +00001284}
1285
Richard Smith11562c52011-10-28 17:51:58 +00001286static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001287 Qualifiers Quals = T.getQualifiers();
1288 return Quals.hasConst() && !Quals.hasVolatile();
1289}
1290
Richard Smithe97cbd72011-11-11 04:05:33 +00001291/// Get the base index of the given base class within an APValue representing
1292/// the given derived class.
1293static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1294 const CXXRecordDecl *Base) {
1295 Base = Base->getCanonicalDecl();
1296 unsigned Index = 0;
1297 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1298 E = Derived->bases_end(); I != E; ++I, ++Index) {
1299 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1300 return Index;
1301 }
1302
1303 llvm_unreachable("base class missing from derived class's bases list");
1304}
1305
Richard Smithf3e9e432011-11-07 09:22:26 +00001306/// Extract the designated sub-object of an rvalue.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001307static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1308 CCValue &Obj, QualType ObjType,
Richard Smithf3e9e432011-11-07 09:22:26 +00001309 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001310 if (Sub.Invalid)
1311 // A diagnostic will have already been produced.
Richard Smithf3e9e432011-11-07 09:22:26 +00001312 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00001313 if (Sub.isOnePastTheEnd()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001314 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gay4a39e492011-12-21 19:36:37 +00001315 (unsigned)diag::note_constexpr_read_past_end :
1316 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001317 return false;
1318 }
Richard Smith6804be52011-11-11 08:28:03 +00001319 if (Sub.Entries.empty())
Richard Smithf3e9e432011-11-07 09:22:26 +00001320 return true;
Richard Smithf3e9e432011-11-07 09:22:26 +00001321
1322 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1323 const APValue *O = &Obj;
Richard Smithd62306a2011-11-10 06:34:14 +00001324 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001325 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001326 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001327 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001328 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001329 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001330 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001331 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001332 // Note, it should not be possible to form a pointer with a valid
1333 // designator which points more than one past the end of the array.
1334 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gay4a39e492011-12-21 19:36:37 +00001335 (unsigned)diag::note_constexpr_read_past_end :
1336 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +00001337 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001338 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001339 if (O->getArrayInitializedElts() > Index)
1340 O = &O->getArrayInitializedElt(Index);
1341 else
1342 O = &O->getArrayFiller();
1343 ObjType = CAT->getElementType();
Richard Smithd62306a2011-11-10 06:34:14 +00001344 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1345 // Next subobject is a class, struct or union field.
1346 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1347 if (RD->isUnion()) {
1348 const FieldDecl *UnionField = O->getUnionField();
1349 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001350 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001351 Info.Diag(E->getExprLoc(),
1352 diag::note_constexpr_read_inactive_union_member)
1353 << Field << !UnionField << UnionField;
Richard Smithd62306a2011-11-10 06:34:14 +00001354 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001355 }
Richard Smithd62306a2011-11-10 06:34:14 +00001356 O = &O->getUnionValue();
1357 } else
1358 O = &O->getStructField(Field->getFieldIndex());
1359 ObjType = Field->getType();
Richard Smithf2b681b2011-12-21 05:04:46 +00001360
1361 if (ObjType.isVolatileQualified()) {
1362 if (Info.getLangOpts().CPlusPlus) {
1363 // FIXME: Include a description of the path to the volatile subobject.
1364 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1365 << 2 << Field;
1366 Info.Note(Field->getLocation(), diag::note_declared_at);
1367 } else {
1368 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1369 }
1370 return false;
1371 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001372 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001373 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001374 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1375 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1376 O = &O->getStructBase(getBaseIndex(Derived, Base));
1377 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithf3e9e432011-11-07 09:22:26 +00001378 }
Richard Smithd62306a2011-11-10 06:34:14 +00001379
Richard Smithf57d8cb2011-12-09 22:58:01 +00001380 if (O->isUninit()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001381 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smithd62306a2011-11-10 06:34:14 +00001382 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001383 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001384 }
1385
Richard Smitha8105bc2012-01-06 16:39:00 +00001386 Obj = CCValue(Info.Ctx, *O, CCValue::GlobalValue());
Richard Smithf3e9e432011-11-07 09:22:26 +00001387 return true;
1388}
1389
Richard Smithd62306a2011-11-10 06:34:14 +00001390/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1391/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1392/// for looking up the glvalue referred to by an entity of reference type.
1393///
1394/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001395/// \param Conv - The expression for which we are performing the conversion.
1396/// Used for diagnostics.
Richard Smithd62306a2011-11-10 06:34:14 +00001397/// \param Type - The type we expect this conversion to produce.
1398/// \param LVal - The glvalue on which we are attempting to perform this action.
1399/// \param RVal - The produced value will be placed here.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001400static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1401 QualType Type,
Richard Smithf3e9e432011-11-07 09:22:26 +00001402 const LValue &LVal, CCValue &RVal) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001403 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1404 if (!Info.getLangOpts().CPlusPlus)
1405 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1406
Richard Smitha8105bc2012-01-06 16:39:00 +00001407 if (LVal.Designator.Invalid)
1408 // A diagnostic will have already been produced.
1409 return false;
1410
Richard Smithce40ad62011-11-12 22:28:03 +00001411 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001412 CallStackFrame *Frame = LVal.Frame;
Richard Smithf2b681b2011-12-21 05:04:46 +00001413 SourceLocation Loc = Conv->getExprLoc();
Richard Smith11562c52011-10-28 17:51:58 +00001414
Richard Smithf57d8cb2011-12-09 22:58:01 +00001415 if (!LVal.Base) {
1416 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smithf2b681b2011-12-21 05:04:46 +00001417 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1418 return false;
1419 }
1420
1421 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1422 // is not a constant expression (even if the object is non-volatile). We also
1423 // apply this rule to C++98, in order to conform to the expected 'volatile'
1424 // semantics.
1425 if (Type.isVolatileQualified()) {
1426 if (Info.getLangOpts().CPlusPlus)
1427 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1428 else
1429 Info.Diag(Loc);
Richard Smith11562c52011-10-28 17:51:58 +00001430 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001431 }
Richard Smith11562c52011-10-28 17:51:58 +00001432
Richard Smithce40ad62011-11-12 22:28:03 +00001433 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smith11562c52011-10-28 17:51:58 +00001434 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1435 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +00001436 // expressions are constant expressions too. Inside constexpr functions,
1437 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +00001438 // In C, such things can also be folded, although they are not ICEs.
Richard Smith11562c52011-10-28 17:51:58 +00001439 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001440 if (!VD || VD->isInvalidDecl()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001441 Info.Diag(Loc);
Richard Smith96e0c102011-11-04 02:25:55 +00001442 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001443 }
1444
Richard Smithf2b681b2011-12-21 05:04:46 +00001445 // DR1313: If the object is volatile-qualified but the glvalue was not,
1446 // behavior is undefined so the result is not a constant expression.
Richard Smithce40ad62011-11-12 22:28:03 +00001447 QualType VT = VD->getType();
Richard Smithf2b681b2011-12-21 05:04:46 +00001448 if (VT.isVolatileQualified()) {
1449 if (Info.getLangOpts().CPlusPlus) {
1450 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1451 Info.Note(VD->getLocation(), diag::note_declared_at);
1452 } else {
1453 Info.Diag(Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001454 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001455 return false;
1456 }
1457
1458 if (!isa<ParmVarDecl>(VD)) {
1459 if (VD->isConstexpr()) {
1460 // OK, we can read this variable.
1461 } else if (VT->isIntegralOrEnumerationType()) {
1462 if (!VT.isConstQualified()) {
1463 if (Info.getLangOpts().CPlusPlus) {
1464 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1465 Info.Note(VD->getLocation(), diag::note_declared_at);
1466 } else {
1467 Info.Diag(Loc);
1468 }
1469 return false;
1470 }
1471 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1472 // We support folding of const floating-point types, in order to make
1473 // static const data members of such types (supported as an extension)
1474 // more useful.
1475 if (Info.getLangOpts().CPlusPlus0x) {
1476 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1477 Info.Note(VD->getLocation(), diag::note_declared_at);
1478 } else {
1479 Info.CCEDiag(Loc);
1480 }
1481 } else {
1482 // FIXME: Allow folding of values of any literal type in all languages.
1483 if (Info.getLangOpts().CPlusPlus0x) {
1484 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1485 Info.Note(VD->getLocation(), diag::note_declared_at);
1486 } else {
1487 Info.Diag(Loc);
1488 }
Richard Smith96e0c102011-11-04 02:25:55 +00001489 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001490 }
Richard Smith96e0c102011-11-04 02:25:55 +00001491 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001492
Richard Smithf57d8cb2011-12-09 22:58:01 +00001493 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smith11562c52011-10-28 17:51:58 +00001494 return false;
1495
Richard Smith0b0a0b62011-10-29 20:57:55 +00001496 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf57d8cb2011-12-09 22:58:01 +00001497 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smith11562c52011-10-28 17:51:58 +00001498
1499 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1500 // conversion. This happens when the declaration and the lvalue should be
1501 // considered synonymous, for instance when initializing an array of char
1502 // from a string literal. Continue as if the initializer lvalue was the
1503 // value we were originally given.
Richard Smith96e0c102011-11-04 02:25:55 +00001504 assert(RVal.getLValueOffset().isZero() &&
1505 "offset for lvalue init of non-reference");
Richard Smithce40ad62011-11-12 22:28:03 +00001506 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001507 Frame = RVal.getLValueFrame();
Richard Smith11562c52011-10-28 17:51:58 +00001508 }
1509
Richard Smithf2b681b2011-12-21 05:04:46 +00001510 // Volatile temporary objects cannot be read in constant expressions.
1511 if (Base->getType().isVolatileQualified()) {
1512 if (Info.getLangOpts().CPlusPlus) {
1513 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1514 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1515 } else {
1516 Info.Diag(Loc);
1517 }
1518 return false;
1519 }
1520
Richard Smith96e0c102011-11-04 02:25:55 +00001521 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1522 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1523 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001524 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001525 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001526 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001527 }
Richard Smith96e0c102011-11-04 02:25:55 +00001528
1529 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith80815602011-11-07 05:07:52 +00001530 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smithf2b681b2011-12-21 05:04:46 +00001531 const ConstantArrayType *CAT =
1532 Info.Ctx.getAsConstantArrayType(S->getType());
1533 if (Index >= CAT->getSize().getZExtValue()) {
1534 // Note, it should not be possible to form a pointer which points more
1535 // than one past the end of the array without producing a prior const expr
1536 // diagnostic.
1537 Info.Diag(Loc, diag::note_constexpr_read_past_end);
Richard Smith96e0c102011-11-04 02:25:55 +00001538 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001539 }
Richard Smith96e0c102011-11-04 02:25:55 +00001540 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1541 Type->isUnsignedIntegerType());
1542 if (Index < S->getLength())
1543 Value = S->getCodeUnit(Index);
1544 RVal = CCValue(Value);
1545 return true;
1546 }
1547
Richard Smithf3e9e432011-11-07 09:22:26 +00001548 if (Frame) {
1549 // If this is a temporary expression with a nontrivial initializer, grab the
1550 // value from the relevant stack frame.
1551 RVal = Frame->Temporaries[Base];
1552 } else if (const CompoundLiteralExpr *CLE
1553 = dyn_cast<CompoundLiteralExpr>(Base)) {
1554 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1555 // initializer until now for such expressions. Such an expression can't be
1556 // an ICE in C, so this only matters for fold.
1557 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1558 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1559 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001560 } else {
Richard Smith92b1ce02011-12-12 09:28:41 +00001561 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001562 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001563 }
Richard Smith96e0c102011-11-04 02:25:55 +00001564
Richard Smithf57d8cb2011-12-09 22:58:01 +00001565 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1566 Type);
Richard Smith11562c52011-10-28 17:51:58 +00001567}
1568
Richard Smithe97cbd72011-11-11 04:05:33 +00001569/// Build an lvalue for the object argument of a member function call.
1570static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1571 LValue &This) {
1572 if (Object->getType()->isPointerType())
1573 return EvaluatePointer(Object, This, Info);
1574
1575 if (Object->isGLValue())
1576 return EvaluateLValue(Object, This, Info);
1577
Richard Smith027bf112011-11-17 22:56:20 +00001578 if (Object->getType()->isLiteralType())
1579 return EvaluateTemporary(Object, This, Info);
1580
1581 return false;
1582}
1583
1584/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1585/// lvalue referring to the result.
1586///
1587/// \param Info - Information about the ongoing evaluation.
1588/// \param BO - The member pointer access operation.
1589/// \param LV - Filled in with a reference to the resulting object.
1590/// \param IncludeMember - Specifies whether the member itself is included in
1591/// the resulting LValue subobject designator. This is not possible when
1592/// creating a bound member function.
1593/// \return The field or method declaration to which the member pointer refers,
1594/// or 0 if evaluation fails.
1595static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1596 const BinaryOperator *BO,
1597 LValue &LV,
1598 bool IncludeMember = true) {
1599 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1600
1601 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV))
1602 return 0;
1603
1604 MemberPtr MemPtr;
1605 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1606 return 0;
1607
1608 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1609 // member value, the behavior is undefined.
1610 if (!MemPtr.getDecl())
1611 return 0;
1612
1613 if (MemPtr.isDerivedMember()) {
1614 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00001615 // The end of the derived-to-base path for the base object must match the
1616 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00001617 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith027bf112011-11-17 22:56:20 +00001618 LV.Designator.Entries.size())
1619 return 0;
1620 unsigned PathLengthToMember =
1621 LV.Designator.Entries.size() - MemPtr.Path.size();
1622 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1623 const CXXRecordDecl *LVDecl = getAsBaseClass(
1624 LV.Designator.Entries[PathLengthToMember + I]);
1625 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1626 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1627 return 0;
1628 }
1629
1630 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00001631 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1632 PathLengthToMember))
1633 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00001634 } else if (!MemPtr.Path.empty()) {
1635 // Extend the LValue path with the member pointer's path.
1636 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1637 MemPtr.Path.size() + IncludeMember);
1638
1639 // Walk down to the appropriate base class.
1640 QualType LVType = BO->getLHS()->getType();
1641 if (const PointerType *PT = LVType->getAs<PointerType>())
1642 LVType = PT->getPointeeType();
1643 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1644 assert(RD && "member pointer access on non-class-type expression");
1645 // The first class in the path is that of the lvalue.
1646 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1647 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smitha8105bc2012-01-06 16:39:00 +00001648 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smith027bf112011-11-17 22:56:20 +00001649 RD = Base;
1650 }
1651 // Finally cast to the class containing the member.
Richard Smitha8105bc2012-01-06 16:39:00 +00001652 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smith027bf112011-11-17 22:56:20 +00001653 }
1654
1655 // Add the member. Note that we cannot build bound member functions here.
1656 if (IncludeMember) {
1657 // FIXME: Deal with IndirectFieldDecls.
1658 const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl());
1659 if (!FD) return 0;
Richard Smitha8105bc2012-01-06 16:39:00 +00001660 HandleLValueMember(Info, BO, LV, FD);
Richard Smith027bf112011-11-17 22:56:20 +00001661 }
1662
1663 return MemPtr.getDecl();
1664}
1665
1666/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1667/// the provided lvalue, which currently refers to the base object.
1668static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1669 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00001670 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001671 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00001672 return false;
1673
Richard Smitha8105bc2012-01-06 16:39:00 +00001674 QualType TargetQT = E->getType();
1675 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1676 TargetQT = PT->getPointeeType();
1677
1678 // Check this cast lands within the final derived-to-base subobject path.
1679 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
1680 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1681 << D.MostDerivedType << TargetQT;
1682 return false;
1683 }
1684
Richard Smith027bf112011-11-17 22:56:20 +00001685 // Check the type of the final cast. We don't need to check the path,
1686 // since a cast can only be formed if the path is unique.
1687 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00001688 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1689 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00001690 if (NewEntriesSize == D.MostDerivedPathLength)
1691 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
1692 else
Richard Smith027bf112011-11-17 22:56:20 +00001693 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00001694 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
1695 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1696 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00001697 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00001698 }
Richard Smith027bf112011-11-17 22:56:20 +00001699
1700 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00001701 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00001702}
1703
Mike Stump876387b2009-10-27 22:09:17 +00001704namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00001705enum EvalStmtResult {
1706 /// Evaluation failed.
1707 ESR_Failed,
1708 /// Hit a 'return' statement.
1709 ESR_Returned,
1710 /// Evaluation succeeded.
1711 ESR_Succeeded
1712};
1713}
1714
1715// Evaluate a statement.
Richard Smith357362d2011-12-13 06:39:58 +00001716static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +00001717 const Stmt *S) {
1718 switch (S->getStmtClass()) {
1719 default:
1720 return ESR_Failed;
1721
1722 case Stmt::NullStmtClass:
1723 case Stmt::DeclStmtClass:
1724 return ESR_Succeeded;
1725
Richard Smith357362d2011-12-13 06:39:58 +00001726 case Stmt::ReturnStmtClass: {
1727 CCValue CCResult;
1728 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1729 if (!Evaluate(CCResult, Info, RetExpr) ||
1730 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1731 CCEK_ReturnValue))
1732 return ESR_Failed;
1733 return ESR_Returned;
1734 }
Richard Smith254a73d2011-10-28 22:34:42 +00001735
1736 case Stmt::CompoundStmtClass: {
1737 const CompoundStmt *CS = cast<CompoundStmt>(S);
1738 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1739 BE = CS->body_end(); BI != BE; ++BI) {
1740 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1741 if (ESR != ESR_Succeeded)
1742 return ESR;
1743 }
1744 return ESR_Succeeded;
1745 }
1746 }
1747}
1748
Richard Smithcc36f692011-12-22 02:22:31 +00001749/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
1750/// default constructor. If so, we'll fold it whether or not it's marked as
1751/// constexpr. If it is marked as constexpr, we will never implicitly define it,
1752/// so we need special handling.
1753static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00001754 const CXXConstructorDecl *CD,
1755 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00001756 if (!CD->isTrivial() || !CD->isDefaultConstructor())
1757 return false;
1758
1759 if (!CD->isConstexpr()) {
1760 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smithfddd3842011-12-30 21:15:51 +00001761 // Value-initialization does not call a trivial default constructor, so
1762 // such a call is a core constant expression whether or not the
1763 // constructor is constexpr.
1764 if (!IsValueInitialization) {
1765 // FIXME: If DiagDecl is an implicitly-declared special member function,
1766 // we should be much more explicit about why it's not constexpr.
1767 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
1768 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
1769 Info.Note(CD->getLocation(), diag::note_declared_at);
1770 }
Richard Smithcc36f692011-12-22 02:22:31 +00001771 } else {
1772 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
1773 }
1774 }
1775 return true;
1776}
1777
Richard Smith357362d2011-12-13 06:39:58 +00001778/// CheckConstexprFunction - Check that a function can be called in a constant
1779/// expression.
1780static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1781 const FunctionDecl *Declaration,
1782 const FunctionDecl *Definition) {
1783 // Can we evaluate this function call?
1784 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1785 return true;
1786
1787 if (Info.getLangOpts().CPlusPlus0x) {
1788 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001789 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1790 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00001791 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1792 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1793 << DiagDecl;
1794 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1795 } else {
1796 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1797 }
1798 return false;
1799}
1800
Richard Smithd62306a2011-11-10 06:34:14 +00001801namespace {
Richard Smith60494462011-11-11 05:48:57 +00001802typedef SmallVector<CCValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00001803}
1804
1805/// EvaluateArgs - Evaluate the arguments to a function call.
1806static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1807 EvalInfo &Info) {
1808 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1809 I != E; ++I)
1810 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1811 return false;
1812 return true;
1813}
1814
Richard Smith254a73d2011-10-28 22:34:42 +00001815/// Evaluate a function call.
Richard Smithf6f003a2011-12-16 19:06:07 +00001816static bool HandleFunctionCall(const Expr *CallExpr, const FunctionDecl *Callee,
1817 const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00001818 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith357362d2011-12-13 06:39:58 +00001819 EvalInfo &Info, APValue &Result) {
1820 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smith254a73d2011-10-28 22:34:42 +00001821 return false;
1822
Richard Smithd62306a2011-11-10 06:34:14 +00001823 ArgVector ArgValues(Args.size());
1824 if (!EvaluateArgs(Args, ArgValues, Info))
1825 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00001826
Richard Smithf6f003a2011-12-16 19:06:07 +00001827 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Callee, This,
1828 ArgValues.data());
Richard Smith254a73d2011-10-28 22:34:42 +00001829 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1830}
1831
Richard Smithd62306a2011-11-10 06:34:14 +00001832/// Evaluate a constructor call.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001833static bool HandleConstructorCall(const Expr *CallExpr, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00001834 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00001835 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00001836 EvalInfo &Info, APValue &Result) {
Richard Smith357362d2011-12-13 06:39:58 +00001837 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smithd62306a2011-11-10 06:34:14 +00001838 return false;
1839
1840 ArgVector ArgValues(Args.size());
1841 if (!EvaluateArgs(Args, ArgValues, Info))
1842 return false;
1843
Richard Smithf6f003a2011-12-16 19:06:07 +00001844 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Definition,
1845 &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00001846
1847 // If it's a delegating constructor, just delegate.
1848 if (Definition->isDelegatingConstructor()) {
1849 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1850 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1851 }
1852
Richard Smith1bc5c2c2012-01-10 04:32:03 +00001853 // For a trivial copy or move constructor, perform an APValue copy. This is
1854 // essential for unions, where the operations performed by the constructor
1855 // cannot be represented by ctor-initializers.
Richard Smithd62306a2011-11-10 06:34:14 +00001856 const CXXRecordDecl *RD = Definition->getParent();
Richard Smith1bc5c2c2012-01-10 04:32:03 +00001857 if (Definition->isDefaulted() &&
1858 ((Definition->isCopyConstructor() && RD->hasTrivialCopyConstructor()) ||
1859 (Definition->isMoveConstructor() && RD->hasTrivialMoveConstructor()))) {
1860 LValue RHS;
1861 RHS.setFrom(ArgValues[0]);
1862 CCValue Value;
1863 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
1864 RHS, Value) &&
1865 CheckConstantExpression(Info, CallExpr, Value, Result);
1866 }
1867
1868 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00001869 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00001870 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1871 std::distance(RD->field_begin(), RD->field_end()));
1872
1873 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1874
1875 unsigned BasesSeen = 0;
1876#ifndef NDEBUG
1877 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1878#endif
1879 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1880 E = Definition->init_end(); I != E; ++I) {
1881 if ((*I)->isBaseInitializer()) {
1882 QualType BaseType((*I)->getBaseClass(), 0);
1883#ifndef NDEBUG
1884 // Non-virtual base classes are initialized in the order in the class
1885 // definition. We cannot have a virtual base class for a literal type.
1886 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1887 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1888 "base class initializers not in expected order");
1889 ++BaseIt;
1890#endif
1891 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00001892 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smithd62306a2011-11-10 06:34:14 +00001893 BaseType->getAsCXXRecordDecl(), &Layout);
1894 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1895 Subobject, (*I)->getInit()))
1896 return false;
1897 } else if (FieldDecl *FD = (*I)->getMember()) {
1898 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00001899 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smithd62306a2011-11-10 06:34:14 +00001900 if (RD->isUnion()) {
1901 Result = APValue(FD);
Richard Smith357362d2011-12-13 06:39:58 +00001902 if (!EvaluateConstantExpression(Result.getUnionValue(), Info, Subobject,
1903 (*I)->getInit(), CCEK_MemberInit))
Richard Smithd62306a2011-11-10 06:34:14 +00001904 return false;
1905 } else if (!EvaluateConstantExpression(
1906 Result.getStructField(FD->getFieldIndex()),
Richard Smith357362d2011-12-13 06:39:58 +00001907 Info, Subobject, (*I)->getInit(), CCEK_MemberInit))
Richard Smithd62306a2011-11-10 06:34:14 +00001908 return false;
1909 } else {
1910 // FIXME: handle indirect field initializers
Richard Smith92b1ce02011-12-12 09:28:41 +00001911 Info.Diag((*I)->getInit()->getExprLoc(),
Richard Smithf57d8cb2011-12-09 22:58:01 +00001912 diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +00001913 return false;
1914 }
1915 }
1916
1917 return true;
1918}
1919
Richard Smith254a73d2011-10-28 22:34:42 +00001920namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001921class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +00001922 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +00001923 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +00001924public:
1925
Richard Smith725810a2011-10-16 21:26:27 +00001926 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +00001927
1928 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +00001929 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +00001930 return true;
1931 }
1932
Peter Collingbournee9200682011-05-13 03:29:01 +00001933 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1934 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001935 return Visit(E->getResultExpr());
1936 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001937 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001938 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001939 return true;
1940 return false;
1941 }
John McCall31168b02011-06-15 23:02:42 +00001942 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001943 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001944 return true;
1945 return false;
1946 }
1947 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001948 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001949 return true;
1950 return false;
1951 }
1952
Mike Stump876387b2009-10-27 22:09:17 +00001953 // We don't want to evaluate BlockExprs multiple times, as they generate
1954 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +00001955 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1956 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1957 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +00001958 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001959 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1960 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1961 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1962 bool VisitStringLiteral(const StringLiteral *E) { return false; }
1963 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1964 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +00001965 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +00001966 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001967 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001968 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +00001969 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001970 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
1971 bool VisitBinAssign(const BinaryOperator *E) { return true; }
1972 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
1973 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001974 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001975 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
1976 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
1977 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
1978 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
1979 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001980 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001981 return true;
Mike Stumpfa502902009-10-29 20:48:09 +00001982 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +00001983 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001984 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +00001985
1986 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +00001987 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +00001988 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
1989 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00001990 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +00001991 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +00001992 return false;
1993 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001994
Peter Collingbournee9200682011-05-13 03:29:01 +00001995 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +00001996};
1997
John McCallc07a0c72011-02-17 10:25:35 +00001998class OpaqueValueEvaluation {
1999 EvalInfo &info;
2000 OpaqueValueExpr *opaqueValue;
2001
2002public:
2003 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2004 Expr *value)
2005 : info(info), opaqueValue(opaqueValue) {
2006
2007 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +00002008 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +00002009 this->opaqueValue = 0;
2010 return;
2011 }
John McCallc07a0c72011-02-17 10:25:35 +00002012 }
2013
2014 bool hasError() const { return opaqueValue == 0; }
2015
2016 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +00002017 // FIXME: This will not work for recursive constexpr functions using opaque
2018 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +00002019 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2020 }
2021};
2022
Mike Stump876387b2009-10-27 22:09:17 +00002023} // end anonymous namespace
2024
Eli Friedman9a156e52008-11-12 09:44:48 +00002025//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00002026// Generic Evaluation
2027//===----------------------------------------------------------------------===//
2028namespace {
2029
Richard Smithf57d8cb2011-12-09 22:58:01 +00002030// FIXME: RetTy is always bool. Remove it.
2031template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00002032class ExprEvaluatorBase
2033 : public ConstStmtVisitor<Derived, RetTy> {
2034private:
Richard Smith0b0a0b62011-10-29 20:57:55 +00002035 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002036 return static_cast<Derived*>(this)->Success(V, E);
2037 }
Richard Smithfddd3842011-12-30 21:15:51 +00002038 RetTy DerivedZeroInitialization(const Expr *E) {
2039 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002040 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002041
2042protected:
2043 EvalInfo &Info;
2044 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2045 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2046
Richard Smith92b1ce02011-12-12 09:28:41 +00002047 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith187ef012011-12-12 09:41:58 +00002048 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002049 }
2050
2051 /// Report an evaluation error. This should only be called when an error is
2052 /// first discovered. When propagating an error, just return false.
2053 bool Error(const Expr *E, diag::kind D) {
Richard Smith92b1ce02011-12-12 09:28:41 +00002054 Info.Diag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002055 return false;
2056 }
2057 bool Error(const Expr *E) {
2058 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2059 }
2060
Richard Smithfddd3842011-12-30 21:15:51 +00002061 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00002062
Peter Collingbournee9200682011-05-13 03:29:01 +00002063public:
2064 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2065
2066 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00002067 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00002068 }
2069 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002070 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002071 }
2072
2073 RetTy VisitParenExpr(const ParenExpr *E)
2074 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2075 RetTy VisitUnaryExtension(const UnaryOperator *E)
2076 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2077 RetTy VisitUnaryPlus(const UnaryOperator *E)
2078 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2079 RetTy VisitChooseExpr(const ChooseExpr *E)
2080 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2081 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2082 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00002083 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2084 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00002085 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2086 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00002087 // We cannot create any objects for which cleanups are required, so there is
2088 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2089 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2090 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002091
Richard Smith6d6ecc32011-12-12 12:46:16 +00002092 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2093 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2094 return static_cast<Derived*>(this)->VisitCastExpr(E);
2095 }
2096 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2097 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2098 return static_cast<Derived*>(this)->VisitCastExpr(E);
2099 }
2100
Richard Smith027bf112011-11-17 22:56:20 +00002101 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2102 switch (E->getOpcode()) {
2103 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00002104 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002105
2106 case BO_Comma:
2107 VisitIgnoredValue(E->getLHS());
2108 return StmtVisitorTy::Visit(E->getRHS());
2109
2110 case BO_PtrMemD:
2111 case BO_PtrMemI: {
2112 LValue Obj;
2113 if (!HandleMemberPointerAccess(Info, E, Obj))
2114 return false;
2115 CCValue Result;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002116 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00002117 return false;
2118 return DerivedSuccess(Result, E);
2119 }
2120 }
2121 }
2122
Peter Collingbournee9200682011-05-13 03:29:01 +00002123 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2124 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2125 if (opaque.hasError())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002126 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002127
2128 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +00002129 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002130 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002131
2132 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
2133 }
2134
2135 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
2136 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00002137 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002138 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002139
Richard Smith11562c52011-10-28 17:51:58 +00002140 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +00002141 return StmtVisitorTy::Visit(EvalExpr);
2142 }
2143
2144 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002145 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002146 if (!Value) {
2147 const Expr *Source = E->getSourceExpr();
2148 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002149 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002150 if (Source == E) { // sanity checking.
2151 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00002152 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002153 }
2154 return StmtVisitorTy::Visit(Source);
2155 }
Richard Smith0b0a0b62011-10-29 20:57:55 +00002156 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002157 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002158
Richard Smith254a73d2011-10-28 22:34:42 +00002159 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002160 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00002161 QualType CalleeType = Callee->getType();
2162
Richard Smith254a73d2011-10-28 22:34:42 +00002163 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00002164 LValue *This = 0, ThisVal;
2165 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith656d49d2011-11-10 09:31:24 +00002166
Richard Smithe97cbd72011-11-11 04:05:33 +00002167 // Extract function decl and 'this' pointer from the callee.
2168 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002169 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00002170 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2171 // Explicit bound member calls, such as x.f() or p->g();
2172 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002173 return false;
2174 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00002175 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00002176 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2177 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00002178 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2179 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00002180 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00002181 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002182 return Error(Callee);
2183
2184 FD = dyn_cast<FunctionDecl>(Member);
2185 if (!FD)
2186 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002187 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002188 LValue Call;
2189 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002190 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00002191
Richard Smitha8105bc2012-01-06 16:39:00 +00002192 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002193 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00002194 FD = dyn_cast_or_null<FunctionDecl>(
2195 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00002196 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002197 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002198
2199 // Overloaded operator calls to member functions are represented as normal
2200 // calls with '*this' as the first argument.
2201 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2202 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002203 // FIXME: When selecting an implicit conversion for an overloaded
2204 // operator delete, we sometimes try to evaluate calls to conversion
2205 // operators without a 'this' parameter!
2206 if (Args.empty())
2207 return Error(E);
2208
Richard Smithe97cbd72011-11-11 04:05:33 +00002209 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2210 return false;
2211 This = &ThisVal;
2212 Args = Args.slice(1);
2213 }
2214
2215 // Don't call function pointers which have been cast to some other type.
2216 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002217 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00002218 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002219 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00002220
Richard Smith357362d2011-12-13 06:39:58 +00002221 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00002222 Stmt *Body = FD->getBody(Definition);
Richard Smithed5165f2011-11-04 05:33:44 +00002223 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00002224
Richard Smith357362d2011-12-13 06:39:58 +00002225 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smithf6f003a2011-12-16 19:06:07 +00002226 !HandleFunctionCall(E, Definition, This, Args, Body, Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002227 return false;
2228
Richard Smitha8105bc2012-01-06 16:39:00 +00002229 return DerivedSuccess(CCValue(Info.Ctx, Result, CCValue::GlobalValue()), E);
Richard Smith254a73d2011-10-28 22:34:42 +00002230 }
2231
Richard Smith11562c52011-10-28 17:51:58 +00002232 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2233 return StmtVisitorTy::Visit(E->getInitializer());
2234 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002235 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00002236 if (E->getNumInits() == 0)
2237 return DerivedZeroInitialization(E);
2238 if (E->getNumInits() == 1)
2239 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00002240 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002241 }
2242 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002243 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002244 }
2245 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002246 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002247 }
Richard Smith027bf112011-11-17 22:56:20 +00002248 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002249 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00002250 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002251
Richard Smithd62306a2011-11-10 06:34:14 +00002252 /// A member expression where the object is a prvalue is itself a prvalue.
2253 RetTy VisitMemberExpr(const MemberExpr *E) {
2254 assert(!E->isArrow() && "missing call to bound member function?");
2255
2256 CCValue Val;
2257 if (!Evaluate(Val, Info, E->getBase()))
2258 return false;
2259
2260 QualType BaseTy = E->getBase()->getType();
2261
2262 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00002263 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002264 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2265 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2266 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2267
Richard Smitha8105bc2012-01-06 16:39:00 +00002268 SubobjectDesignator Designator(BaseTy);
2269 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00002270
Richard Smithf57d8cb2011-12-09 22:58:01 +00002271 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smithd62306a2011-11-10 06:34:14 +00002272 DerivedSuccess(Val, E);
2273 }
2274
Richard Smith11562c52011-10-28 17:51:58 +00002275 RetTy VisitCastExpr(const CastExpr *E) {
2276 switch (E->getCastKind()) {
2277 default:
2278 break;
2279
2280 case CK_NoOp:
2281 return StmtVisitorTy::Visit(E->getSubExpr());
2282
2283 case CK_LValueToRValue: {
2284 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002285 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2286 return false;
2287 CCValue RVal;
2288 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2289 return false;
2290 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00002291 }
2292 }
2293
Richard Smithf57d8cb2011-12-09 22:58:01 +00002294 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002295 }
2296
Richard Smith4a678122011-10-24 18:44:57 +00002297 /// Visit a value which is evaluated, but whose value is ignored.
2298 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002299 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +00002300 if (!Evaluate(Scratch, Info, E))
2301 Info.EvalStatus.HasSideEffects = true;
2302 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002303};
2304
2305}
2306
2307//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002308// Common base class for lvalue and temporary evaluation.
2309//===----------------------------------------------------------------------===//
2310namespace {
2311template<class Derived>
2312class LValueExprEvaluatorBase
2313 : public ExprEvaluatorBase<Derived, bool> {
2314protected:
2315 LValue &Result;
2316 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2317 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2318
2319 bool Success(APValue::LValueBase B) {
2320 Result.set(B);
2321 return true;
2322 }
2323
2324public:
2325 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2326 ExprEvaluatorBaseTy(Info), Result(Result) {}
2327
2328 bool Success(const CCValue &V, const Expr *E) {
2329 Result.setFrom(V);
2330 return true;
2331 }
Richard Smith027bf112011-11-17 22:56:20 +00002332
Richard Smith027bf112011-11-17 22:56:20 +00002333 bool VisitMemberExpr(const MemberExpr *E) {
2334 // Handle non-static data members.
2335 QualType BaseTy;
2336 if (E->isArrow()) {
2337 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2338 return false;
2339 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00002340 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002341 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00002342 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2343 return false;
2344 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00002345 } else {
2346 if (!this->Visit(E->getBase()))
2347 return false;
2348 BaseTy = E->getBase()->getType();
2349 }
Richard Smith027bf112011-11-17 22:56:20 +00002350
2351 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2352 // FIXME: Handle IndirectFieldDecls
Richard Smithf57d8cb2011-12-09 22:58:01 +00002353 if (!FD) return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002354 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2355 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2356 (void)BaseTy;
2357
Richard Smitha8105bc2012-01-06 16:39:00 +00002358 HandleLValueMember(this->Info, E, Result, FD);
Richard Smith027bf112011-11-17 22:56:20 +00002359
2360 if (FD->getType()->isReferenceType()) {
2361 CCValue RefValue;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002362 if (!HandleLValueToRValueConversion(this->Info, E, FD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002363 RefValue))
2364 return false;
2365 return Success(RefValue, E);
2366 }
2367 return true;
2368 }
2369
2370 bool VisitBinaryOperator(const BinaryOperator *E) {
2371 switch (E->getOpcode()) {
2372 default:
2373 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2374
2375 case BO_PtrMemD:
2376 case BO_PtrMemI:
2377 return HandleMemberPointerAccess(this->Info, E, Result);
2378 }
2379 }
2380
2381 bool VisitCastExpr(const CastExpr *E) {
2382 switch (E->getCastKind()) {
2383 default:
2384 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2385
2386 case CK_DerivedToBase:
2387 case CK_UncheckedDerivedToBase: {
2388 if (!this->Visit(E->getSubExpr()))
2389 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002390
2391 // Now figure out the necessary offset to add to the base LV to get from
2392 // the derived class to the base class.
2393 QualType Type = E->getSubExpr()->getType();
2394
2395 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2396 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002397 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smith027bf112011-11-17 22:56:20 +00002398 *PathI))
2399 return false;
2400 Type = (*PathI)->getType();
2401 }
2402
2403 return true;
2404 }
2405 }
2406 }
2407};
2408}
2409
2410//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00002411// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00002412//
2413// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2414// function designators (in C), decl references to void objects (in C), and
2415// temporaries (if building with -Wno-address-of-temporary).
2416//
2417// LValue evaluation produces values comprising a base expression of one of the
2418// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00002419// - Declarations
2420// * VarDecl
2421// * FunctionDecl
2422// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00002423// * CompoundLiteralExpr in C
2424// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00002425// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00002426// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00002427// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00002428// * ObjCEncodeExpr
2429// * AddrLabelExpr
2430// * BlockExpr
2431// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00002432// - Locals and temporaries
2433// * Any Expr, with a Frame indicating the function in which the temporary was
2434// evaluated.
2435// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00002436//===----------------------------------------------------------------------===//
2437namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002438class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00002439 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00002440public:
Richard Smith027bf112011-11-17 22:56:20 +00002441 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2442 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00002443
Richard Smith11562c52011-10-28 17:51:58 +00002444 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2445
Peter Collingbournee9200682011-05-13 03:29:01 +00002446 bool VisitDeclRefExpr(const DeclRefExpr *E);
2447 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002448 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002449 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2450 bool VisitMemberExpr(const MemberExpr *E);
2451 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2452 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00002453 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002454 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2455 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002456
Peter Collingbournee9200682011-05-13 03:29:01 +00002457 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00002458 switch (E->getCastKind()) {
2459 default:
Richard Smith027bf112011-11-17 22:56:20 +00002460 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002461
Eli Friedmance3e02a2011-10-11 00:13:24 +00002462 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002463 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00002464 if (!Visit(E->getSubExpr()))
2465 return false;
2466 Result.Designator.setInvalid();
2467 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00002468
Richard Smith027bf112011-11-17 22:56:20 +00002469 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00002470 if (!Visit(E->getSubExpr()))
2471 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002472 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00002473 }
2474 }
Sebastian Redl12757ab2011-09-24 17:48:14 +00002475
Eli Friedman449fe542009-03-23 04:56:01 +00002476 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +00002477
Eli Friedman9a156e52008-11-12 09:44:48 +00002478};
2479} // end anonymous namespace
2480
Richard Smith11562c52011-10-28 17:51:58 +00002481/// Evaluate an expression as an lvalue. This can be legitimately called on
2482/// expressions which are not glvalues, in a few cases:
2483/// * function designators in C,
2484/// * "extern void" objects,
2485/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +00002486static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002487 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2488 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2489 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +00002490 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002491}
2492
Peter Collingbournee9200682011-05-13 03:29:01 +00002493bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002494 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2495 return Success(FD);
2496 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00002497 return VisitVarDecl(E, VD);
2498 return Error(E);
2499}
Richard Smith733237d2011-10-24 23:14:33 +00002500
Richard Smith11562c52011-10-28 17:51:58 +00002501bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +00002502 if (!VD->getType()->isReferenceType()) {
2503 if (isa<ParmVarDecl>(VD)) {
Richard Smithce40ad62011-11-12 22:28:03 +00002504 Result.set(VD, Info.CurrentCall);
Richard Smithfec09922011-11-01 16:57:24 +00002505 return true;
2506 }
Richard Smithce40ad62011-11-12 22:28:03 +00002507 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00002508 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00002509
Richard Smith0b0a0b62011-10-29 20:57:55 +00002510 CCValue V;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002511 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2512 return false;
2513 return Success(V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00002514}
2515
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002516bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2517 const MaterializeTemporaryExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002518 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002519 if (E->getType()->isRecordType())
Richard Smith027bf112011-11-17 22:56:20 +00002520 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2521
2522 Result.set(E, Info.CurrentCall);
2523 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2524 Result, E->GetTemporaryExpr());
2525 }
2526
2527 // Materialization of an lvalue temporary occurs when we need to force a copy
2528 // (for instance, if it's a bitfield).
2529 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2530 if (!Visit(E->GetTemporaryExpr()))
2531 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002532 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002533 Info.CurrentCall->Temporaries[E]))
2534 return false;
Richard Smithce40ad62011-11-12 22:28:03 +00002535 Result.set(E, Info.CurrentCall);
Richard Smith027bf112011-11-17 22:56:20 +00002536 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002537}
2538
Peter Collingbournee9200682011-05-13 03:29:01 +00002539bool
2540LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002541 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2542 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2543 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00002544 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002545}
2546
Richard Smith6e525142011-12-27 12:18:28 +00002547bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2548 if (E->isTypeOperand())
2549 return Success(E);
2550 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2551 if (RD && RD->isPolymorphic()) {
2552 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2553 << E->getExprOperand()->getType()
2554 << E->getExprOperand()->getSourceRange();
2555 return false;
2556 }
2557 return Success(E);
2558}
2559
Peter Collingbournee9200682011-05-13 03:29:01 +00002560bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002561 // Handle static data members.
2562 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2563 VisitIgnoredValue(E->getBase());
2564 return VisitVarDecl(E, VD);
2565 }
2566
Richard Smith254a73d2011-10-28 22:34:42 +00002567 // Handle static member functions.
2568 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2569 if (MD->isStatic()) {
2570 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00002571 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00002572 }
2573 }
2574
Richard Smithd62306a2011-11-10 06:34:14 +00002575 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00002576 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002577}
2578
Peter Collingbournee9200682011-05-13 03:29:01 +00002579bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002580 // FIXME: Deal with vectors as array subscript bases.
2581 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002582 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002583
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002584 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00002585 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002586
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002587 APSInt Index;
2588 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00002589 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002590 int64_t IndexValue
2591 = Index.isSigned() ? Index.getSExtValue()
2592 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002593
Richard Smitha8105bc2012-01-06 16:39:00 +00002594 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002595}
Eli Friedman9a156e52008-11-12 09:44:48 +00002596
Peter Collingbournee9200682011-05-13 03:29:01 +00002597bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00002598 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00002599}
2600
Eli Friedman9a156e52008-11-12 09:44:48 +00002601//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00002602// Pointer Evaluation
2603//===----------------------------------------------------------------------===//
2604
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002605namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002606class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002607 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00002608 LValue &Result;
2609
Peter Collingbournee9200682011-05-13 03:29:01 +00002610 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002611 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00002612 return true;
2613 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002614public:
Mike Stump11289f42009-09-09 15:08:12 +00002615
John McCall45d55e42010-05-07 21:00:08 +00002616 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002617 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00002618
Richard Smith0b0a0b62011-10-29 20:57:55 +00002619 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002620 Result.setFrom(V);
2621 return true;
2622 }
Richard Smithfddd3842011-12-30 21:15:51 +00002623 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00002624 return Success((Expr*)0);
2625 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002626
John McCall45d55e42010-05-07 21:00:08 +00002627 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002628 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00002629 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002630 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00002631 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002632 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00002633 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002634 bool VisitCallExpr(const CallExpr *E);
2635 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00002636 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00002637 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002638 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00002639 }
Richard Smithd62306a2011-11-10 06:34:14 +00002640 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2641 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002642 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002643 Result = *Info.CurrentCall->This;
2644 return true;
2645 }
John McCallc07a0c72011-02-17 10:25:35 +00002646
Eli Friedman449fe542009-03-23 04:56:01 +00002647 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002648};
Chris Lattner05706e882008-07-11 18:11:29 +00002649} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002650
John McCall45d55e42010-05-07 21:00:08 +00002651static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002652 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00002653 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00002654}
2655
John McCall45d55e42010-05-07 21:00:08 +00002656bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002657 if (E->getOpcode() != BO_Add &&
2658 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00002659 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00002660
Chris Lattner05706e882008-07-11 18:11:29 +00002661 const Expr *PExp = E->getLHS();
2662 const Expr *IExp = E->getRHS();
2663 if (IExp->getType()->isPointerType())
2664 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00002665
John McCall45d55e42010-05-07 21:00:08 +00002666 if (!EvaluatePointer(PExp, Result, Info))
2667 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002668
John McCall45d55e42010-05-07 21:00:08 +00002669 llvm::APSInt Offset;
2670 if (!EvaluateInteger(IExp, Offset, Info))
2671 return false;
2672 int64_t AdditionalOffset
2673 = Offset.isSigned() ? Offset.getSExtValue()
2674 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00002675 if (E->getOpcode() == BO_Sub)
2676 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00002677
Richard Smithd62306a2011-11-10 06:34:14 +00002678 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00002679 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
2680 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00002681}
Eli Friedman9a156e52008-11-12 09:44:48 +00002682
John McCall45d55e42010-05-07 21:00:08 +00002683bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2684 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002685}
Mike Stump11289f42009-09-09 15:08:12 +00002686
Peter Collingbournee9200682011-05-13 03:29:01 +00002687bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2688 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00002689
Eli Friedman847a2bc2009-12-27 05:43:15 +00002690 switch (E->getCastKind()) {
2691 default:
2692 break;
2693
John McCalle3027922010-08-25 11:45:40 +00002694 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00002695 case CK_CPointerToObjCPointerCast:
2696 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00002697 case CK_AnyPointerToBlockPointerCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002698 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2699 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2700 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00002701 if (!E->getType()->isVoidPointerType()) {
2702 if (SubExpr->getType()->isVoidPointerType())
2703 CCEDiag(E, diag::note_constexpr_invalid_cast)
2704 << 3 << SubExpr->getType();
2705 else
2706 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2707 }
Richard Smith96e0c102011-11-04 02:25:55 +00002708 if (!Visit(SubExpr))
2709 return false;
2710 Result.Designator.setInvalid();
2711 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00002712
Anders Carlsson18275092010-10-31 20:41:46 +00002713 case CK_DerivedToBase:
2714 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002715 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00002716 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002717 if (!Result.Base && Result.Offset.isZero())
2718 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00002719
Richard Smithd62306a2011-11-10 06:34:14 +00002720 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00002721 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00002722 QualType Type =
2723 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00002724
Richard Smithd62306a2011-11-10 06:34:14 +00002725 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00002726 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002727 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2728 *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00002729 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002730 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00002731 }
2732
Anders Carlsson18275092010-10-31 20:41:46 +00002733 return true;
2734 }
2735
Richard Smith027bf112011-11-17 22:56:20 +00002736 case CK_BaseToDerived:
2737 if (!Visit(E->getSubExpr()))
2738 return false;
2739 if (!Result.Base && Result.Offset.isZero())
2740 return true;
2741 return HandleBaseToDerivedCast(Info, E, Result);
2742
Richard Smith0b0a0b62011-10-29 20:57:55 +00002743 case CK_NullToPointer:
Richard Smithfddd3842011-12-30 21:15:51 +00002744 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00002745
John McCalle3027922010-08-25 11:45:40 +00002746 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00002747 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2748
Richard Smith0b0a0b62011-10-29 20:57:55 +00002749 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00002750 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00002751 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00002752
John McCall45d55e42010-05-07 21:00:08 +00002753 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002754 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2755 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00002756 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002757 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithfec09922011-11-01 16:57:24 +00002758 Result.Frame = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00002759 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00002760 return true;
2761 } else {
2762 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002763 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00002764 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00002765 }
2766 }
John McCalle3027922010-08-25 11:45:40 +00002767 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00002768 if (SubExpr->isGLValue()) {
2769 if (!EvaluateLValue(SubExpr, Result, Info))
2770 return false;
2771 } else {
2772 Result.set(SubExpr, Info.CurrentCall);
2773 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2774 Info, Result, SubExpr))
2775 return false;
2776 }
Richard Smith96e0c102011-11-04 02:25:55 +00002777 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00002778 if (const ConstantArrayType *CAT
2779 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
2780 Result.addArray(Info, E, CAT);
2781 else
2782 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00002783 return true;
Richard Smithdd785442011-10-31 20:57:44 +00002784
John McCalle3027922010-08-25 11:45:40 +00002785 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00002786 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002787 }
2788
Richard Smith11562c52011-10-28 17:51:58 +00002789 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00002790}
Chris Lattner05706e882008-07-11 18:11:29 +00002791
Peter Collingbournee9200682011-05-13 03:29:01 +00002792bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00002793 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00002794 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00002795
Peter Collingbournee9200682011-05-13 03:29:01 +00002796 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002797}
Chris Lattner05706e882008-07-11 18:11:29 +00002798
2799//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002800// Member Pointer Evaluation
2801//===----------------------------------------------------------------------===//
2802
2803namespace {
2804class MemberPointerExprEvaluator
2805 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2806 MemberPtr &Result;
2807
2808 bool Success(const ValueDecl *D) {
2809 Result = MemberPtr(D);
2810 return true;
2811 }
2812public:
2813
2814 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2815 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2816
2817 bool Success(const CCValue &V, const Expr *E) {
2818 Result.setFrom(V);
2819 return true;
2820 }
Richard Smithfddd3842011-12-30 21:15:51 +00002821 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002822 return Success((const ValueDecl*)0);
2823 }
2824
2825 bool VisitCastExpr(const CastExpr *E);
2826 bool VisitUnaryAddrOf(const UnaryOperator *E);
2827};
2828} // end anonymous namespace
2829
2830static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2831 EvalInfo &Info) {
2832 assert(E->isRValue() && E->getType()->isMemberPointerType());
2833 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2834}
2835
2836bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2837 switch (E->getCastKind()) {
2838 default:
2839 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2840
2841 case CK_NullToMemberPointer:
Richard Smithfddd3842011-12-30 21:15:51 +00002842 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00002843
2844 case CK_BaseToDerivedMemberPointer: {
2845 if (!Visit(E->getSubExpr()))
2846 return false;
2847 if (E->path_empty())
2848 return true;
2849 // Base-to-derived member pointer casts store the path in derived-to-base
2850 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2851 // the wrong end of the derived->base arc, so stagger the path by one class.
2852 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2853 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2854 PathI != PathE; ++PathI) {
2855 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2856 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2857 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002858 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002859 }
2860 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2861 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002862 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002863 return true;
2864 }
2865
2866 case CK_DerivedToBaseMemberPointer:
2867 if (!Visit(E->getSubExpr()))
2868 return false;
2869 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2870 PathE = E->path_end(); PathI != PathE; ++PathI) {
2871 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2872 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2873 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002874 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002875 }
2876 return true;
2877 }
2878}
2879
2880bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2881 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
2882 // member can be formed.
2883 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
2884}
2885
2886//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00002887// Record Evaluation
2888//===----------------------------------------------------------------------===//
2889
2890namespace {
2891 class RecordExprEvaluator
2892 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
2893 const LValue &This;
2894 APValue &Result;
2895 public:
2896
2897 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
2898 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
2899
2900 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002901 return CheckConstantExpression(Info, E, V, Result);
Richard Smithd62306a2011-11-10 06:34:14 +00002902 }
Richard Smithfddd3842011-12-30 21:15:51 +00002903 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00002904
Richard Smithe97cbd72011-11-11 04:05:33 +00002905 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00002906 bool VisitInitListExpr(const InitListExpr *E);
2907 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
2908 };
2909}
2910
Richard Smithfddd3842011-12-30 21:15:51 +00002911/// Perform zero-initialization on an object of non-union class type.
2912/// C++11 [dcl.init]p5:
2913/// To zero-initialize an object or reference of type T means:
2914/// [...]
2915/// -- if T is a (possibly cv-qualified) non-union class type,
2916/// each non-static data member and each base-class subobject is
2917/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00002918static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
2919 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00002920 const LValue &This, APValue &Result) {
2921 assert(!RD->isUnion() && "Expected non-union class type");
2922 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
2923 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
2924 std::distance(RD->field_begin(), RD->field_end()));
2925
2926 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2927
2928 if (CD) {
2929 unsigned Index = 0;
2930 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00002931 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00002932 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
2933 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00002934 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
2935 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00002936 Result.getStructBase(Index)))
2937 return false;
2938 }
2939 }
2940
Richard Smitha8105bc2012-01-06 16:39:00 +00002941 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
2942 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00002943 // -- if T is a reference type, no initialization is performed.
2944 if ((*I)->getType()->isReferenceType())
2945 continue;
2946
2947 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00002948 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smithfddd3842011-12-30 21:15:51 +00002949
2950 ImplicitValueInitExpr VIE((*I)->getType());
2951 if (!EvaluateConstantExpression(
2952 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
2953 return false;
2954 }
2955
2956 return true;
2957}
2958
2959bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
2960 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2961 if (RD->isUnion()) {
2962 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
2963 // object's first non-static named data member is zero-initialized
2964 RecordDecl::field_iterator I = RD->field_begin();
2965 if (I == RD->field_end()) {
2966 Result = APValue((const FieldDecl*)0);
2967 return true;
2968 }
2969
2970 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00002971 HandleLValueMember(Info, E, Subobject, *I);
Richard Smithfddd3842011-12-30 21:15:51 +00002972 Result = APValue(*I);
2973 ImplicitValueInitExpr VIE((*I)->getType());
2974 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2975 Subobject, &VIE);
2976 }
2977
Richard Smitha8105bc2012-01-06 16:39:00 +00002978 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00002979}
2980
Richard Smithe97cbd72011-11-11 04:05:33 +00002981bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
2982 switch (E->getCastKind()) {
2983 default:
2984 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2985
2986 case CK_ConstructorConversion:
2987 return Visit(E->getSubExpr());
2988
2989 case CK_DerivedToBase:
2990 case CK_UncheckedDerivedToBase: {
2991 CCValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002992 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00002993 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002994 if (!DerivedObject.isStruct())
2995 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00002996
2997 // Derived-to-base rvalue conversion: just slice off the derived part.
2998 APValue *Value = &DerivedObject;
2999 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3000 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3001 PathE = E->path_end(); PathI != PathE; ++PathI) {
3002 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3003 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3004 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3005 RD = Base;
3006 }
3007 Result = *Value;
3008 return true;
3009 }
3010 }
3011}
3012
Richard Smithd62306a2011-11-10 06:34:14 +00003013bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3014 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3015 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3016
3017 if (RD->isUnion()) {
3018 Result = APValue(E->getInitializedFieldInUnion());
3019 if (!E->getNumInits())
3020 return true;
3021 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00003022 HandleLValueMember(Info, E->getInit(0), Subobject,
3023 E->getInitializedFieldInUnion(), &Layout);
Richard Smithd62306a2011-11-10 06:34:14 +00003024 return EvaluateConstantExpression(Result.getUnionValue(), Info,
3025 Subobject, E->getInit(0));
3026 }
3027
3028 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3029 "initializer list for class with base classes");
3030 Result = APValue(APValue::UninitStruct(), 0,
3031 std::distance(RD->field_begin(), RD->field_end()));
3032 unsigned ElementNo = 0;
3033 for (RecordDecl::field_iterator Field = RD->field_begin(),
3034 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3035 // Anonymous bit-fields are not considered members of the class for
3036 // purposes of aggregate initialization.
3037 if (Field->isUnnamedBitfield())
3038 continue;
3039
3040 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00003041
3042 if (ElementNo < E->getNumInits()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003043 HandleLValueMember(Info, E->getInit(ElementNo), Subobject, *Field,
3044 &Layout);
Richard Smithd62306a2011-11-10 06:34:14 +00003045 if (!EvaluateConstantExpression(
3046 Result.getStructField((*Field)->getFieldIndex()),
3047 Info, Subobject, E->getInit(ElementNo++)))
3048 return false;
3049 } else {
3050 // Perform an implicit value-initialization for members beyond the end of
3051 // the initializer list.
Richard Smitha8105bc2012-01-06 16:39:00 +00003052 HandleLValueMember(Info, E, Subobject, *Field, &Layout);
Richard Smithd62306a2011-11-10 06:34:14 +00003053 ImplicitValueInitExpr VIE(Field->getType());
3054 if (!EvaluateConstantExpression(
3055 Result.getStructField((*Field)->getFieldIndex()),
3056 Info, Subobject, &VIE))
3057 return false;
3058 }
3059 }
3060
3061 return true;
3062}
3063
3064bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3065 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithfddd3842011-12-30 21:15:51 +00003066 bool ZeroInit = E->requiresZeroInitialization();
3067 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
3068 if (ZeroInit)
3069 return ZeroInitialization(E);
3070
Richard Smithcc36f692011-12-22 02:22:31 +00003071 const CXXRecordDecl *RD = FD->getParent();
3072 if (RD->isUnion())
3073 Result = APValue((FieldDecl*)0);
3074 else
3075 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3076 std::distance(RD->field_begin(), RD->field_end()));
3077 return true;
3078 }
3079
Richard Smithd62306a2011-11-10 06:34:14 +00003080 const FunctionDecl *Definition = 0;
3081 FD->getBody(Definition);
3082
Richard Smith357362d2011-12-13 06:39:58 +00003083 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3084 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003085
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003086 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00003087 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00003088 if (const MaterializeTemporaryExpr *ME
3089 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3090 return Visit(ME->GetTemporaryExpr());
3091
Richard Smithfddd3842011-12-30 21:15:51 +00003092 if (ZeroInit && !ZeroInitialization(E))
3093 return false;
3094
Richard Smithd62306a2011-11-10 06:34:14 +00003095 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003096 return HandleConstructorCall(E, This, Args,
3097 cast<CXXConstructorDecl>(Definition), Info,
3098 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00003099}
3100
3101static bool EvaluateRecord(const Expr *E, const LValue &This,
3102 APValue &Result, EvalInfo &Info) {
3103 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00003104 "can't evaluate expression as a record rvalue");
3105 return RecordExprEvaluator(Info, This, Result).Visit(E);
3106}
3107
3108//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003109// Temporary Evaluation
3110//
3111// Temporaries are represented in the AST as rvalues, but generally behave like
3112// lvalues. The full-object of which the temporary is a subobject is implicitly
3113// materialized so that a reference can bind to it.
3114//===----------------------------------------------------------------------===//
3115namespace {
3116class TemporaryExprEvaluator
3117 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3118public:
3119 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3120 LValueExprEvaluatorBaseTy(Info, Result) {}
3121
3122 /// Visit an expression which constructs the value of this temporary.
3123 bool VisitConstructExpr(const Expr *E) {
3124 Result.set(E, Info.CurrentCall);
3125 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
3126 Result, E);
3127 }
3128
3129 bool VisitCastExpr(const CastExpr *E) {
3130 switch (E->getCastKind()) {
3131 default:
3132 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3133
3134 case CK_ConstructorConversion:
3135 return VisitConstructExpr(E->getSubExpr());
3136 }
3137 }
3138 bool VisitInitListExpr(const InitListExpr *E) {
3139 return VisitConstructExpr(E);
3140 }
3141 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3142 return VisitConstructExpr(E);
3143 }
3144 bool VisitCallExpr(const CallExpr *E) {
3145 return VisitConstructExpr(E);
3146 }
3147};
3148} // end anonymous namespace
3149
3150/// Evaluate an expression of record type as a temporary.
3151static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00003152 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00003153 return TemporaryExprEvaluator(Info, Result).Visit(E);
3154}
3155
3156//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003157// Vector Evaluation
3158//===----------------------------------------------------------------------===//
3159
3160namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003161 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00003162 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3163 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003164 public:
Mike Stump11289f42009-09-09 15:08:12 +00003165
Richard Smith2d406342011-10-22 21:10:00 +00003166 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3167 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00003168
Richard Smith2d406342011-10-22 21:10:00 +00003169 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3170 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3171 // FIXME: remove this APValue copy.
3172 Result = APValue(V.data(), V.size());
3173 return true;
3174 }
Richard Smithed5165f2011-11-04 05:33:44 +00003175 bool Success(const CCValue &V, const Expr *E) {
3176 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00003177 Result = V;
3178 return true;
3179 }
Richard Smithfddd3842011-12-30 21:15:51 +00003180 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00003181
Richard Smith2d406342011-10-22 21:10:00 +00003182 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00003183 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00003184 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00003185 bool VisitInitListExpr(const InitListExpr *E);
3186 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003187 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00003188 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00003189 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003190 };
3191} // end anonymous namespace
3192
3193static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003194 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00003195 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003196}
3197
Richard Smith2d406342011-10-22 21:10:00 +00003198bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3199 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00003200 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00003201
Richard Smith161f09a2011-12-06 22:44:34 +00003202 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00003203 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003204
Eli Friedmanc757de22011-03-25 00:43:55 +00003205 switch (E->getCastKind()) {
3206 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00003207 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00003208 if (SETy->isIntegerType()) {
3209 APSInt IntResult;
3210 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003211 return false;
Richard Smith2d406342011-10-22 21:10:00 +00003212 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00003213 } else if (SETy->isRealFloatingType()) {
3214 APFloat F(0.0);
3215 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003216 return false;
Richard Smith2d406342011-10-22 21:10:00 +00003217 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00003218 } else {
Richard Smith2d406342011-10-22 21:10:00 +00003219 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003220 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00003221
3222 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00003223 SmallVector<APValue, 4> Elts(NElts, Val);
3224 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00003225 }
Eli Friedman803acb32011-12-22 03:51:45 +00003226 case CK_BitCast: {
3227 // Evaluate the operand into an APInt we can extract from.
3228 llvm::APInt SValInt;
3229 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3230 return false;
3231 // Extract the elements
3232 QualType EltTy = VTy->getElementType();
3233 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3234 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3235 SmallVector<APValue, 4> Elts;
3236 if (EltTy->isRealFloatingType()) {
3237 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3238 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3239 unsigned FloatEltSize = EltSize;
3240 if (&Sem == &APFloat::x87DoubleExtended)
3241 FloatEltSize = 80;
3242 for (unsigned i = 0; i < NElts; i++) {
3243 llvm::APInt Elt;
3244 if (BigEndian)
3245 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3246 else
3247 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3248 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3249 }
3250 } else if (EltTy->isIntegerType()) {
3251 for (unsigned i = 0; i < NElts; i++) {
3252 llvm::APInt Elt;
3253 if (BigEndian)
3254 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3255 else
3256 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3257 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3258 }
3259 } else {
3260 return Error(E);
3261 }
3262 return Success(Elts, E);
3263 }
Eli Friedmanc757de22011-03-25 00:43:55 +00003264 default:
Richard Smith11562c52011-10-28 17:51:58 +00003265 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003266 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003267}
3268
Richard Smith2d406342011-10-22 21:10:00 +00003269bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003270VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00003271 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003272 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00003273 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00003274
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003275 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003276 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003277
Eli Friedmanb9c71292012-01-03 23:24:20 +00003278 // The number of initializers can be less than the number of
3279 // vector elements. For OpenCL, this can be due to nested vector
3280 // initialization. For GCC compatibility, missing trailing elements
3281 // should be initialized with zeroes.
3282 unsigned CountInits = 0, CountElts = 0;
3283 while (CountElts < NumElements) {
3284 // Handle nested vector initialization.
3285 if (CountInits < NumInits
3286 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3287 APValue v;
3288 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3289 return Error(E);
3290 unsigned vlen = v.getVectorLength();
3291 for (unsigned j = 0; j < vlen; j++)
3292 Elements.push_back(v.getVectorElt(j));
3293 CountElts += vlen;
3294 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003295 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00003296 if (CountInits < NumInits) {
3297 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3298 return Error(E);
3299 } else // trailing integer zero.
3300 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3301 Elements.push_back(APValue(sInt));
3302 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003303 } else {
3304 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00003305 if (CountInits < NumInits) {
3306 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3307 return Error(E);
3308 } else // trailing float zero.
3309 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3310 Elements.push_back(APValue(f));
3311 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00003312 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00003313 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003314 }
Richard Smith2d406342011-10-22 21:10:00 +00003315 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003316}
3317
Richard Smith2d406342011-10-22 21:10:00 +00003318bool
Richard Smithfddd3842011-12-30 21:15:51 +00003319VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00003320 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00003321 QualType EltTy = VT->getElementType();
3322 APValue ZeroElement;
3323 if (EltTy->isIntegerType())
3324 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3325 else
3326 ZeroElement =
3327 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3328
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003329 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00003330 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003331}
3332
Richard Smith2d406342011-10-22 21:10:00 +00003333bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00003334 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00003335 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003336}
3337
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003338//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00003339// Array Evaluation
3340//===----------------------------------------------------------------------===//
3341
3342namespace {
3343 class ArrayExprEvaluator
3344 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00003345 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00003346 APValue &Result;
3347 public:
3348
Richard Smithd62306a2011-11-10 06:34:14 +00003349 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3350 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00003351
3352 bool Success(const APValue &V, const Expr *E) {
3353 assert(V.isArray() && "Expected array type");
3354 Result = V;
3355 return true;
3356 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003357
Richard Smithfddd3842011-12-30 21:15:51 +00003358 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003359 const ConstantArrayType *CAT =
3360 Info.Ctx.getAsConstantArrayType(E->getType());
3361 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003362 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003363
3364 Result = APValue(APValue::UninitArray(), 0,
3365 CAT->getSize().getZExtValue());
3366 if (!Result.hasArrayFiller()) return true;
3367
Richard Smithfddd3842011-12-30 21:15:51 +00003368 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00003369 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00003370 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00003371 ImplicitValueInitExpr VIE(CAT->getElementType());
3372 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3373 Subobject, &VIE);
3374 }
3375
Richard Smithf3e9e432011-11-07 09:22:26 +00003376 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00003377 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003378 };
3379} // end anonymous namespace
3380
Richard Smithd62306a2011-11-10 06:34:14 +00003381static bool EvaluateArray(const Expr *E, const LValue &This,
3382 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00003383 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00003384 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003385}
3386
3387bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3388 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3389 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003390 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003391
Richard Smithca2cfbf2011-12-22 01:07:19 +00003392 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3393 // an appropriately-typed string literal enclosed in braces.
3394 if (E->getNumInits() == 1 && CAT->getElementType()->isAnyCharacterType() &&
3395 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3396 LValue LV;
3397 if (!EvaluateLValue(E->getInit(0), LV, Info))
3398 return false;
3399 uint64_t NumElements = CAT->getSize().getZExtValue();
3400 Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3401
3402 // Copy the string literal into the array. FIXME: Do this better.
Richard Smitha8105bc2012-01-06 16:39:00 +00003403 LV.addArray(Info, E, CAT);
Richard Smithca2cfbf2011-12-22 01:07:19 +00003404 for (uint64_t I = 0; I < NumElements; ++I) {
3405 CCValue Char;
3406 if (!HandleLValueToRValueConversion(Info, E->getInit(0),
3407 CAT->getElementType(), LV, Char))
3408 return false;
3409 if (!CheckConstantExpression(Info, E->getInit(0), Char,
3410 Result.getArrayInitializedElt(I)))
3411 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003412 if (!HandleLValueArrayAdjustment(Info, E->getInit(0), LV,
3413 CAT->getElementType(), 1))
Richard Smithca2cfbf2011-12-22 01:07:19 +00003414 return false;
3415 }
3416 return true;
3417 }
3418
Richard Smithf3e9e432011-11-07 09:22:26 +00003419 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3420 CAT->getSize().getZExtValue());
Richard Smithd62306a2011-11-10 06:34:14 +00003421 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00003422 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00003423 unsigned Index = 0;
Richard Smithf3e9e432011-11-07 09:22:26 +00003424 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smithd62306a2011-11-10 06:34:14 +00003425 I != End; ++I, ++Index) {
3426 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
3427 Info, Subobject, cast<Expr>(*I)))
Richard Smithf3e9e432011-11-07 09:22:26 +00003428 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003429 if (!HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3430 CAT->getElementType(), 1))
Richard Smithd62306a2011-11-10 06:34:14 +00003431 return false;
3432 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003433
3434 if (!Result.hasArrayFiller()) return true;
3435 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smithd62306a2011-11-10 06:34:14 +00003436 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3437 // but sometimes does:
3438 // struct S { constexpr S() : p(&p) {} void *p; };
3439 // S s[10] = {};
Richard Smithf3e9e432011-11-07 09:22:26 +00003440 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smithd62306a2011-11-10 06:34:14 +00003441 Subobject, E->getArrayFiller());
Richard Smithf3e9e432011-11-07 09:22:26 +00003442}
3443
Richard Smith027bf112011-11-17 22:56:20 +00003444bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3445 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3446 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003447 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003448
3449 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3450 if (!Result.hasArrayFiller())
3451 return true;
3452
3453 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00003454
Richard Smithfddd3842011-12-30 21:15:51 +00003455 bool ZeroInit = E->requiresZeroInitialization();
3456 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
3457 if (ZeroInit) {
3458 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00003459 Subobject.addArray(Info, E, CAT);
Richard Smithfddd3842011-12-30 21:15:51 +00003460 ImplicitValueInitExpr VIE(CAT->getElementType());
3461 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3462 Subobject, &VIE);
3463 }
3464
Richard Smithcc36f692011-12-22 02:22:31 +00003465 const CXXRecordDecl *RD = FD->getParent();
3466 if (RD->isUnion())
3467 Result.getArrayFiller() = APValue((FieldDecl*)0);
3468 else
3469 Result.getArrayFiller() =
3470 APValue(APValue::UninitStruct(), RD->getNumBases(),
3471 std::distance(RD->field_begin(), RD->field_end()));
3472 return true;
3473 }
3474
Richard Smith027bf112011-11-17 22:56:20 +00003475 const FunctionDecl *Definition = 0;
3476 FD->getBody(Definition);
3477
Richard Smith357362d2011-12-13 06:39:58 +00003478 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3479 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003480
3481 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3482 // but sometimes does:
3483 // struct S { constexpr S() : p(&p) {} void *p; };
3484 // S s[10];
3485 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00003486 Subobject.addArray(Info, E, CAT);
Richard Smithfddd3842011-12-30 21:15:51 +00003487
3488 if (ZeroInit) {
3489 ImplicitValueInitExpr VIE(CAT->getElementType());
3490 if (!EvaluateConstantExpression(Result.getArrayFiller(), Info, Subobject,
3491 &VIE))
3492 return false;
3493 }
3494
Richard Smith027bf112011-11-17 22:56:20 +00003495 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003496 return HandleConstructorCall(E, Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00003497 cast<CXXConstructorDecl>(Definition),
3498 Info, Result.getArrayFiller());
3499}
3500
Richard Smithf3e9e432011-11-07 09:22:26 +00003501//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003502// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003503//
3504// As a GNU extension, we support casting pointers to sufficiently-wide integer
3505// types and back in constant folding. Integer values are thus represented
3506// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00003507//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003508
3509namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003510class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003511 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003512 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003513public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00003514 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003515 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00003516
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003517 bool Success(const llvm::APSInt &SI, const Expr *E) {
3518 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00003519 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003520 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003521 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003522 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003523 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003524 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003525 return true;
3526 }
3527
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003528 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003529 assert(E->getType()->isIntegralOrEnumerationType() &&
3530 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003531 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003532 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003533 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00003534 Result.getInt().setIsUnsigned(
3535 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003536 return true;
3537 }
3538
3539 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003540 assert(E->getType()->isIntegralOrEnumerationType() &&
3541 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003542 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003543 return true;
3544 }
3545
Ken Dyckdbc01912011-03-11 02:13:43 +00003546 bool Success(CharUnits Size, const Expr *E) {
3547 return Success(Size.getQuantity(), E);
3548 }
3549
Richard Smith0b0a0b62011-10-29 20:57:55 +00003550 bool Success(const CCValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00003551 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00003552 Result = V;
3553 return true;
3554 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003555 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00003556 }
Mike Stump11289f42009-09-09 15:08:12 +00003557
Richard Smithfddd3842011-12-30 21:15:51 +00003558 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00003559
Peter Collingbournee9200682011-05-13 03:29:01 +00003560 //===--------------------------------------------------------------------===//
3561 // Visitor Methods
3562 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003563
Chris Lattner7174bf32008-07-12 00:38:25 +00003564 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003565 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00003566 }
3567 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003568 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00003569 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003570
3571 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3572 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003573 if (CheckReferencedDecl(E, E->getDecl()))
3574 return true;
3575
3576 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003577 }
3578 bool VisitMemberExpr(const MemberExpr *E) {
3579 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00003580 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003581 return true;
3582 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003583
3584 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003585 }
3586
Peter Collingbournee9200682011-05-13 03:29:01 +00003587 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00003588 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00003589 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00003590 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00003591
Peter Collingbournee9200682011-05-13 03:29:01 +00003592 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003593 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00003594
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003595 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003596 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003597 }
Mike Stump11289f42009-09-09 15:08:12 +00003598
Richard Smith4ce706a2011-10-11 21:43:33 +00003599 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00003600 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003601 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003602 }
3603
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003604 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003605 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003606 }
3607
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003608 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3609 return Success(E->getValue(), E);
3610 }
3611
John Wiegley6242b6a2011-04-28 00:16:57 +00003612 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3613 return Success(E->getValue(), E);
3614 }
3615
John Wiegleyf9f65842011-04-25 06:54:41 +00003616 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3617 return Success(E->getValue(), E);
3618 }
3619
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003620 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003621 bool VisitUnaryImag(const UnaryOperator *E);
3622
Sebastian Redl5f0180d2010-09-10 20:55:47 +00003623 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003624 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00003625
Chris Lattnerf8d7f722008-07-11 21:24:13 +00003626private:
Ken Dyck160146e2010-01-27 17:10:57 +00003627 CharUnits GetAlignOfExpr(const Expr *E);
3628 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00003629 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00003630 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003631 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00003632};
Chris Lattner05706e882008-07-11 18:11:29 +00003633} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003634
Richard Smith11562c52011-10-28 17:51:58 +00003635/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3636/// produce either the integer value or a pointer.
3637///
3638/// GCC has a heinous extension which folds casts between pointer types and
3639/// pointer-sized integral types. We support this by allowing the evaluation of
3640/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3641/// Some simple arithmetic on such values is supported (they are treated much
3642/// like char*).
Richard Smithf57d8cb2011-12-09 22:58:01 +00003643static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00003644 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003645 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003646 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00003647}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003648
Richard Smithf57d8cb2011-12-09 22:58:01 +00003649static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003650 CCValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003651 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00003652 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003653 if (!Val.isInt()) {
3654 // FIXME: It would be better to produce the diagnostic for casting
3655 // a pointer to an integer.
Richard Smith92b1ce02011-12-12 09:28:41 +00003656 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003657 return false;
3658 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003659 Result = Val.getInt();
3660 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003661}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003662
Richard Smithf57d8cb2011-12-09 22:58:01 +00003663/// Check whether the given declaration can be directly converted to an integral
3664/// rvalue. If not, no diagnostic is produced; there are other things we can
3665/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003666bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00003667 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003668 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003669 // Check for signedness/width mismatches between E type and ECD value.
3670 bool SameSign = (ECD->getInitVal().isSigned()
3671 == E->getType()->isSignedIntegerOrEnumerationType());
3672 bool SameWidth = (ECD->getInitVal().getBitWidth()
3673 == Info.Ctx.getIntWidth(E->getType()));
3674 if (SameSign && SameWidth)
3675 return Success(ECD->getInitVal(), E);
3676 else {
3677 // Get rid of mismatch (otherwise Success assertions will fail)
3678 // by computing a new value matching the type of E.
3679 llvm::APSInt Val = ECD->getInitVal();
3680 if (!SameSign)
3681 Val.setIsSigned(!ECD->getInitVal().isSigned());
3682 if (!SameWidth)
3683 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3684 return Success(Val, E);
3685 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003686 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003687 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00003688}
3689
Chris Lattner86ee2862008-10-06 06:40:35 +00003690/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3691/// as GCC.
3692static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3693 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003694 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00003695 enum gcc_type_class {
3696 no_type_class = -1,
3697 void_type_class, integer_type_class, char_type_class,
3698 enumeral_type_class, boolean_type_class,
3699 pointer_type_class, reference_type_class, offset_type_class,
3700 real_type_class, complex_type_class,
3701 function_type_class, method_type_class,
3702 record_type_class, union_type_class,
3703 array_type_class, string_type_class,
3704 lang_type_class
3705 };
Mike Stump11289f42009-09-09 15:08:12 +00003706
3707 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00003708 // ideal, however it is what gcc does.
3709 if (E->getNumArgs() == 0)
3710 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00003711
Chris Lattner86ee2862008-10-06 06:40:35 +00003712 QualType ArgTy = E->getArg(0)->getType();
3713 if (ArgTy->isVoidType())
3714 return void_type_class;
3715 else if (ArgTy->isEnumeralType())
3716 return enumeral_type_class;
3717 else if (ArgTy->isBooleanType())
3718 return boolean_type_class;
3719 else if (ArgTy->isCharType())
3720 return string_type_class; // gcc doesn't appear to use char_type_class
3721 else if (ArgTy->isIntegerType())
3722 return integer_type_class;
3723 else if (ArgTy->isPointerType())
3724 return pointer_type_class;
3725 else if (ArgTy->isReferenceType())
3726 return reference_type_class;
3727 else if (ArgTy->isRealType())
3728 return real_type_class;
3729 else if (ArgTy->isComplexType())
3730 return complex_type_class;
3731 else if (ArgTy->isFunctionType())
3732 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00003733 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00003734 return record_type_class;
3735 else if (ArgTy->isUnionType())
3736 return union_type_class;
3737 else if (ArgTy->isArrayType())
3738 return array_type_class;
3739 else if (ArgTy->isUnionType())
3740 return union_type_class;
3741 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00003742 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00003743 return -1;
3744}
3745
Richard Smith5fab0c92011-12-28 19:48:30 +00003746/// EvaluateBuiltinConstantPForLValue - Determine the result of
3747/// __builtin_constant_p when applied to the given lvalue.
3748///
3749/// An lvalue is only "constant" if it is a pointer or reference to the first
3750/// character of a string literal.
3751template<typename LValue>
3752static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
3753 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
3754 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3755}
3756
3757/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
3758/// GCC as we can manage.
3759static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
3760 QualType ArgType = Arg->getType();
3761
3762 // __builtin_constant_p always has one operand. The rules which gcc follows
3763 // are not precisely documented, but are as follows:
3764 //
3765 // - If the operand is of integral, floating, complex or enumeration type,
3766 // and can be folded to a known value of that type, it returns 1.
3767 // - If the operand and can be folded to a pointer to the first character
3768 // of a string literal (or such a pointer cast to an integral type), it
3769 // returns 1.
3770 //
3771 // Otherwise, it returns 0.
3772 //
3773 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3774 // its support for this does not currently work.
3775 if (ArgType->isIntegralOrEnumerationType()) {
3776 Expr::EvalResult Result;
3777 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
3778 return false;
3779
3780 APValue &V = Result.Val;
3781 if (V.getKind() == APValue::Int)
3782 return true;
3783
3784 return EvaluateBuiltinConstantPForLValue(V);
3785 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3786 return Arg->isEvaluatable(Ctx);
3787 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3788 LValue LV;
3789 Expr::EvalStatus Status;
3790 EvalInfo Info(Ctx, Status);
3791 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
3792 : EvaluatePointer(Arg, LV, Info)) &&
3793 !Status.HasSideEffects)
3794 return EvaluateBuiltinConstantPForLValue(LV);
3795 }
3796
3797 // Anything else isn't considered to be sufficiently constant.
3798 return false;
3799}
3800
John McCall95007602010-05-10 23:27:23 +00003801/// Retrieves the "underlying object type" of the given expression,
3802/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00003803QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3804 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3805 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00003806 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00003807 } else if (const Expr *E = B.get<const Expr*>()) {
3808 if (isa<CompoundLiteralExpr>(E))
3809 return E->getType();
John McCall95007602010-05-10 23:27:23 +00003810 }
3811
3812 return QualType();
3813}
3814
Peter Collingbournee9200682011-05-13 03:29:01 +00003815bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00003816 // TODO: Perhaps we should let LLVM lower this?
3817 LValue Base;
3818 if (!EvaluatePointer(E->getArg(0), Base, Info))
3819 return false;
3820
3821 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00003822 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00003823
Richard Smithce40ad62011-11-12 22:28:03 +00003824 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00003825 if (T.isNull() ||
3826 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00003827 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00003828 T->isVariablyModifiedType() ||
3829 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003830 return Error(E);
John McCall95007602010-05-10 23:27:23 +00003831
3832 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3833 CharUnits Offset = Base.getLValueOffset();
3834
3835 if (!Offset.isNegative() && Offset <= Size)
3836 Size -= Offset;
3837 else
3838 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00003839 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00003840}
3841
Peter Collingbournee9200682011-05-13 03:29:01 +00003842bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003843 switch (E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003844 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00003845 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003846
3847 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00003848 if (TryEvaluateBuiltinObjectSize(E))
3849 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00003850
Eric Christopher99469702010-01-19 22:58:35 +00003851 // If evaluating the argument has side-effects we can't determine
3852 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003853 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00003854 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00003855 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00003856 return Success(0, E);
3857 }
Mike Stump876387b2009-10-27 22:09:17 +00003858
Richard Smithf57d8cb2011-12-09 22:58:01 +00003859 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003860 }
3861
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003862 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003863 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00003864
Richard Smith5fab0c92011-12-28 19:48:30 +00003865 case Builtin::BI__builtin_constant_p:
3866 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smith10c7c902011-12-09 02:04:48 +00003867
Chris Lattnerd545ad12009-09-23 06:06:36 +00003868 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00003869 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00003870 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00003871 return Success(Operand, E);
3872 }
Eli Friedmand5c93992010-02-13 00:10:10 +00003873
3874 case Builtin::BI__builtin_expect:
3875 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003876
3877 case Builtin::BIstrlen:
3878 case Builtin::BI__builtin_strlen:
3879 // As an extension, we support strlen() and __builtin_strlen() as constant
3880 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00003881 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003882 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
3883 // The string literal may have embedded null characters. Find the first
3884 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003885 StringRef Str = S->getString();
3886 StringRef::size_type Pos = Str.find(0);
3887 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003888 Str = Str.substr(0, Pos);
3889
3890 return Success(Str.size(), E);
3891 }
3892
Richard Smithf57d8cb2011-12-09 22:58:01 +00003893 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003894
3895 case Builtin::BI__atomic_is_lock_free: {
3896 APSInt SizeVal;
3897 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
3898 return false;
3899
3900 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
3901 // of two less than the maximum inline atomic width, we know it is
3902 // lock-free. If the size isn't a power of two, or greater than the
3903 // maximum alignment where we promote atomics, we know it is not lock-free
3904 // (at least not in the sense of atomic_is_lock_free). Otherwise,
3905 // the answer can only be determined at runtime; for example, 16-byte
3906 // atomics have lock-free implementations on some, but not all,
3907 // x86-64 processors.
3908
3909 // Check power-of-two.
3910 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
3911 if (!Size.isPowerOfTwo())
3912#if 0
3913 // FIXME: Suppress this folding until the ABI for the promotion width
3914 // settles.
3915 return Success(0, E);
3916#else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003917 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003918#endif
3919
3920#if 0
3921 // Check against promotion width.
3922 // FIXME: Suppress this folding until the ABI for the promotion width
3923 // settles.
3924 unsigned PromoteWidthBits =
3925 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
3926 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
3927 return Success(0, E);
3928#endif
3929
3930 // Check against inlining width.
3931 unsigned InlineWidthBits =
3932 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
3933 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
3934 return Success(1, E);
3935
Richard Smithf57d8cb2011-12-09 22:58:01 +00003936 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003937 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003938 }
Chris Lattner7174bf32008-07-12 00:38:25 +00003939}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003940
Richard Smith8b3497e2011-10-31 01:37:14 +00003941static bool HasSameBase(const LValue &A, const LValue &B) {
3942 if (!A.getLValueBase())
3943 return !B.getLValueBase();
3944 if (!B.getLValueBase())
3945 return false;
3946
Richard Smithce40ad62011-11-12 22:28:03 +00003947 if (A.getLValueBase().getOpaqueValue() !=
3948 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003949 const Decl *ADecl = GetLValueBaseDecl(A);
3950 if (!ADecl)
3951 return false;
3952 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00003953 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00003954 return false;
3955 }
3956
3957 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithfec09922011-11-01 16:57:24 +00003958 A.getLValueFrame() == B.getLValueFrame();
Richard Smith8b3497e2011-10-31 01:37:14 +00003959}
3960
Chris Lattnere13042c2008-07-11 19:10:17 +00003961bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003962 if (E->isAssignmentOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003963 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003964
John McCalle3027922010-08-25 11:45:40 +00003965 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00003966 VisitIgnoredValue(E->getLHS());
3967 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00003968 }
3969
3970 if (E->isLogicalOp()) {
3971 // These need to be handled specially because the operands aren't
3972 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003973 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00003974
Richard Smith11562c52011-10-28 17:51:58 +00003975 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00003976 // We were able to evaluate the LHS, see if we can get away with not
3977 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00003978 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003979 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003980
Richard Smith11562c52011-10-28 17:51:58 +00003981 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00003982 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003983 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003984 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003985 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003986 }
3987 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003988 // FIXME: If both evaluations fail, we should produce the diagnostic from
3989 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
3990 // less clear how to diagnose this.
Richard Smith11562c52011-10-28 17:51:58 +00003991 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00003992 // We can't evaluate the LHS; however, sometimes the result
3993 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003994 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003995 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003996 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00003997 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003998
3999 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00004000 }
4001 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00004002 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00004003
Eli Friedman5a332ea2008-11-13 06:09:17 +00004004 return false;
4005 }
4006
Anders Carlssonacc79812008-11-16 07:17:21 +00004007 QualType LHSTy = E->getLHS()->getType();
4008 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004009
4010 if (LHSTy->isAnyComplexType()) {
4011 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00004012 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004013
4014 if (!EvaluateComplex(E->getLHS(), LHS, Info))
4015 return false;
4016
4017 if (!EvaluateComplex(E->getRHS(), RHS, Info))
4018 return false;
4019
4020 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00004021 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004022 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00004023 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004024 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4025
John McCalle3027922010-08-25 11:45:40 +00004026 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004027 return Success((CR_r == APFloat::cmpEqual &&
4028 CR_i == APFloat::cmpEqual), E);
4029 else {
John McCalle3027922010-08-25 11:45:40 +00004030 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004031 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00004032 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00004033 CR_r == APFloat::cmpLessThan ||
4034 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00004035 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00004036 CR_i == APFloat::cmpLessThan ||
4037 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004038 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004039 } else {
John McCalle3027922010-08-25 11:45:40 +00004040 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004041 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4042 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4043 else {
John McCalle3027922010-08-25 11:45:40 +00004044 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004045 "Invalid compex comparison.");
4046 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4047 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4048 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004049 }
4050 }
Mike Stump11289f42009-09-09 15:08:12 +00004051
Anders Carlssonacc79812008-11-16 07:17:21 +00004052 if (LHSTy->isRealFloatingType() &&
4053 RHSTy->isRealFloatingType()) {
4054 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00004055
Anders Carlssonacc79812008-11-16 07:17:21 +00004056 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4057 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004058
Anders Carlssonacc79812008-11-16 07:17:21 +00004059 if (!EvaluateFloat(E->getLHS(), LHS, Info))
4060 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004061
Anders Carlssonacc79812008-11-16 07:17:21 +00004062 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00004063
Anders Carlssonacc79812008-11-16 07:17:21 +00004064 switch (E->getOpcode()) {
4065 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004066 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00004067 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004068 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00004069 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004070 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00004071 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004072 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00004073 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00004074 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004075 E);
John McCalle3027922010-08-25 11:45:40 +00004076 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004077 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00004078 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00004079 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00004080 || CR == APFloat::cmpLessThan
4081 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00004082 }
Anders Carlssonacc79812008-11-16 07:17:21 +00004083 }
Mike Stump11289f42009-09-09 15:08:12 +00004084
Eli Friedmana38da572009-04-28 19:17:36 +00004085 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00004086 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCall45d55e42010-05-07 21:00:08 +00004087 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004088 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
4089 return false;
Eli Friedman64004332009-03-23 04:38:34 +00004090
John McCall45d55e42010-05-07 21:00:08 +00004091 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004092 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
4093 return false;
Eli Friedman64004332009-03-23 04:38:34 +00004094
Richard Smith8b3497e2011-10-31 01:37:14 +00004095 // Reject differing bases from the normal codepath; we special-case
4096 // comparisons to null.
4097 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004098 if (E->getOpcode() == BO_Sub) {
4099 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004100 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4101 return false;
4102 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4103 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4104 if (!LHSExpr || !RHSExpr)
4105 return false;
4106 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4107 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4108 if (!LHSAddrExpr || !RHSAddrExpr)
4109 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00004110 // Make sure both labels come from the same function.
4111 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4112 RHSAddrExpr->getLabel()->getDeclContext())
4113 return false;
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004114 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4115 return true;
4116 }
Richard Smith83c68212011-10-31 05:11:32 +00004117 // Inequalities and subtractions between unrelated pointers have
4118 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00004119 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004120 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00004121 // A constant address may compare equal to the address of a symbol.
4122 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00004123 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00004124 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4125 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004126 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00004127 // It's implementation-defined whether distinct literals will have
Eli Friedman42fbd622011-10-31 22:54:30 +00004128 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smithe9e20dd32011-11-04 01:10:57 +00004129 // distinct. However, we do know that the address of a literal will be
4130 // non-null.
4131 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4132 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004133 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00004134 // We can't tell whether weak symbols will end up pointing to the same
4135 // object.
4136 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004137 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00004138 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00004139 // (Note that clang defaults to -fmerge-all-constants, which can
4140 // lead to inconsistent results for comparisons involving the address
4141 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00004142 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00004143 }
Eli Friedman64004332009-03-23 04:38:34 +00004144
Richard Smithf3e9e432011-11-07 09:22:26 +00004145 // FIXME: Implement the C++11 restrictions:
4146 // - Pointer subtractions must be on elements of the same array.
4147 // - Pointer comparisons must be between members with the same access.
4148
John McCalle3027922010-08-25 11:45:40 +00004149 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00004150 QualType Type = E->getLHS()->getType();
4151 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004152
Richard Smithd62306a2011-11-10 06:34:14 +00004153 CharUnits ElementSize;
4154 if (!HandleSizeof(Info, ElementType, ElementSize))
4155 return false;
Eli Friedman64004332009-03-23 04:38:34 +00004156
Richard Smithd62306a2011-11-10 06:34:14 +00004157 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dyck02990832010-01-15 12:37:54 +00004158 RHSValue.getLValueOffset();
4159 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00004160 }
Richard Smith8b3497e2011-10-31 01:37:14 +00004161
4162 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4163 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4164 switch (E->getOpcode()) {
4165 default: llvm_unreachable("missing comparison operator");
4166 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4167 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4168 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4169 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4170 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4171 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmana38da572009-04-28 19:17:36 +00004172 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004173 }
4174 }
Douglas Gregorb90df602010-06-16 00:17:44 +00004175 if (!LHSTy->isIntegralOrEnumerationType() ||
4176 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smith027bf112011-11-17 22:56:20 +00004177 // We can't continue from here for non-integral types.
4178 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004179 }
4180
Anders Carlsson9c181652008-07-08 14:35:21 +00004181 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00004182 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00004183 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004184 return false;
Eli Friedmanbd840592008-07-27 05:46:18 +00004185
Richard Smith11562c52011-10-28 17:51:58 +00004186 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004187 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004188 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00004189
4190 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00004191 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00004192 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4193 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00004194 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00004195 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00004196 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00004197 LHSVal.getLValueOffset() -= AdditionalOffset;
4198 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00004199 return true;
4200 }
4201
4202 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00004203 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00004204 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004205 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4206 LHSVal.getInt().getZExtValue());
4207 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00004208 return true;
4209 }
4210
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004211 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4212 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004213 if (!LHSVal.getLValueOffset().isZero() ||
4214 !RHSVal.getLValueOffset().isZero())
4215 return false;
4216 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4217 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4218 if (!LHSExpr || !RHSExpr)
4219 return false;
4220 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4221 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4222 if (!LHSAddrExpr || !RHSAddrExpr)
4223 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00004224 // Make sure both labels come from the same function.
4225 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4226 RHSAddrExpr->getLabel()->getDeclContext())
4227 return false;
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004228 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4229 return true;
4230 }
4231
Eli Friedman94c25c62009-03-24 01:14:50 +00004232 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00004233 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004234 return Error(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004235
Richard Smith11562c52011-10-28 17:51:58 +00004236 APSInt &LHS = LHSVal.getInt();
4237 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00004238
Anders Carlsson9c181652008-07-08 14:35:21 +00004239 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00004240 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004241 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004242 case BO_Mul: return Success(LHS * RHS, E);
4243 case BO_Add: return Success(LHS + RHS, E);
4244 case BO_Sub: return Success(LHS - RHS, E);
4245 case BO_And: return Success(LHS & RHS, E);
4246 case BO_Xor: return Success(LHS ^ RHS, E);
4247 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00004248 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00004249 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004250 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00004251 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00004252 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00004253 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004254 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00004255 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00004256 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00004257 // During constant-folding, a negative shift is an opposite shift.
4258 if (RHS.isSigned() && RHS.isNegative()) {
4259 RHS = -RHS;
4260 goto shift_right;
4261 }
4262
4263 shift_left:
4264 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00004265 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4266 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004267 }
John McCalle3027922010-08-25 11:45:40 +00004268 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00004269 // During constant-folding, a negative shift is an opposite shift.
4270 if (RHS.isSigned() && RHS.isNegative()) {
4271 RHS = -RHS;
4272 goto shift_left;
4273 }
4274
4275 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00004276 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00004277 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4278 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004279 }
Mike Stump11289f42009-09-09 15:08:12 +00004280
Richard Smith11562c52011-10-28 17:51:58 +00004281 case BO_LT: return Success(LHS < RHS, E);
4282 case BO_GT: return Success(LHS > RHS, E);
4283 case BO_LE: return Success(LHS <= RHS, E);
4284 case BO_GE: return Success(LHS >= RHS, E);
4285 case BO_EQ: return Success(LHS == RHS, E);
4286 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00004287 }
Anders Carlsson9c181652008-07-08 14:35:21 +00004288}
4289
Ken Dyck160146e2010-01-27 17:10:57 +00004290CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00004291 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4292 // the result is the size of the referenced type."
4293 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4294 // result shall be the alignment of the referenced type."
4295 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4296 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00004297
4298 // __alignof is defined to return the preferred alignment.
4299 return Info.Ctx.toCharUnitsFromBits(
4300 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00004301}
4302
Ken Dyck160146e2010-01-27 17:10:57 +00004303CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00004304 E = E->IgnoreParens();
4305
4306 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00004307 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00004308 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00004309 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4310 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00004311
Chris Lattner68061312009-01-24 21:53:27 +00004312 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00004313 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4314 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00004315
Chris Lattner24aeeab2009-01-24 21:09:06 +00004316 return GetAlignOfType(E->getType());
4317}
4318
4319
Peter Collingbournee190dee2011-03-11 19:24:49 +00004320/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4321/// a result as the expression's type.
4322bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4323 const UnaryExprOrTypeTraitExpr *E) {
4324 switch(E->getKind()) {
4325 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00004326 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00004327 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00004328 else
Ken Dyckdbc01912011-03-11 02:13:43 +00004329 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00004330 }
Eli Friedman64004332009-03-23 04:38:34 +00004331
Peter Collingbournee190dee2011-03-11 19:24:49 +00004332 case UETT_VecStep: {
4333 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00004334
Peter Collingbournee190dee2011-03-11 19:24:49 +00004335 if (Ty->isVectorType()) {
4336 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00004337
Peter Collingbournee190dee2011-03-11 19:24:49 +00004338 // The vec_step built-in functions that take a 3-component
4339 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4340 if (n == 3)
4341 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00004342
Peter Collingbournee190dee2011-03-11 19:24:49 +00004343 return Success(n, E);
4344 } else
4345 return Success(1, E);
4346 }
4347
4348 case UETT_SizeOf: {
4349 QualType SrcTy = E->getTypeOfArgument();
4350 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4351 // the result is the size of the referenced type."
4352 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4353 // result shall be the alignment of the referenced type."
4354 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4355 SrcTy = Ref->getPointeeType();
4356
Richard Smithd62306a2011-11-10 06:34:14 +00004357 CharUnits Sizeof;
4358 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00004359 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004360 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00004361 }
4362 }
4363
4364 llvm_unreachable("unknown expr/type trait");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004365 return Error(E);
Chris Lattnerf8d7f722008-07-11 21:24:13 +00004366}
4367
Peter Collingbournee9200682011-05-13 03:29:01 +00004368bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00004369 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00004370 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00004371 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004372 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00004373 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00004374 for (unsigned i = 0; i != n; ++i) {
4375 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4376 switch (ON.getKind()) {
4377 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00004378 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00004379 APSInt IdxResult;
4380 if (!EvaluateInteger(Idx, IdxResult, Info))
4381 return false;
4382 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4383 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004384 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004385 CurrentType = AT->getElementType();
4386 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4387 Result += IdxResult.getSExtValue() * ElementSize;
4388 break;
4389 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00004390
Douglas Gregor882211c2010-04-28 22:16:22 +00004391 case OffsetOfExpr::OffsetOfNode::Field: {
4392 FieldDecl *MemberDecl = ON.getField();
4393 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00004394 if (!RT)
4395 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004396 RecordDecl *RD = RT->getDecl();
4397 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00004398 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00004399 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00004400 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00004401 CurrentType = MemberDecl->getType().getNonReferenceType();
4402 break;
4403 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00004404
Douglas Gregor882211c2010-04-28 22:16:22 +00004405 case OffsetOfExpr::OffsetOfNode::Identifier:
4406 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004407 return Error(OOE);
4408
Douglas Gregord1702062010-04-29 00:18:15 +00004409 case OffsetOfExpr::OffsetOfNode::Base: {
4410 CXXBaseSpecifier *BaseSpec = ON.getBase();
4411 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004412 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004413
4414 // Find the layout of the class whose base we are looking into.
4415 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00004416 if (!RT)
4417 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004418 RecordDecl *RD = RT->getDecl();
4419 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4420
4421 // Find the base class itself.
4422 CurrentType = BaseSpec->getType();
4423 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4424 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004425 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004426
4427 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00004428 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00004429 break;
4430 }
Douglas Gregor882211c2010-04-28 22:16:22 +00004431 }
4432 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004433 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004434}
4435
Chris Lattnere13042c2008-07-11 19:10:17 +00004436bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004437 switch (E->getOpcode()) {
4438 default:
4439 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4440 // See C99 6.6p3.
4441 return Error(E);
4442 case UO_Extension:
4443 // FIXME: Should extension allow i-c-e extension expressions in its scope?
4444 // If so, we could clear the diagnostic ID.
4445 return Visit(E->getSubExpr());
4446 case UO_Plus:
4447 // The result is just the value.
4448 return Visit(E->getSubExpr());
4449 case UO_Minus: {
4450 if (!Visit(E->getSubExpr()))
4451 return false;
4452 if (!Result.isInt()) return Error(E);
4453 return Success(-Result.getInt(), E);
4454 }
4455 case UO_Not: {
4456 if (!Visit(E->getSubExpr()))
4457 return false;
4458 if (!Result.isInt()) return Error(E);
4459 return Success(~Result.getInt(), E);
4460 }
4461 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00004462 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00004463 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00004464 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004465 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004466 }
Anders Carlsson9c181652008-07-08 14:35:21 +00004467 }
Anders Carlsson9c181652008-07-08 14:35:21 +00004468}
Mike Stump11289f42009-09-09 15:08:12 +00004469
Chris Lattner477c4be2008-07-12 01:15:53 +00004470/// HandleCast - This is used to evaluate implicit or explicit casts where the
4471/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00004472bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4473 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00004474 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00004475 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00004476
Eli Friedmanc757de22011-03-25 00:43:55 +00004477 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00004478 case CK_BaseToDerived:
4479 case CK_DerivedToBase:
4480 case CK_UncheckedDerivedToBase:
4481 case CK_Dynamic:
4482 case CK_ToUnion:
4483 case CK_ArrayToPointerDecay:
4484 case CK_FunctionToPointerDecay:
4485 case CK_NullToPointer:
4486 case CK_NullToMemberPointer:
4487 case CK_BaseToDerivedMemberPointer:
4488 case CK_DerivedToBaseMemberPointer:
4489 case CK_ConstructorConversion:
4490 case CK_IntegralToPointer:
4491 case CK_ToVoid:
4492 case CK_VectorSplat:
4493 case CK_IntegralToFloating:
4494 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00004495 case CK_CPointerToObjCPointerCast:
4496 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00004497 case CK_AnyPointerToBlockPointerCast:
4498 case CK_ObjCObjectLValueCast:
4499 case CK_FloatingRealToComplex:
4500 case CK_FloatingComplexToReal:
4501 case CK_FloatingComplexCast:
4502 case CK_FloatingComplexToIntegralComplex:
4503 case CK_IntegralRealToComplex:
4504 case CK_IntegralComplexCast:
4505 case CK_IntegralComplexToFloatingComplex:
4506 llvm_unreachable("invalid cast kind for integral value");
4507
Eli Friedman9faf2f92011-03-25 19:07:11 +00004508 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00004509 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004510 case CK_LValueBitCast:
4511 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00004512 case CK_ARCProduceObject:
4513 case CK_ARCConsumeObject:
4514 case CK_ARCReclaimReturnedObject:
4515 case CK_ARCExtendBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004516 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004517
4518 case CK_LValueToRValue:
4519 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004520 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004521
4522 case CK_MemberPointerToBoolean:
4523 case CK_PointerToBoolean:
4524 case CK_IntegralToBoolean:
4525 case CK_FloatingToBoolean:
4526 case CK_FloatingComplexToBoolean:
4527 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004528 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00004529 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00004530 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004531 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004532 }
4533
Eli Friedmanc757de22011-03-25 00:43:55 +00004534 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00004535 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00004536 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00004537
Eli Friedman742421e2009-02-20 01:15:07 +00004538 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004539 // Allow casts of address-of-label differences if they are no-ops
4540 // or narrowing. (The narrowing case isn't actually guaranteed to
4541 // be constant-evaluatable except in some narrow cases which are hard
4542 // to detect here. We let it through on the assumption the user knows
4543 // what they are doing.)
4544 if (Result.isAddrLabelDiff())
4545 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00004546 // Only allow casts of lvalues if they are lossless.
4547 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
4548 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004549
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004550 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004551 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00004552 }
Mike Stump11289f42009-09-09 15:08:12 +00004553
Eli Friedmanc757de22011-03-25 00:43:55 +00004554 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004555 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4556
John McCall45d55e42010-05-07 21:00:08 +00004557 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00004558 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00004559 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00004560
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004561 if (LV.getLValueBase()) {
4562 // Only allow based lvalue casts if they are lossless.
4563 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004564 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004565
Richard Smithcf74da72011-11-16 07:18:12 +00004566 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004567 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004568 return true;
4569 }
4570
Ken Dyck02990832010-01-15 12:37:54 +00004571 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
4572 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004573 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004574 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004575
Eli Friedmanc757de22011-03-25 00:43:55 +00004576 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00004577 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00004578 if (!EvaluateComplex(SubExpr, C, Info))
4579 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00004580 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00004581 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00004582
Eli Friedmanc757de22011-03-25 00:43:55 +00004583 case CK_FloatingToIntegral: {
4584 APFloat F(0.0);
4585 if (!EvaluateFloat(SubExpr, F, Info))
4586 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00004587
Richard Smith357362d2011-12-13 06:39:58 +00004588 APSInt Value;
4589 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
4590 return false;
4591 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004592 }
4593 }
Mike Stump11289f42009-09-09 15:08:12 +00004594
Eli Friedmanc757de22011-03-25 00:43:55 +00004595 llvm_unreachable("unknown cast resulting in integral value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004596 return Error(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00004597}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004598
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004599bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4600 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00004601 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004602 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4603 return false;
4604 if (!LV.isComplexInt())
4605 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004606 return Success(LV.getComplexIntReal(), E);
4607 }
4608
4609 return Visit(E->getSubExpr());
4610}
4611
Eli Friedman4e7a2412009-02-27 04:45:43 +00004612bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004613 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00004614 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004615 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4616 return false;
4617 if (!LV.isComplexInt())
4618 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004619 return Success(LV.getComplexIntImag(), E);
4620 }
4621
Richard Smith4a678122011-10-24 18:44:57 +00004622 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00004623 return Success(0, E);
4624}
4625
Douglas Gregor820ba7b2011-01-04 17:33:58 +00004626bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4627 return Success(E->getPackLength(), E);
4628}
4629
Sebastian Redl5f0180d2010-09-10 20:55:47 +00004630bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4631 return Success(E->getValue(), E);
4632}
4633
Chris Lattner05706e882008-07-11 18:11:29 +00004634//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00004635// Float Evaluation
4636//===----------------------------------------------------------------------===//
4637
4638namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004639class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004640 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00004641 APFloat &Result;
4642public:
4643 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004644 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00004645
Richard Smith0b0a0b62011-10-29 20:57:55 +00004646 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004647 Result = V.getFloat();
4648 return true;
4649 }
Eli Friedman24c01542008-08-22 00:06:13 +00004650
Richard Smithfddd3842011-12-30 21:15:51 +00004651 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00004652 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4653 return true;
4654 }
4655
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004656 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00004657
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004658 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00004659 bool VisitBinaryOperator(const BinaryOperator *E);
4660 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004661 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00004662
John McCallb1fb0d32010-05-07 22:08:54 +00004663 bool VisitUnaryReal(const UnaryOperator *E);
4664 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00004665
Richard Smithfddd3842011-12-30 21:15:51 +00004666 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00004667};
4668} // end anonymous namespace
4669
4670static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004671 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004672 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00004673}
4674
Jay Foad39c79802011-01-12 09:06:06 +00004675static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00004676 QualType ResultTy,
4677 const Expr *Arg,
4678 bool SNaN,
4679 llvm::APFloat &Result) {
4680 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4681 if (!S) return false;
4682
4683 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4684
4685 llvm::APInt fill;
4686
4687 // Treat empty strings as if they were zero.
4688 if (S->getString().empty())
4689 fill = llvm::APInt(32, 0);
4690 else if (S->getString().getAsInteger(0, fill))
4691 return false;
4692
4693 if (SNaN)
4694 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
4695 else
4696 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
4697 return true;
4698}
4699
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004700bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004701 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004702 default:
4703 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4704
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004705 case Builtin::BI__builtin_huge_val:
4706 case Builtin::BI__builtin_huge_valf:
4707 case Builtin::BI__builtin_huge_vall:
4708 case Builtin::BI__builtin_inf:
4709 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00004710 case Builtin::BI__builtin_infl: {
4711 const llvm::fltSemantics &Sem =
4712 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00004713 Result = llvm::APFloat::getInf(Sem);
4714 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00004715 }
Mike Stump11289f42009-09-09 15:08:12 +00004716
John McCall16291492010-02-28 13:00:19 +00004717 case Builtin::BI__builtin_nans:
4718 case Builtin::BI__builtin_nansf:
4719 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004720 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4721 true, Result))
4722 return Error(E);
4723 return true;
John McCall16291492010-02-28 13:00:19 +00004724
Chris Lattner0b7282e2008-10-06 06:31:58 +00004725 case Builtin::BI__builtin_nan:
4726 case Builtin::BI__builtin_nanf:
4727 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00004728 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00004729 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004730 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4731 false, Result))
4732 return Error(E);
4733 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004734
4735 case Builtin::BI__builtin_fabs:
4736 case Builtin::BI__builtin_fabsf:
4737 case Builtin::BI__builtin_fabsl:
4738 if (!EvaluateFloat(E->getArg(0), Result, Info))
4739 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004740
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004741 if (Result.isNegative())
4742 Result.changeSign();
4743 return true;
4744
Mike Stump11289f42009-09-09 15:08:12 +00004745 case Builtin::BI__builtin_copysign:
4746 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004747 case Builtin::BI__builtin_copysignl: {
4748 APFloat RHS(0.);
4749 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4750 !EvaluateFloat(E->getArg(1), RHS, Info))
4751 return false;
4752 Result.copySign(RHS);
4753 return true;
4754 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004755 }
4756}
4757
John McCallb1fb0d32010-05-07 22:08:54 +00004758bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004759 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4760 ComplexValue CV;
4761 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4762 return false;
4763 Result = CV.FloatReal;
4764 return true;
4765 }
4766
4767 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00004768}
4769
4770bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004771 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4772 ComplexValue CV;
4773 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4774 return false;
4775 Result = CV.FloatImag;
4776 return true;
4777 }
4778
Richard Smith4a678122011-10-24 18:44:57 +00004779 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00004780 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4781 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00004782 return true;
4783}
4784
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004785bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004786 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004787 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004788 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00004789 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00004790 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00004791 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
4792 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004793 Result.changeSign();
4794 return true;
4795 }
4796}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004797
Eli Friedman24c01542008-08-22 00:06:13 +00004798bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004799 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
4800 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00004801
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004802 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00004803 if (!EvaluateFloat(E->getLHS(), Result, Info))
4804 return false;
4805 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4806 return false;
4807
4808 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004809 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004810 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00004811 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
4812 return true;
John McCalle3027922010-08-25 11:45:40 +00004813 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00004814 Result.add(RHS, APFloat::rmNearestTiesToEven);
4815 return true;
John McCalle3027922010-08-25 11:45:40 +00004816 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00004817 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
4818 return true;
John McCalle3027922010-08-25 11:45:40 +00004819 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00004820 Result.divide(RHS, APFloat::rmNearestTiesToEven);
4821 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00004822 }
4823}
4824
4825bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
4826 Result = E->getValue();
4827 return true;
4828}
4829
Peter Collingbournee9200682011-05-13 03:29:01 +00004830bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4831 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00004832
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004833 switch (E->getCastKind()) {
4834 default:
Richard Smith11562c52011-10-28 17:51:58 +00004835 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004836
4837 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004838 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00004839 return EvaluateInteger(SubExpr, IntResult, Info) &&
4840 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
4841 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00004842 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004843
4844 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004845 if (!Visit(SubExpr))
4846 return false;
Richard Smith357362d2011-12-13 06:39:58 +00004847 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
4848 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00004849 }
John McCalld7646252010-11-14 08:17:51 +00004850
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004851 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00004852 ComplexValue V;
4853 if (!EvaluateComplex(SubExpr, V, Info))
4854 return false;
4855 Result = V.getComplexFloatReal();
4856 return true;
4857 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004858 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004859
Richard Smithf57d8cb2011-12-09 22:58:01 +00004860 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004861}
4862
Eli Friedman24c01542008-08-22 00:06:13 +00004863//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004864// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00004865//===----------------------------------------------------------------------===//
4866
4867namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004868class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004869 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00004870 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00004871
Anders Carlsson537969c2008-11-16 20:27:53 +00004872public:
John McCall93d91dc2010-05-07 17:22:02 +00004873 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004874 : ExprEvaluatorBaseTy(info), Result(Result) {}
4875
Richard Smith0b0a0b62011-10-29 20:57:55 +00004876 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004877 Result.setFrom(V);
4878 return true;
4879 }
Mike Stump11289f42009-09-09 15:08:12 +00004880
Eli Friedmanc4b251d2012-01-10 04:58:17 +00004881 bool ZeroInitialization(const Expr *E);
4882
Anders Carlsson537969c2008-11-16 20:27:53 +00004883 //===--------------------------------------------------------------------===//
4884 // Visitor Methods
4885 //===--------------------------------------------------------------------===//
4886
Peter Collingbournee9200682011-05-13 03:29:01 +00004887 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004888 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00004889 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004890 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00004891 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00004892};
4893} // end anonymous namespace
4894
John McCall93d91dc2010-05-07 17:22:02 +00004895static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
4896 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004897 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004898 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00004899}
4900
Eli Friedmanc4b251d2012-01-10 04:58:17 +00004901bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
4902 QualType ElemTy = cast<ComplexType>(E->getType())->getElementType();
4903 if (ElemTy->isRealFloatingType()) {
4904 Result.makeComplexFloat();
4905 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
4906 Result.FloatReal = Zero;
4907 Result.FloatImag = Zero;
4908 } else {
4909 Result.makeComplexInt();
4910 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
4911 Result.IntReal = Zero;
4912 Result.IntImag = Zero;
4913 }
4914 return true;
4915}
4916
Peter Collingbournee9200682011-05-13 03:29:01 +00004917bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
4918 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004919
4920 if (SubExpr->getType()->isRealFloatingType()) {
4921 Result.makeComplexFloat();
4922 APFloat &Imag = Result.FloatImag;
4923 if (!EvaluateFloat(SubExpr, Imag, Info))
4924 return false;
4925
4926 Result.FloatReal = APFloat(Imag.getSemantics());
4927 return true;
4928 } else {
4929 assert(SubExpr->getType()->isIntegerType() &&
4930 "Unexpected imaginary literal.");
4931
4932 Result.makeComplexInt();
4933 APSInt &Imag = Result.IntImag;
4934 if (!EvaluateInteger(SubExpr, Imag, Info))
4935 return false;
4936
4937 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
4938 return true;
4939 }
4940}
4941
Peter Collingbournee9200682011-05-13 03:29:01 +00004942bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004943
John McCallfcef3cf2010-12-14 17:51:41 +00004944 switch (E->getCastKind()) {
4945 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004946 case CK_BaseToDerived:
4947 case CK_DerivedToBase:
4948 case CK_UncheckedDerivedToBase:
4949 case CK_Dynamic:
4950 case CK_ToUnion:
4951 case CK_ArrayToPointerDecay:
4952 case CK_FunctionToPointerDecay:
4953 case CK_NullToPointer:
4954 case CK_NullToMemberPointer:
4955 case CK_BaseToDerivedMemberPointer:
4956 case CK_DerivedToBaseMemberPointer:
4957 case CK_MemberPointerToBoolean:
4958 case CK_ConstructorConversion:
4959 case CK_IntegralToPointer:
4960 case CK_PointerToIntegral:
4961 case CK_PointerToBoolean:
4962 case CK_ToVoid:
4963 case CK_VectorSplat:
4964 case CK_IntegralCast:
4965 case CK_IntegralToBoolean:
4966 case CK_IntegralToFloating:
4967 case CK_FloatingToIntegral:
4968 case CK_FloatingToBoolean:
4969 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00004970 case CK_CPointerToObjCPointerCast:
4971 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004972 case CK_AnyPointerToBlockPointerCast:
4973 case CK_ObjCObjectLValueCast:
4974 case CK_FloatingComplexToReal:
4975 case CK_FloatingComplexToBoolean:
4976 case CK_IntegralComplexToReal:
4977 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00004978 case CK_ARCProduceObject:
4979 case CK_ARCConsumeObject:
4980 case CK_ARCReclaimReturnedObject:
4981 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00004982 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00004983
John McCallfcef3cf2010-12-14 17:51:41 +00004984 case CK_LValueToRValue:
4985 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004986 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004987
4988 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004989 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004990 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004991 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004992
4993 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004994 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00004995 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004996 return false;
4997
John McCallfcef3cf2010-12-14 17:51:41 +00004998 Result.makeComplexFloat();
4999 Result.FloatImag = APFloat(Real.getSemantics());
5000 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00005001 }
5002
John McCallfcef3cf2010-12-14 17:51:41 +00005003 case CK_FloatingComplexCast: {
5004 if (!Visit(E->getSubExpr()))
5005 return false;
5006
5007 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5008 QualType From
5009 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5010
Richard Smith357362d2011-12-13 06:39:58 +00005011 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5012 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00005013 }
5014
5015 case CK_FloatingComplexToIntegralComplex: {
5016 if (!Visit(E->getSubExpr()))
5017 return false;
5018
5019 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5020 QualType From
5021 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5022 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00005023 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5024 To, Result.IntReal) &&
5025 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5026 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00005027 }
5028
5029 case CK_IntegralRealToComplex: {
5030 APSInt &Real = Result.IntReal;
5031 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5032 return false;
5033
5034 Result.makeComplexInt();
5035 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5036 return true;
5037 }
5038
5039 case CK_IntegralComplexCast: {
5040 if (!Visit(E->getSubExpr()))
5041 return false;
5042
5043 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5044 QualType From
5045 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5046
5047 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
5048 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
5049 return true;
5050 }
5051
5052 case CK_IntegralComplexToFloatingComplex: {
5053 if (!Visit(E->getSubExpr()))
5054 return false;
5055
5056 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5057 QualType From
5058 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5059 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00005060 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5061 To, Result.FloatReal) &&
5062 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5063 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00005064 }
5065 }
5066
5067 llvm_unreachable("unknown cast resulting in complex value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00005068 return Error(E);
Eli Friedmanc3e9df32010-08-16 23:27:44 +00005069}
5070
John McCall93d91dc2010-05-07 17:22:02 +00005071bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005072 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00005073 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5074
John McCall93d91dc2010-05-07 17:22:02 +00005075 if (!Visit(E->getLHS()))
5076 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005077
John McCall93d91dc2010-05-07 17:22:02 +00005078 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00005079 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00005080 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00005081
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005082 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5083 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00005084 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005085 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00005086 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00005087 if (Result.isComplexFloat()) {
5088 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5089 APFloat::rmNearestTiesToEven);
5090 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5091 APFloat::rmNearestTiesToEven);
5092 } else {
5093 Result.getComplexIntReal() += RHS.getComplexIntReal();
5094 Result.getComplexIntImag() += RHS.getComplexIntImag();
5095 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005096 break;
John McCalle3027922010-08-25 11:45:40 +00005097 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00005098 if (Result.isComplexFloat()) {
5099 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5100 APFloat::rmNearestTiesToEven);
5101 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5102 APFloat::rmNearestTiesToEven);
5103 } else {
5104 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5105 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5106 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005107 break;
John McCalle3027922010-08-25 11:45:40 +00005108 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005109 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00005110 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005111 APFloat &LHS_r = LHS.getComplexFloatReal();
5112 APFloat &LHS_i = LHS.getComplexFloatImag();
5113 APFloat &RHS_r = RHS.getComplexFloatReal();
5114 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00005115
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005116 APFloat Tmp = LHS_r;
5117 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5118 Result.getComplexFloatReal() = Tmp;
5119 Tmp = LHS_i;
5120 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5121 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5122
5123 Tmp = LHS_r;
5124 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5125 Result.getComplexFloatImag() = Tmp;
5126 Tmp = LHS_i;
5127 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5128 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5129 } else {
John McCall93d91dc2010-05-07 17:22:02 +00005130 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00005131 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005132 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5133 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00005134 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005135 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5136 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5137 }
5138 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005139 case BO_Div:
5140 if (Result.isComplexFloat()) {
5141 ComplexValue LHS = Result;
5142 APFloat &LHS_r = LHS.getComplexFloatReal();
5143 APFloat &LHS_i = LHS.getComplexFloatImag();
5144 APFloat &RHS_r = RHS.getComplexFloatReal();
5145 APFloat &RHS_i = RHS.getComplexFloatImag();
5146 APFloat &Res_r = Result.getComplexFloatReal();
5147 APFloat &Res_i = Result.getComplexFloatImag();
5148
5149 APFloat Den = RHS_r;
5150 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5151 APFloat Tmp = RHS_i;
5152 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5153 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5154
5155 Res_r = LHS_r;
5156 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5157 Tmp = LHS_i;
5158 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5159 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5160 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5161
5162 Res_i = LHS_i;
5163 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5164 Tmp = LHS_r;
5165 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5166 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5167 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5168 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005169 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5170 return Error(E, diag::note_expr_divide_by_zero);
5171
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005172 ComplexValue LHS = Result;
5173 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5174 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5175 Result.getComplexIntReal() =
5176 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5177 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5178 Result.getComplexIntImag() =
5179 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5180 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5181 }
5182 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00005183 }
5184
John McCall93d91dc2010-05-07 17:22:02 +00005185 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00005186}
5187
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005188bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5189 // Get the operand value into 'Result'.
5190 if (!Visit(E->getSubExpr()))
5191 return false;
5192
5193 switch (E->getOpcode()) {
5194 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00005195 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005196 case UO_Extension:
5197 return true;
5198 case UO_Plus:
5199 // The result is always just the subexpr.
5200 return true;
5201 case UO_Minus:
5202 if (Result.isComplexFloat()) {
5203 Result.getComplexFloatReal().changeSign();
5204 Result.getComplexFloatImag().changeSign();
5205 }
5206 else {
5207 Result.getComplexIntReal() = -Result.getComplexIntReal();
5208 Result.getComplexIntImag() = -Result.getComplexIntImag();
5209 }
5210 return true;
5211 case UO_Not:
5212 if (Result.isComplexFloat())
5213 Result.getComplexFloatImag().changeSign();
5214 else
5215 Result.getComplexIntImag() = -Result.getComplexIntImag();
5216 return true;
5217 }
5218}
5219
Eli Friedmanc4b251d2012-01-10 04:58:17 +00005220bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5221 if (E->getNumInits() == 2) {
5222 if (E->getType()->isComplexType()) {
5223 Result.makeComplexFloat();
5224 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5225 return false;
5226 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5227 return false;
5228 } else {
5229 Result.makeComplexInt();
5230 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5231 return false;
5232 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5233 return false;
5234 }
5235 return true;
5236 }
5237 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5238}
5239
Anders Carlsson537969c2008-11-16 20:27:53 +00005240//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00005241// Void expression evaluation, primarily for a cast to void on the LHS of a
5242// comma operator
5243//===----------------------------------------------------------------------===//
5244
5245namespace {
5246class VoidExprEvaluator
5247 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5248public:
5249 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5250
5251 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00005252
5253 bool VisitCastExpr(const CastExpr *E) {
5254 switch (E->getCastKind()) {
5255 default:
5256 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5257 case CK_ToVoid:
5258 VisitIgnoredValue(E->getSubExpr());
5259 return true;
5260 }
5261 }
5262};
5263} // end anonymous namespace
5264
5265static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5266 assert(E->isRValue() && E->getType()->isVoidType());
5267 return VoidExprEvaluator(Info).Visit(E);
5268}
5269
5270//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00005271// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00005272//===----------------------------------------------------------------------===//
5273
Richard Smith0b0a0b62011-10-29 20:57:55 +00005274static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005275 // In C, function designators are not lvalues, but we evaluate them as if they
5276 // are.
5277 if (E->isGLValue() || E->getType()->isFunctionType()) {
5278 LValue LV;
5279 if (!EvaluateLValue(E, LV, Info))
5280 return false;
5281 LV.moveInto(Result);
5282 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00005283 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005284 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005285 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00005286 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005287 return false;
John McCall45d55e42010-05-07 21:00:08 +00005288 } else if (E->getType()->hasPointerRepresentation()) {
5289 LValue LV;
5290 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005291 return false;
Richard Smith725810a2011-10-16 21:26:27 +00005292 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00005293 } else if (E->getType()->isRealFloatingType()) {
5294 llvm::APFloat F(0.0);
5295 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005296 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005297 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00005298 } else if (E->getType()->isAnyComplexType()) {
5299 ComplexValue C;
5300 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005301 return false;
Richard Smith725810a2011-10-16 21:26:27 +00005302 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00005303 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00005304 MemberPtr P;
5305 if (!EvaluateMemberPointer(E, P, Info))
5306 return false;
5307 P.moveInto(Result);
5308 return true;
Richard Smithfddd3842011-12-30 21:15:51 +00005309 } else if (E->getType()->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005310 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00005311 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00005312 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00005313 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005314 Result = Info.CurrentCall->Temporaries[E];
Richard Smithfddd3842011-12-30 21:15:51 +00005315 } else if (E->getType()->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005316 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00005317 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00005318 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5319 return false;
5320 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00005321 } else if (E->getType()->isVoidType()) {
Richard Smith357362d2011-12-13 06:39:58 +00005322 if (Info.getLangOpts().CPlusPlus0x)
5323 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5324 << E->getType();
5325 else
5326 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith42d3af92011-12-07 00:43:50 +00005327 if (!EvaluateVoid(E, Info))
5328 return false;
Richard Smith357362d2011-12-13 06:39:58 +00005329 } else if (Info.getLangOpts().CPlusPlus0x) {
5330 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5331 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005332 } else {
Richard Smith92b1ce02011-12-12 09:28:41 +00005333 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00005334 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005335 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005336
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00005337 return true;
5338}
5339
Richard Smithed5165f2011-11-04 05:33:44 +00005340/// EvaluateConstantExpression - Evaluate an expression as a constant expression
5341/// in-place in an APValue. In some cases, the in-place evaluation is essential,
5342/// since later initializers for an object can indirectly refer to subobjects
5343/// which were initialized earlier.
5344static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smith357362d2011-12-13 06:39:58 +00005345 const LValue &This, const Expr *E,
5346 CheckConstantExpressionKind CCEK) {
Richard Smithfddd3842011-12-30 21:15:51 +00005347 if (!CheckLiteralType(Info, E))
5348 return false;
5349
5350 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00005351 // Evaluate arrays and record types in-place, so that later initializers can
5352 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00005353 if (E->getType()->isArrayType())
5354 return EvaluateArray(E, This, Result, Info);
5355 else if (E->getType()->isRecordType())
5356 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00005357 }
5358
5359 // For any other type, in-place evaluation is unimportant.
5360 CCValue CoreConstResult;
5361 return Evaluate(CoreConstResult, Info, E) &&
Richard Smith357362d2011-12-13 06:39:58 +00005362 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smithed5165f2011-11-04 05:33:44 +00005363}
5364
Richard Smithf57d8cb2011-12-09 22:58:01 +00005365/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5366/// lvalue-to-rvalue cast if it is an lvalue.
5367static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00005368 if (!CheckLiteralType(Info, E))
5369 return false;
5370
Richard Smithf57d8cb2011-12-09 22:58:01 +00005371 CCValue Value;
5372 if (!::Evaluate(Value, Info, E))
5373 return false;
5374
5375 if (E->isGLValue()) {
5376 LValue LV;
5377 LV.setFrom(Value);
5378 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
5379 return false;
5380 }
5381
5382 // Check this core constant expression is a constant expression, and if so,
5383 // convert it to one.
5384 return CheckConstantExpression(Info, E, Value, Result);
5385}
Richard Smith11562c52011-10-28 17:51:58 +00005386
Richard Smith7b553f12011-10-29 00:50:52 +00005387/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00005388/// any crazy technique (that has nothing to do with language standards) that
5389/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00005390/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
5391/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00005392bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith036e2bd2011-12-10 01:10:13 +00005393 // Fast-path evaluations of integer literals, since we sometimes see files
5394 // containing vast quantities of these.
5395 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
5396 Result.Val = APValue(APSInt(L->getValue(),
5397 L->getType()->isUnsignedIntegerType()));
5398 return true;
5399 }
5400
Richard Smith5686e752011-11-10 03:30:42 +00005401 // FIXME: Evaluating initializers for large arrays can cause performance
5402 // problems, and we don't use such values yet. Once we have a more efficient
5403 // array representation, this should be reinstated, and used by CodeGen.
Richard Smith027bf112011-11-17 22:56:20 +00005404 // The same problem affects large records.
5405 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5406 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith5686e752011-11-10 03:30:42 +00005407 return false;
5408
Richard Smithd62306a2011-11-10 06:34:14 +00005409 // FIXME: If this is the initializer for an lvalue, pass that in.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005410 EvalInfo Info(Ctx, Result);
5411 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00005412}
5413
Jay Foad39c79802011-01-12 09:06:06 +00005414bool Expr::EvaluateAsBooleanCondition(bool &Result,
5415 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00005416 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00005417 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00005418 HandleConversionToBool(CCValue(const_cast<ASTContext&>(Ctx),
5419 Scratch.Val, CCValue::GlobalValue()),
Richard Smith0b0a0b62011-10-29 20:57:55 +00005420 Result);
John McCall1be1c632010-01-05 23:42:56 +00005421}
5422
Richard Smith5fab0c92011-12-28 19:48:30 +00005423bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
5424 SideEffectsKind AllowSideEffects) const {
5425 if (!getType()->isIntegralOrEnumerationType())
5426 return false;
5427
Richard Smith11562c52011-10-28 17:51:58 +00005428 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00005429 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
5430 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00005431 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005432
Richard Smith11562c52011-10-28 17:51:58 +00005433 Result = ExprResult.Val.getInt();
5434 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00005435}
5436
Jay Foad39c79802011-01-12 09:06:06 +00005437bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00005438 EvalInfo Info(Ctx, Result);
5439
John McCall45d55e42010-05-07 21:00:08 +00005440 LValue LV;
Richard Smith80815602011-11-07 05:07:52 +00005441 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smith357362d2011-12-13 06:39:58 +00005442 CheckLValueConstantExpression(Info, this, LV, Result.Val,
5443 CCEK_Constant);
Eli Friedman7d45c482009-09-13 10:17:44 +00005444}
5445
Richard Smithd0b4dd62011-12-19 06:19:21 +00005446bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
5447 const VarDecl *VD,
5448 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
5449 Expr::EvalStatus EStatus;
5450 EStatus.Diag = &Notes;
5451
5452 EvalInfo InitInfo(Ctx, EStatus);
5453 InitInfo.setEvaluatingDecl(VD, Value);
5454
Richard Smithfddd3842011-12-30 21:15:51 +00005455 if (!CheckLiteralType(InitInfo, this))
5456 return false;
5457
Richard Smithd0b4dd62011-12-19 06:19:21 +00005458 LValue LVal;
5459 LVal.set(VD);
5460
Richard Smithfddd3842011-12-30 21:15:51 +00005461 // C++11 [basic.start.init]p2:
5462 // Variables with static storage duration or thread storage duration shall be
5463 // zero-initialized before any other initialization takes place.
5464 // This behavior is not present in C.
5465 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
5466 !VD->getType()->isReferenceType()) {
5467 ImplicitValueInitExpr VIE(VD->getType());
5468 if (!EvaluateConstantExpression(Value, InitInfo, LVal, &VIE))
5469 return false;
5470 }
5471
Richard Smithd0b4dd62011-12-19 06:19:21 +00005472 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
5473 !EStatus.HasSideEffects;
5474}
5475
Richard Smith7b553f12011-10-29 00:50:52 +00005476/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
5477/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00005478bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00005479 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00005480 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00005481}
Anders Carlsson59689ed2008-11-22 21:04:56 +00005482
Jay Foad39c79802011-01-12 09:06:06 +00005483bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00005484 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005485}
5486
Richard Smithcaf33902011-10-10 18:28:20 +00005487APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005488 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005489 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00005490 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00005491 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005492 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00005493
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005494 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00005495}
John McCall864e3962010-05-07 05:32:02 +00005496
Abramo Bagnaraf8199452010-05-14 17:07:14 +00005497 bool Expr::EvalResult::isGlobalLValue() const {
5498 assert(Val.isLValue());
5499 return IsGlobalLValue(Val.getLValueBase());
5500 }
5501
5502
John McCall864e3962010-05-07 05:32:02 +00005503/// isIntegerConstantExpr - this recursive routine will test if an expression is
5504/// an integer constant expression.
5505
5506/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
5507/// comma, etc
5508///
5509/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
5510/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
5511/// cast+dereference.
5512
5513// CheckICE - This function does the fundamental ICE checking: the returned
5514// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
5515// Note that to reduce code duplication, this helper does no evaluation
5516// itself; the caller checks whether the expression is evaluatable, and
5517// in the rare cases where CheckICE actually cares about the evaluated
5518// value, it calls into Evalute.
5519//
5520// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00005521// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00005522// 1: This expression is not an ICE, but if it isn't evaluated, it's
5523// a legal subexpression for an ICE. This return value is used to handle
5524// the comma operator in C99 mode.
5525// 2: This expression is not an ICE, and is not a legal subexpression for one.
5526
Dan Gohman28ade552010-07-26 21:25:24 +00005527namespace {
5528
John McCall864e3962010-05-07 05:32:02 +00005529struct ICEDiag {
5530 unsigned Val;
5531 SourceLocation Loc;
5532
5533 public:
5534 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
5535 ICEDiag() : Val(0) {}
5536};
5537
Dan Gohman28ade552010-07-26 21:25:24 +00005538}
5539
5540static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00005541
5542static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
5543 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005544 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00005545 !EVResult.Val.isInt()) {
5546 return ICEDiag(2, E->getLocStart());
5547 }
5548 return NoDiag();
5549}
5550
5551static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
5552 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00005553 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00005554 return ICEDiag(2, E->getLocStart());
5555 }
5556
5557 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00005558#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00005559#define STMT(Node, Base) case Expr::Node##Class:
5560#define EXPR(Node, Base)
5561#include "clang/AST/StmtNodes.inc"
5562 case Expr::PredefinedExprClass:
5563 case Expr::FloatingLiteralClass:
5564 case Expr::ImaginaryLiteralClass:
5565 case Expr::StringLiteralClass:
5566 case Expr::ArraySubscriptExprClass:
5567 case Expr::MemberExprClass:
5568 case Expr::CompoundAssignOperatorClass:
5569 case Expr::CompoundLiteralExprClass:
5570 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00005571 case Expr::DesignatedInitExprClass:
5572 case Expr::ImplicitValueInitExprClass:
5573 case Expr::ParenListExprClass:
5574 case Expr::VAArgExprClass:
5575 case Expr::AddrLabelExprClass:
5576 case Expr::StmtExprClass:
5577 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00005578 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00005579 case Expr::CXXDynamicCastExprClass:
5580 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00005581 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00005582 case Expr::CXXNullPtrLiteralExprClass:
5583 case Expr::CXXThisExprClass:
5584 case Expr::CXXThrowExprClass:
5585 case Expr::CXXNewExprClass:
5586 case Expr::CXXDeleteExprClass:
5587 case Expr::CXXPseudoDestructorExprClass:
5588 case Expr::UnresolvedLookupExprClass:
5589 case Expr::DependentScopeDeclRefExprClass:
5590 case Expr::CXXConstructExprClass:
5591 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00005592 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00005593 case Expr::CXXTemporaryObjectExprClass:
5594 case Expr::CXXUnresolvedConstructExprClass:
5595 case Expr::CXXDependentScopeMemberExprClass:
5596 case Expr::UnresolvedMemberExprClass:
5597 case Expr::ObjCStringLiteralClass:
5598 case Expr::ObjCEncodeExprClass:
5599 case Expr::ObjCMessageExprClass:
5600 case Expr::ObjCSelectorExprClass:
5601 case Expr::ObjCProtocolExprClass:
5602 case Expr::ObjCIvarRefExprClass:
5603 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00005604 case Expr::ObjCIsaExprClass:
5605 case Expr::ShuffleVectorExprClass:
5606 case Expr::BlockExprClass:
5607 case Expr::BlockDeclRefExprClass:
5608 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00005609 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00005610 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00005611 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00005612 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00005613 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00005614 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00005615 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00005616 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00005617 case Expr::InitListExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00005618 return ICEDiag(2, E->getLocStart());
5619
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005620 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00005621 case Expr::GNUNullExprClass:
5622 // GCC considers the GNU __null value to be an integral constant expression.
5623 return NoDiag();
5624
John McCall7c454bb2011-07-15 05:09:51 +00005625 case Expr::SubstNonTypeTemplateParmExprClass:
5626 return
5627 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
5628
John McCall864e3962010-05-07 05:32:02 +00005629 case Expr::ParenExprClass:
5630 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00005631 case Expr::GenericSelectionExprClass:
5632 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005633 case Expr::IntegerLiteralClass:
5634 case Expr::CharacterLiteralClass:
5635 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00005636 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00005637 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005638 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00005639 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00005640 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00005641 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00005642 return NoDiag();
5643 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00005644 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00005645 // C99 6.6/3 allows function calls within unevaluated subexpressions of
5646 // constant expressions, but they can never be ICEs because an ICE cannot
5647 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00005648 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005649 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00005650 return CheckEvalInICE(E, Ctx);
5651 return ICEDiag(2, E->getLocStart());
5652 }
5653 case Expr::DeclRefExprClass:
5654 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
5655 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00005656 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00005657 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
5658
5659 // Parameter variables are never constants. Without this check,
5660 // getAnyInitializer() can find a default argument, which leads
5661 // to chaos.
5662 if (isa<ParmVarDecl>(D))
5663 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5664
5665 // C++ 7.1.5.1p2
5666 // A variable of non-volatile const-qualified integral or enumeration
5667 // type initialized by an ICE can be used in ICEs.
5668 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00005669 if (!Dcl->getType()->isIntegralOrEnumerationType())
5670 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5671
Richard Smithd0b4dd62011-12-19 06:19:21 +00005672 const VarDecl *VD;
5673 // Look for a declaration of this variable that has an initializer, and
5674 // check whether it is an ICE.
5675 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
5676 return NoDiag();
5677 else
5678 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00005679 }
5680 }
5681 return ICEDiag(2, E->getLocStart());
5682 case Expr::UnaryOperatorClass: {
5683 const UnaryOperator *Exp = cast<UnaryOperator>(E);
5684 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00005685 case UO_PostInc:
5686 case UO_PostDec:
5687 case UO_PreInc:
5688 case UO_PreDec:
5689 case UO_AddrOf:
5690 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00005691 // C99 6.6/3 allows increment and decrement within unevaluated
5692 // subexpressions of constant expressions, but they can never be ICEs
5693 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00005694 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00005695 case UO_Extension:
5696 case UO_LNot:
5697 case UO_Plus:
5698 case UO_Minus:
5699 case UO_Not:
5700 case UO_Real:
5701 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00005702 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005703 }
5704
5705 // OffsetOf falls through here.
5706 }
5707 case Expr::OffsetOfExprClass: {
5708 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00005709 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00005710 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00005711 // compliance: we should warn earlier for offsetof expressions with
5712 // array subscripts that aren't ICEs, and if the array subscripts
5713 // are ICEs, the value of the offsetof must be an integer constant.
5714 return CheckEvalInICE(E, Ctx);
5715 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00005716 case Expr::UnaryExprOrTypeTraitExprClass: {
5717 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
5718 if ((Exp->getKind() == UETT_SizeOf) &&
5719 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00005720 return ICEDiag(2, E->getLocStart());
5721 return NoDiag();
5722 }
5723 case Expr::BinaryOperatorClass: {
5724 const BinaryOperator *Exp = cast<BinaryOperator>(E);
5725 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00005726 case BO_PtrMemD:
5727 case BO_PtrMemI:
5728 case BO_Assign:
5729 case BO_MulAssign:
5730 case BO_DivAssign:
5731 case BO_RemAssign:
5732 case BO_AddAssign:
5733 case BO_SubAssign:
5734 case BO_ShlAssign:
5735 case BO_ShrAssign:
5736 case BO_AndAssign:
5737 case BO_XorAssign:
5738 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00005739 // C99 6.6/3 allows assignments within unevaluated subexpressions of
5740 // constant expressions, but they can never be ICEs because an ICE cannot
5741 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00005742 return ICEDiag(2, E->getLocStart());
5743
John McCalle3027922010-08-25 11:45:40 +00005744 case BO_Mul:
5745 case BO_Div:
5746 case BO_Rem:
5747 case BO_Add:
5748 case BO_Sub:
5749 case BO_Shl:
5750 case BO_Shr:
5751 case BO_LT:
5752 case BO_GT:
5753 case BO_LE:
5754 case BO_GE:
5755 case BO_EQ:
5756 case BO_NE:
5757 case BO_And:
5758 case BO_Xor:
5759 case BO_Or:
5760 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00005761 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5762 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00005763 if (Exp->getOpcode() == BO_Div ||
5764 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00005765 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00005766 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00005767 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00005768 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00005769 if (REval == 0)
5770 return ICEDiag(1, E->getLocStart());
5771 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00005772 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00005773 if (LEval.isMinSignedValue())
5774 return ICEDiag(1, E->getLocStart());
5775 }
5776 }
5777 }
John McCalle3027922010-08-25 11:45:40 +00005778 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00005779 if (Ctx.getLangOptions().C99) {
5780 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
5781 // if it isn't evaluated.
5782 if (LHSResult.Val == 0 && RHSResult.Val == 0)
5783 return ICEDiag(1, E->getLocStart());
5784 } else {
5785 // In both C89 and C++, commas in ICEs are illegal.
5786 return ICEDiag(2, E->getLocStart());
5787 }
5788 }
5789 if (LHSResult.Val >= RHSResult.Val)
5790 return LHSResult;
5791 return RHSResult;
5792 }
John McCalle3027922010-08-25 11:45:40 +00005793 case BO_LAnd:
5794 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00005795 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5796 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
5797 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
5798 // Rare case where the RHS has a comma "side-effect"; we need
5799 // to actually check the condition to see whether the side
5800 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00005801 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00005802 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00005803 return RHSResult;
5804 return NoDiag();
5805 }
5806
5807 if (LHSResult.Val >= RHSResult.Val)
5808 return LHSResult;
5809 return RHSResult;
5810 }
5811 }
5812 }
5813 case Expr::ImplicitCastExprClass:
5814 case Expr::CStyleCastExprClass:
5815 case Expr::CXXFunctionalCastExprClass:
5816 case Expr::CXXStaticCastExprClass:
5817 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00005818 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005819 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00005820 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00005821 if (isa<ExplicitCastExpr>(E)) {
5822 if (const FloatingLiteral *FL
5823 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
5824 unsigned DestWidth = Ctx.getIntWidth(E->getType());
5825 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
5826 APSInt IgnoredVal(DestWidth, !DestSigned);
5827 bool Ignored;
5828 // If the value does not fit in the destination type, the behavior is
5829 // undefined, so we are not required to treat it as a constant
5830 // expression.
5831 if (FL->getValue().convertToInteger(IgnoredVal,
5832 llvm::APFloat::rmTowardZero,
5833 &Ignored) & APFloat::opInvalidOp)
5834 return ICEDiag(2, E->getLocStart());
5835 return NoDiag();
5836 }
5837 }
Eli Friedman76d4e432011-09-29 21:49:34 +00005838 switch (cast<CastExpr>(E)->getCastKind()) {
5839 case CK_LValueToRValue:
5840 case CK_NoOp:
5841 case CK_IntegralToBoolean:
5842 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00005843 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00005844 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00005845 return ICEDiag(2, E->getLocStart());
5846 }
John McCall864e3962010-05-07 05:32:02 +00005847 }
John McCallc07a0c72011-02-17 10:25:35 +00005848 case Expr::BinaryConditionalOperatorClass: {
5849 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
5850 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
5851 if (CommonResult.Val == 2) return CommonResult;
5852 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
5853 if (FalseResult.Val == 2) return FalseResult;
5854 if (CommonResult.Val == 1) return CommonResult;
5855 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00005856 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00005857 return FalseResult;
5858 }
John McCall864e3962010-05-07 05:32:02 +00005859 case Expr::ConditionalOperatorClass: {
5860 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
5861 // If the condition (ignoring parens) is a __builtin_constant_p call,
5862 // then only the true side is actually considered in an integer constant
5863 // expression, and it is fully evaluated. This is an important GNU
5864 // extension. See GCC PR38377 for discussion.
5865 if (const CallExpr *CallCE
5866 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00005867 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
5868 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00005869 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005870 if (CondResult.Val == 2)
5871 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005872
Richard Smithf57d8cb2011-12-09 22:58:01 +00005873 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
5874 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005875
John McCall864e3962010-05-07 05:32:02 +00005876 if (TrueResult.Val == 2)
5877 return TrueResult;
5878 if (FalseResult.Val == 2)
5879 return FalseResult;
5880 if (CondResult.Val == 1)
5881 return CondResult;
5882 if (TrueResult.Val == 0 && FalseResult.Val == 0)
5883 return NoDiag();
5884 // Rare case where the diagnostics depend on which side is evaluated
5885 // Note that if we get here, CondResult is 0, and at least one of
5886 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00005887 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00005888 return FalseResult;
5889 }
5890 return TrueResult;
5891 }
5892 case Expr::CXXDefaultArgExprClass:
5893 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
5894 case Expr::ChooseExprClass: {
5895 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
5896 }
5897 }
5898
5899 // Silence a GCC warning
5900 return ICEDiag(2, E->getLocStart());
5901}
5902
Richard Smithf57d8cb2011-12-09 22:58:01 +00005903/// Evaluate an expression as a C++11 integral constant expression.
5904static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
5905 const Expr *E,
5906 llvm::APSInt *Value,
5907 SourceLocation *Loc) {
5908 if (!E->getType()->isIntegralOrEnumerationType()) {
5909 if (Loc) *Loc = E->getExprLoc();
5910 return false;
5911 }
5912
5913 Expr::EvalResult Result;
Richard Smith92b1ce02011-12-12 09:28:41 +00005914 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
5915 Result.Diag = &Diags;
5916 EvalInfo Info(Ctx, Result);
5917
5918 bool IsICE = EvaluateAsRValue(Info, E, Result.Val);
5919 if (!Diags.empty()) {
5920 IsICE = false;
5921 if (Loc) *Loc = Diags[0].first;
5922 } else if (!IsICE && Loc) {
5923 *Loc = E->getExprLoc();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005924 }
Richard Smith92b1ce02011-12-12 09:28:41 +00005925
5926 if (!IsICE)
5927 return false;
5928
5929 assert(Result.Val.isInt() && "pointer cast to int is not an ICE");
5930 if (Value) *Value = Result.Val.getInt();
5931 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005932}
5933
Richard Smith92b1ce02011-12-12 09:28:41 +00005934bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005935 if (Ctx.getLangOptions().CPlusPlus0x)
5936 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
5937
John McCall864e3962010-05-07 05:32:02 +00005938 ICEDiag d = CheckICE(this, Ctx);
5939 if (d.Val != 0) {
5940 if (Loc) *Loc = d.Loc;
5941 return false;
5942 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005943 return true;
5944}
5945
5946bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
5947 SourceLocation *Loc, bool isEvaluated) const {
5948 if (Ctx.getLangOptions().CPlusPlus0x)
5949 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
5950
5951 if (!isIntegerConstantExpr(Ctx, Loc))
5952 return false;
5953 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00005954 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00005955 return true;
5956}