blob: 36addddcc5cf97efc19eb962099177698a8d8267 [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
835/// either LValue or CCValue.
Richard Smith80815602011-11-07 05:07:52 +0000836template<typename T>
Richard Smithf57d8cb2011-12-09 22:58:01 +0000837static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +0000838 const T &LVal, APValue &Value,
839 CheckConstantExpressionKind CCEK) {
840 APValue::LValueBase Base = LVal.getLValueBase();
841 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
842
843 if (!IsGlobalLValue(Base)) {
844 if (Info.getLangOpts().CPlusPlus0x) {
845 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
846 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
847 << E->isGLValue() << !Designator.Entries.empty()
848 << !!VD << CCEK << VD;
849 if (VD)
850 Info.Note(VD->getLocation(), diag::note_declared_at);
851 else
852 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
853 diag::note_constexpr_temporary_here);
854 } else {
Richard Smithf2b681b2011-12-21 05:04:46 +0000855 Info.Diag(E->getExprLoc());
Richard Smith357362d2011-12-13 06:39:58 +0000856 }
Richard Smith80815602011-11-07 05:07:52 +0000857 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000858 }
Richard Smith80815602011-11-07 05:07:52 +0000859
Richard Smitha8105bc2012-01-06 16:39:00 +0000860 bool IsReferenceType = E->isGLValue();
861
862 if (Designator.Invalid) {
863 // This is not a core constant expression. A diagnostic will have already
864 // been produced.
865 if (IsReferenceType)
866 return false;
867
868 // Allow this for pointers, so we can fold things like integers cast to
869 // pointers.
Richard Smith80815602011-11-07 05:07:52 +0000870 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
871 APValue::NoLValuePath());
872 return true;
873 }
874
Richard Smitha8105bc2012-01-06 16:39:00 +0000875 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
876 Designator.Entries, Designator.IsOnePastTheEnd);
877
878 // Allow address constant expressions to be past-the-end pointers. This is
879 // an extension: the standard requires them to point to an object.
880 if (!IsReferenceType)
881 return true;
882
883 // A reference constant expression must refer to an object.
884 if (!Base) {
885 // FIXME: diagnostic
886 Info.CCEDiag(E->getExprLoc());
887 return false;
888 }
889
Richard Smith357362d2011-12-13 06:39:58 +0000890 // Does this refer one past the end of some object?
Richard Smitha8105bc2012-01-06 16:39:00 +0000891 if (Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +0000892 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
893 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
894 << !Designator.Entries.empty() << !!VD << VD;
895 if (VD)
896 Info.Note(VD->getLocation(), diag::note_declared_at);
897 else
898 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
899 diag::note_constexpr_temporary_here);
900 return false;
901 }
902
Richard Smith80815602011-11-07 05:07:52 +0000903 return true;
904}
905
Richard Smithfddd3842011-12-30 21:15:51 +0000906/// Check that this core constant expression is of literal type, and if not,
907/// produce an appropriate diagnostic.
908static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
909 if (!E->isRValue() || E->getType()->isLiteralType())
910 return true;
911
912 // Prvalue constant expressions must be of literal types.
913 if (Info.getLangOpts().CPlusPlus0x)
914 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
915 << E->getType();
916 else
917 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
918 return false;
919}
920
Richard Smith0b0a0b62011-10-29 20:57:55 +0000921/// Check that this core constant expression value is a valid value for a
Richard Smithed5165f2011-11-04 05:33:44 +0000922/// constant expression, and if it is, produce the corresponding constant value.
Richard Smithfddd3842011-12-30 21:15:51 +0000923/// If not, report an appropriate diagnostic. Does not check that the expression
924/// is of literal type.
Richard Smithf57d8cb2011-12-09 22:58:01 +0000925static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +0000926 const CCValue &CCValue, APValue &Value,
927 CheckConstantExpressionKind CCEK
928 = CCEK_Constant) {
Richard Smith80815602011-11-07 05:07:52 +0000929 if (!CCValue.isLValue()) {
930 Value = CCValue;
931 return true;
932 }
Richard Smith357362d2011-12-13 06:39:58 +0000933 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000934}
935
Richard Smith83c68212011-10-31 05:11:32 +0000936const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +0000937 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +0000938}
939
940static bool IsLiteralLValue(const LValue &Value) {
Richard Smithce40ad62011-11-12 22:28:03 +0000941 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith83c68212011-10-31 05:11:32 +0000942}
943
Richard Smithcecf1842011-11-01 21:06:14 +0000944static bool IsWeakLValue(const LValue &Value) {
945 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +0000946 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +0000947}
948
Richard Smith027bf112011-11-17 22:56:20 +0000949static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +0000950 // A null base expression indicates a null pointer. These are always
951 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +0000952 if (!Value.getLValueBase()) {
953 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +0000954 return true;
955 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000956
John McCall95007602010-05-10 23:27:23 +0000957 // Require the base expression to be a global l-value.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000958 // FIXME: C++11 requires such conversions. Remove this check.
Richard Smith027bf112011-11-17 22:56:20 +0000959 if (!IsGlobalLValue(Value.getLValueBase())) return false;
John McCall95007602010-05-10 23:27:23 +0000960
Richard Smith027bf112011-11-17 22:56:20 +0000961 // We have a non-null base. These are generally known to be true, but if it's
962 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000963 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +0000964 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +0000965 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +0000966}
967
Richard Smith0b0a0b62011-10-29 20:57:55 +0000968static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +0000969 switch (Val.getKind()) {
970 case APValue::Uninitialized:
971 return false;
972 case APValue::Int:
973 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000974 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000975 case APValue::Float:
976 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000977 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000978 case APValue::ComplexInt:
979 Result = Val.getComplexIntReal().getBoolValue() ||
980 Val.getComplexIntImag().getBoolValue();
981 return true;
982 case APValue::ComplexFloat:
983 Result = !Val.getComplexFloatReal().isZero() ||
984 !Val.getComplexFloatImag().isZero();
985 return true;
Richard Smith027bf112011-11-17 22:56:20 +0000986 case APValue::LValue:
987 return EvalPointerValueAsBool(Val, Result);
988 case APValue::MemberPointer:
989 Result = Val.getMemberPointerDecl();
990 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000991 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +0000992 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +0000993 case APValue::Struct:
994 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +0000995 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +0000996 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000997 }
998
Richard Smith11562c52011-10-28 17:51:58 +0000999 llvm_unreachable("unknown APValue kind");
1000}
1001
1002static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1003 EvalInfo &Info) {
1004 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001005 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +00001006 if (!Evaluate(Val, Info, E))
1007 return false;
1008 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001009}
1010
Richard Smith357362d2011-12-13 06:39:58 +00001011template<typename T>
1012static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1013 const T &SrcValue, QualType DestType) {
1014 llvm::SmallVector<char, 32> Buffer;
1015 SrcValue.toString(Buffer);
1016 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
1017 << StringRef(Buffer.data(), Buffer.size()) << DestType;
1018 return false;
1019}
1020
1021static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1022 QualType SrcType, const APFloat &Value,
1023 QualType DestType, APSInt &Result) {
1024 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001025 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001026 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001027
Richard Smith357362d2011-12-13 06:39:58 +00001028 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001029 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001030 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1031 & APFloat::opInvalidOp)
1032 return HandleOverflow(Info, E, Value, DestType);
1033 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001034}
1035
Richard Smith357362d2011-12-13 06:39:58 +00001036static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1037 QualType SrcType, QualType DestType,
1038 APFloat &Result) {
1039 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001040 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001041 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1042 APFloat::rmNearestTiesToEven, &ignored)
1043 & APFloat::opOverflow)
1044 return HandleOverflow(Info, E, Value, DestType);
1045 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001046}
1047
Mike Stump11289f42009-09-09 15:08:12 +00001048static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +00001049 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001050 unsigned DestWidth = Ctx.getIntWidth(DestType);
1051 APSInt Result = Value;
1052 // Figure out if this is a truncate, extend or noop cast.
1053 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001054 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001055 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001056 return Result;
1057}
1058
Richard Smith357362d2011-12-13 06:39:58 +00001059static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1060 QualType SrcType, const APSInt &Value,
1061 QualType DestType, APFloat &Result) {
1062 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1063 if (Result.convertFromAPInt(Value, Value.isSigned(),
1064 APFloat::rmNearestTiesToEven)
1065 & APFloat::opOverflow)
1066 return HandleOverflow(Info, E, Value, DestType);
1067 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001068}
1069
Eli Friedman803acb32011-12-22 03:51:45 +00001070static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1071 llvm::APInt &Res) {
1072 CCValue SVal;
1073 if (!Evaluate(SVal, Info, E))
1074 return false;
1075 if (SVal.isInt()) {
1076 Res = SVal.getInt();
1077 return true;
1078 }
1079 if (SVal.isFloat()) {
1080 Res = SVal.getFloat().bitcastToAPInt();
1081 return true;
1082 }
1083 if (SVal.isVector()) {
1084 QualType VecTy = E->getType();
1085 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1086 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1087 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1088 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1089 Res = llvm::APInt::getNullValue(VecSize);
1090 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1091 APValue &Elt = SVal.getVectorElt(i);
1092 llvm::APInt EltAsInt;
1093 if (Elt.isInt()) {
1094 EltAsInt = Elt.getInt();
1095 } else if (Elt.isFloat()) {
1096 EltAsInt = Elt.getFloat().bitcastToAPInt();
1097 } else {
1098 // Don't try to handle vectors of anything other than int or float
1099 // (not sure if it's possible to hit this case).
1100 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1101 return false;
1102 }
1103 unsigned BaseEltSize = EltAsInt.getBitWidth();
1104 if (BigEndian)
1105 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1106 else
1107 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1108 }
1109 return true;
1110 }
1111 // Give up if the input isn't an int, float, or vector. For example, we
1112 // reject "(v4i16)(intptr_t)&a".
1113 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1114 return false;
1115}
1116
Richard Smitha8105bc2012-01-06 16:39:00 +00001117/// Cast an lvalue referring to a base subobject to a derived class, by
1118/// truncating the lvalue's path to the given length.
1119static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1120 const RecordDecl *TruncatedType,
1121 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001122 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001123
1124 // Check we actually point to a derived class object.
1125 if (TruncatedElements == D.Entries.size())
1126 return true;
1127 assert(TruncatedElements >= D.MostDerivedPathLength &&
1128 "not casting to a derived class");
1129 if (!Result.checkSubobject(Info, E, CSK_Derived))
1130 return false;
1131
1132 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001133 const RecordDecl *RD = TruncatedType;
1134 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smithd62306a2011-11-10 06:34:14 +00001135 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1136 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001137 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001138 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001139 else
Richard Smithd62306a2011-11-10 06:34:14 +00001140 Result.Offset -= Layout.getBaseClassOffset(Base);
1141 RD = Base;
1142 }
Richard Smith027bf112011-11-17 22:56:20 +00001143 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001144 return true;
1145}
1146
Richard Smitha8105bc2012-01-06 16:39:00 +00001147static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001148 const CXXRecordDecl *Derived,
1149 const CXXRecordDecl *Base,
1150 const ASTRecordLayout *RL = 0) {
1151 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1152 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001153 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
Richard Smithd62306a2011-11-10 06:34:14 +00001154}
1155
Richard Smitha8105bc2012-01-06 16:39:00 +00001156static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001157 const CXXRecordDecl *DerivedDecl,
1158 const CXXBaseSpecifier *Base) {
1159 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1160
1161 if (!Base->isVirtual()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001162 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001163 return true;
1164 }
1165
Richard Smitha8105bc2012-01-06 16:39:00 +00001166 SubobjectDesignator &D = Obj.Designator;
1167 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001168 return false;
1169
Richard Smitha8105bc2012-01-06 16:39:00 +00001170 // Extract most-derived object and corresponding type.
1171 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1172 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1173 return false;
1174
1175 // Find the virtual base class.
Richard Smithd62306a2011-11-10 06:34:14 +00001176 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1177 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001178 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001179 return true;
1180}
1181
1182/// Update LVal to refer to the given field, which must be a member of the type
1183/// currently described by LVal.
Richard Smitha8105bc2012-01-06 16:39:00 +00001184static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001185 const FieldDecl *FD,
1186 const ASTRecordLayout *RL = 0) {
1187 if (!RL)
1188 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1189
1190 unsigned I = FD->getFieldIndex();
1191 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001192 LVal.addDecl(Info, E, FD);
Richard Smithd62306a2011-11-10 06:34:14 +00001193}
1194
1195/// Get the size of the given type in char units.
1196static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1197 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1198 // extension.
1199 if (Type->isVoidType() || Type->isFunctionType()) {
1200 Size = CharUnits::One();
1201 return true;
1202 }
1203
1204 if (!Type->isConstantSizeType()) {
1205 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smitha8105bc2012-01-06 16:39:00 +00001206 // FIXME: Diagnostic.
Richard Smithd62306a2011-11-10 06:34:14 +00001207 return false;
1208 }
1209
1210 Size = Info.Ctx.getTypeSizeInChars(Type);
1211 return true;
1212}
1213
1214/// Update a pointer value to model pointer arithmetic.
1215/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001216/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001217/// \param LVal - The pointer value to be updated.
1218/// \param EltTy - The pointee type represented by LVal.
1219/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001220static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1221 LValue &LVal, QualType EltTy,
1222 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001223 CharUnits SizeOfPointee;
1224 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1225 return false;
1226
1227 // Compute the new offset in the appropriate width.
1228 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001229 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001230 return true;
1231}
1232
Richard Smith27908702011-10-24 17:54:18 +00001233/// Try to evaluate the initializer for a variable declaration.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001234static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1235 const VarDecl *VD,
Richard Smithfec09922011-11-01 16:57:24 +00001236 CallStackFrame *Frame, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001237 // If this is a parameter to an active constexpr function call, perform
1238 // argument substitution.
1239 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001240 if (!Frame || !Frame->Arguments) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001241 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001242 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001243 }
Richard Smithfec09922011-11-01 16:57:24 +00001244 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1245 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001246 }
Richard Smith27908702011-10-24 17:54:18 +00001247
Richard Smithd0b4dd62011-12-19 06:19:21 +00001248 // Dig out the initializer, and use the declaration which it's attached to.
1249 const Expr *Init = VD->getAnyInitializer(VD);
1250 if (!Init || Init->isValueDependent()) {
1251 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1252 return false;
1253 }
1254
Richard Smithd62306a2011-11-10 06:34:14 +00001255 // If we're currently evaluating the initializer of this declaration, use that
1256 // in-flight value.
1257 if (Info.EvaluatingDecl == VD) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001258 Result = CCValue(Info.Ctx, *Info.EvaluatingDeclValue,
1259 CCValue::GlobalValue());
Richard Smithd62306a2011-11-10 06:34:14 +00001260 return !Result.isUninit();
1261 }
1262
Richard Smithcecf1842011-11-01 21:06:14 +00001263 // Never evaluate the initializer of a weak variable. We can't be sure that
1264 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001265 if (VD->isWeak()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001266 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001267 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001268 }
Richard Smithcecf1842011-11-01 21:06:14 +00001269
Richard Smithd0b4dd62011-12-19 06:19:21 +00001270 // Check that we can fold the initializer. In C++, we will have already done
1271 // this in the cases where it matters for conformance.
1272 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1273 if (!VD->evaluateValue(Notes)) {
1274 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1275 Notes.size() + 1) << VD;
1276 Info.Note(VD->getLocation(), diag::note_declared_at);
1277 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001278 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001279 } else if (!VD->checkInitIsICE()) {
1280 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1281 Notes.size() + 1) << VD;
1282 Info.Note(VD->getLocation(), diag::note_declared_at);
1283 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001284 }
Richard Smith27908702011-10-24 17:54:18 +00001285
Richard Smitha8105bc2012-01-06 16:39:00 +00001286 Result = CCValue(Info.Ctx, *VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +00001287 return true;
Richard Smith27908702011-10-24 17:54:18 +00001288}
1289
Richard Smith11562c52011-10-28 17:51:58 +00001290static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001291 Qualifiers Quals = T.getQualifiers();
1292 return Quals.hasConst() && !Quals.hasVolatile();
1293}
1294
Richard Smithe97cbd72011-11-11 04:05:33 +00001295/// Get the base index of the given base class within an APValue representing
1296/// the given derived class.
1297static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1298 const CXXRecordDecl *Base) {
1299 Base = Base->getCanonicalDecl();
1300 unsigned Index = 0;
1301 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1302 E = Derived->bases_end(); I != E; ++I, ++Index) {
1303 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1304 return Index;
1305 }
1306
1307 llvm_unreachable("base class missing from derived class's bases list");
1308}
1309
Richard Smithf3e9e432011-11-07 09:22:26 +00001310/// Extract the designated sub-object of an rvalue.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001311static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1312 CCValue &Obj, QualType ObjType,
Richard Smithf3e9e432011-11-07 09:22:26 +00001313 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001314 if (Sub.Invalid)
1315 // A diagnostic will have already been produced.
Richard Smithf3e9e432011-11-07 09:22:26 +00001316 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00001317 if (Sub.isOnePastTheEnd()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001318 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gay4a39e492011-12-21 19:36:37 +00001319 (unsigned)diag::note_constexpr_read_past_end :
1320 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001321 return false;
1322 }
Richard Smith6804be52011-11-11 08:28:03 +00001323 if (Sub.Entries.empty())
Richard Smithf3e9e432011-11-07 09:22:26 +00001324 return true;
Richard Smithf3e9e432011-11-07 09:22:26 +00001325
1326 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1327 const APValue *O = &Obj;
Richard Smithd62306a2011-11-10 06:34:14 +00001328 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001329 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001330 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001331 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001332 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001333 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001334 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001335 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001336 // Note, it should not be possible to form a pointer with a valid
1337 // designator which points more than one past the end of the array.
1338 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gay4a39e492011-12-21 19:36:37 +00001339 (unsigned)diag::note_constexpr_read_past_end :
1340 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +00001341 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001342 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001343 if (O->getArrayInitializedElts() > Index)
1344 O = &O->getArrayInitializedElt(Index);
1345 else
1346 O = &O->getArrayFiller();
1347 ObjType = CAT->getElementType();
Richard Smithd62306a2011-11-10 06:34:14 +00001348 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1349 // Next subobject is a class, struct or union field.
1350 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1351 if (RD->isUnion()) {
1352 const FieldDecl *UnionField = O->getUnionField();
1353 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001354 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001355 Info.Diag(E->getExprLoc(),
1356 diag::note_constexpr_read_inactive_union_member)
1357 << Field << !UnionField << UnionField;
Richard Smithd62306a2011-11-10 06:34:14 +00001358 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001359 }
Richard Smithd62306a2011-11-10 06:34:14 +00001360 O = &O->getUnionValue();
1361 } else
1362 O = &O->getStructField(Field->getFieldIndex());
1363 ObjType = Field->getType();
Richard Smithf2b681b2011-12-21 05:04:46 +00001364
1365 if (ObjType.isVolatileQualified()) {
1366 if (Info.getLangOpts().CPlusPlus) {
1367 // FIXME: Include a description of the path to the volatile subobject.
1368 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1369 << 2 << Field;
1370 Info.Note(Field->getLocation(), diag::note_declared_at);
1371 } else {
1372 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1373 }
1374 return false;
1375 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001376 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001377 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001378 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1379 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1380 O = &O->getStructBase(getBaseIndex(Derived, Base));
1381 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithf3e9e432011-11-07 09:22:26 +00001382 }
Richard Smithd62306a2011-11-10 06:34:14 +00001383
Richard Smithf57d8cb2011-12-09 22:58:01 +00001384 if (O->isUninit()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001385 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smithd62306a2011-11-10 06:34:14 +00001386 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001387 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001388 }
1389
Richard Smitha8105bc2012-01-06 16:39:00 +00001390 Obj = CCValue(Info.Ctx, *O, CCValue::GlobalValue());
Richard Smithf3e9e432011-11-07 09:22:26 +00001391 return true;
1392}
1393
Richard Smithd62306a2011-11-10 06:34:14 +00001394/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1395/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1396/// for looking up the glvalue referred to by an entity of reference type.
1397///
1398/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001399/// \param Conv - The expression for which we are performing the conversion.
1400/// Used for diagnostics.
Richard Smithd62306a2011-11-10 06:34:14 +00001401/// \param Type - The type we expect this conversion to produce.
1402/// \param LVal - The glvalue on which we are attempting to perform this action.
1403/// \param RVal - The produced value will be placed here.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001404static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1405 QualType Type,
Richard Smithf3e9e432011-11-07 09:22:26 +00001406 const LValue &LVal, CCValue &RVal) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001407 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1408 if (!Info.getLangOpts().CPlusPlus)
1409 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1410
Richard Smitha8105bc2012-01-06 16:39:00 +00001411 if (LVal.Designator.Invalid)
1412 // A diagnostic will have already been produced.
1413 return false;
1414
Richard Smithce40ad62011-11-12 22:28:03 +00001415 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001416 CallStackFrame *Frame = LVal.Frame;
Richard Smithf2b681b2011-12-21 05:04:46 +00001417 SourceLocation Loc = Conv->getExprLoc();
Richard Smith11562c52011-10-28 17:51:58 +00001418
Richard Smithf57d8cb2011-12-09 22:58:01 +00001419 if (!LVal.Base) {
1420 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smithf2b681b2011-12-21 05:04:46 +00001421 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1422 return false;
1423 }
1424
1425 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1426 // is not a constant expression (even if the object is non-volatile). We also
1427 // apply this rule to C++98, in order to conform to the expected 'volatile'
1428 // semantics.
1429 if (Type.isVolatileQualified()) {
1430 if (Info.getLangOpts().CPlusPlus)
1431 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1432 else
1433 Info.Diag(Loc);
Richard Smith11562c52011-10-28 17:51:58 +00001434 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001435 }
Richard Smith11562c52011-10-28 17:51:58 +00001436
Richard Smithce40ad62011-11-12 22:28:03 +00001437 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smith11562c52011-10-28 17:51:58 +00001438 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1439 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +00001440 // expressions are constant expressions too. Inside constexpr functions,
1441 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +00001442 // In C, such things can also be folded, although they are not ICEs.
Richard Smith11562c52011-10-28 17:51:58 +00001443 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001444 if (!VD || VD->isInvalidDecl()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001445 Info.Diag(Loc);
Richard Smith96e0c102011-11-04 02:25:55 +00001446 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001447 }
1448
Richard Smithf2b681b2011-12-21 05:04:46 +00001449 // DR1313: If the object is volatile-qualified but the glvalue was not,
1450 // behavior is undefined so the result is not a constant expression.
Richard Smithce40ad62011-11-12 22:28:03 +00001451 QualType VT = VD->getType();
Richard Smithf2b681b2011-12-21 05:04:46 +00001452 if (VT.isVolatileQualified()) {
1453 if (Info.getLangOpts().CPlusPlus) {
1454 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1455 Info.Note(VD->getLocation(), diag::note_declared_at);
1456 } else {
1457 Info.Diag(Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001458 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001459 return false;
1460 }
1461
1462 if (!isa<ParmVarDecl>(VD)) {
1463 if (VD->isConstexpr()) {
1464 // OK, we can read this variable.
1465 } else if (VT->isIntegralOrEnumerationType()) {
1466 if (!VT.isConstQualified()) {
1467 if (Info.getLangOpts().CPlusPlus) {
1468 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1469 Info.Note(VD->getLocation(), diag::note_declared_at);
1470 } else {
1471 Info.Diag(Loc);
1472 }
1473 return false;
1474 }
1475 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1476 // We support folding of const floating-point types, in order to make
1477 // static const data members of such types (supported as an extension)
1478 // more useful.
1479 if (Info.getLangOpts().CPlusPlus0x) {
1480 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1481 Info.Note(VD->getLocation(), diag::note_declared_at);
1482 } else {
1483 Info.CCEDiag(Loc);
1484 }
1485 } else {
1486 // FIXME: Allow folding of values of any literal type in all languages.
1487 if (Info.getLangOpts().CPlusPlus0x) {
1488 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1489 Info.Note(VD->getLocation(), diag::note_declared_at);
1490 } else {
1491 Info.Diag(Loc);
1492 }
Richard Smith96e0c102011-11-04 02:25:55 +00001493 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001494 }
Richard Smith96e0c102011-11-04 02:25:55 +00001495 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001496
Richard Smithf57d8cb2011-12-09 22:58:01 +00001497 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smith11562c52011-10-28 17:51:58 +00001498 return false;
1499
Richard Smith0b0a0b62011-10-29 20:57:55 +00001500 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf57d8cb2011-12-09 22:58:01 +00001501 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smith11562c52011-10-28 17:51:58 +00001502
1503 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1504 // conversion. This happens when the declaration and the lvalue should be
1505 // considered synonymous, for instance when initializing an array of char
1506 // from a string literal. Continue as if the initializer lvalue was the
1507 // value we were originally given.
Richard Smith96e0c102011-11-04 02:25:55 +00001508 assert(RVal.getLValueOffset().isZero() &&
1509 "offset for lvalue init of non-reference");
Richard Smithce40ad62011-11-12 22:28:03 +00001510 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001511 Frame = RVal.getLValueFrame();
Richard Smith11562c52011-10-28 17:51:58 +00001512 }
1513
Richard Smithf2b681b2011-12-21 05:04:46 +00001514 // Volatile temporary objects cannot be read in constant expressions.
1515 if (Base->getType().isVolatileQualified()) {
1516 if (Info.getLangOpts().CPlusPlus) {
1517 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1518 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1519 } else {
1520 Info.Diag(Loc);
1521 }
1522 return false;
1523 }
1524
Richard Smith96e0c102011-11-04 02:25:55 +00001525 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1526 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1527 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001528 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001529 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001530 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001531 }
Richard Smith96e0c102011-11-04 02:25:55 +00001532
1533 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith80815602011-11-07 05:07:52 +00001534 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smithf2b681b2011-12-21 05:04:46 +00001535 const ConstantArrayType *CAT =
1536 Info.Ctx.getAsConstantArrayType(S->getType());
1537 if (Index >= CAT->getSize().getZExtValue()) {
1538 // Note, it should not be possible to form a pointer which points more
1539 // than one past the end of the array without producing a prior const expr
1540 // diagnostic.
1541 Info.Diag(Loc, diag::note_constexpr_read_past_end);
Richard Smith96e0c102011-11-04 02:25:55 +00001542 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001543 }
Richard Smith96e0c102011-11-04 02:25:55 +00001544 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1545 Type->isUnsignedIntegerType());
1546 if (Index < S->getLength())
1547 Value = S->getCodeUnit(Index);
1548 RVal = CCValue(Value);
1549 return true;
1550 }
1551
Richard Smithf3e9e432011-11-07 09:22:26 +00001552 if (Frame) {
1553 // If this is a temporary expression with a nontrivial initializer, grab the
1554 // value from the relevant stack frame.
1555 RVal = Frame->Temporaries[Base];
1556 } else if (const CompoundLiteralExpr *CLE
1557 = dyn_cast<CompoundLiteralExpr>(Base)) {
1558 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1559 // initializer until now for such expressions. Such an expression can't be
1560 // an ICE in C, so this only matters for fold.
1561 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1562 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1563 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001564 } else {
Richard Smith92b1ce02011-12-12 09:28:41 +00001565 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001566 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001567 }
Richard Smith96e0c102011-11-04 02:25:55 +00001568
Richard Smithf57d8cb2011-12-09 22:58:01 +00001569 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1570 Type);
Richard Smith11562c52011-10-28 17:51:58 +00001571}
1572
Richard Smithe97cbd72011-11-11 04:05:33 +00001573/// Build an lvalue for the object argument of a member function call.
1574static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1575 LValue &This) {
1576 if (Object->getType()->isPointerType())
1577 return EvaluatePointer(Object, This, Info);
1578
1579 if (Object->isGLValue())
1580 return EvaluateLValue(Object, This, Info);
1581
Richard Smith027bf112011-11-17 22:56:20 +00001582 if (Object->getType()->isLiteralType())
1583 return EvaluateTemporary(Object, This, Info);
1584
1585 return false;
1586}
1587
1588/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1589/// lvalue referring to the result.
1590///
1591/// \param Info - Information about the ongoing evaluation.
1592/// \param BO - The member pointer access operation.
1593/// \param LV - Filled in with a reference to the resulting object.
1594/// \param IncludeMember - Specifies whether the member itself is included in
1595/// the resulting LValue subobject designator. This is not possible when
1596/// creating a bound member function.
1597/// \return The field or method declaration to which the member pointer refers,
1598/// or 0 if evaluation fails.
1599static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1600 const BinaryOperator *BO,
1601 LValue &LV,
1602 bool IncludeMember = true) {
1603 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1604
1605 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV))
1606 return 0;
1607
1608 MemberPtr MemPtr;
1609 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1610 return 0;
1611
1612 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1613 // member value, the behavior is undefined.
1614 if (!MemPtr.getDecl())
1615 return 0;
1616
1617 if (MemPtr.isDerivedMember()) {
1618 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00001619 // The end of the derived-to-base path for the base object must match the
1620 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00001621 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith027bf112011-11-17 22:56:20 +00001622 LV.Designator.Entries.size())
1623 return 0;
1624 unsigned PathLengthToMember =
1625 LV.Designator.Entries.size() - MemPtr.Path.size();
1626 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1627 const CXXRecordDecl *LVDecl = getAsBaseClass(
1628 LV.Designator.Entries[PathLengthToMember + I]);
1629 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1630 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1631 return 0;
1632 }
1633
1634 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00001635 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1636 PathLengthToMember))
1637 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00001638 } else if (!MemPtr.Path.empty()) {
1639 // Extend the LValue path with the member pointer's path.
1640 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1641 MemPtr.Path.size() + IncludeMember);
1642
1643 // Walk down to the appropriate base class.
1644 QualType LVType = BO->getLHS()->getType();
1645 if (const PointerType *PT = LVType->getAs<PointerType>())
1646 LVType = PT->getPointeeType();
1647 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1648 assert(RD && "member pointer access on non-class-type expression");
1649 // The first class in the path is that of the lvalue.
1650 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1651 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smitha8105bc2012-01-06 16:39:00 +00001652 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smith027bf112011-11-17 22:56:20 +00001653 RD = Base;
1654 }
1655 // Finally cast to the class containing the member.
Richard Smitha8105bc2012-01-06 16:39:00 +00001656 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smith027bf112011-11-17 22:56:20 +00001657 }
1658
1659 // Add the member. Note that we cannot build bound member functions here.
1660 if (IncludeMember) {
1661 // FIXME: Deal with IndirectFieldDecls.
1662 const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl());
1663 if (!FD) return 0;
Richard Smitha8105bc2012-01-06 16:39:00 +00001664 HandleLValueMember(Info, BO, LV, FD);
Richard Smith027bf112011-11-17 22:56:20 +00001665 }
1666
1667 return MemPtr.getDecl();
1668}
1669
1670/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1671/// the provided lvalue, which currently refers to the base object.
1672static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1673 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00001674 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001675 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00001676 return false;
1677
Richard Smitha8105bc2012-01-06 16:39:00 +00001678 QualType TargetQT = E->getType();
1679 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1680 TargetQT = PT->getPointeeType();
1681
1682 // Check this cast lands within the final derived-to-base subobject path.
1683 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
1684 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1685 << D.MostDerivedType << TargetQT;
1686 return false;
1687 }
1688
Richard Smith027bf112011-11-17 22:56:20 +00001689 // Check the type of the final cast. We don't need to check the path,
1690 // since a cast can only be formed if the path is unique.
1691 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00001692 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1693 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00001694 if (NewEntriesSize == D.MostDerivedPathLength)
1695 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
1696 else
Richard Smith027bf112011-11-17 22:56:20 +00001697 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00001698 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
1699 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1700 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00001701 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00001702 }
Richard Smith027bf112011-11-17 22:56:20 +00001703
1704 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00001705 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00001706}
1707
Mike Stump876387b2009-10-27 22:09:17 +00001708namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00001709enum EvalStmtResult {
1710 /// Evaluation failed.
1711 ESR_Failed,
1712 /// Hit a 'return' statement.
1713 ESR_Returned,
1714 /// Evaluation succeeded.
1715 ESR_Succeeded
1716};
1717}
1718
1719// Evaluate a statement.
Richard Smith357362d2011-12-13 06:39:58 +00001720static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +00001721 const Stmt *S) {
1722 switch (S->getStmtClass()) {
1723 default:
1724 return ESR_Failed;
1725
1726 case Stmt::NullStmtClass:
1727 case Stmt::DeclStmtClass:
1728 return ESR_Succeeded;
1729
Richard Smith357362d2011-12-13 06:39:58 +00001730 case Stmt::ReturnStmtClass: {
1731 CCValue CCResult;
1732 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1733 if (!Evaluate(CCResult, Info, RetExpr) ||
1734 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1735 CCEK_ReturnValue))
1736 return ESR_Failed;
1737 return ESR_Returned;
1738 }
Richard Smith254a73d2011-10-28 22:34:42 +00001739
1740 case Stmt::CompoundStmtClass: {
1741 const CompoundStmt *CS = cast<CompoundStmt>(S);
1742 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1743 BE = CS->body_end(); BI != BE; ++BI) {
1744 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1745 if (ESR != ESR_Succeeded)
1746 return ESR;
1747 }
1748 return ESR_Succeeded;
1749 }
1750 }
1751}
1752
Richard Smithcc36f692011-12-22 02:22:31 +00001753/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
1754/// default constructor. If so, we'll fold it whether or not it's marked as
1755/// constexpr. If it is marked as constexpr, we will never implicitly define it,
1756/// so we need special handling.
1757static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00001758 const CXXConstructorDecl *CD,
1759 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00001760 if (!CD->isTrivial() || !CD->isDefaultConstructor())
1761 return false;
1762
1763 if (!CD->isConstexpr()) {
1764 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smithfddd3842011-12-30 21:15:51 +00001765 // Value-initialization does not call a trivial default constructor, so
1766 // such a call is a core constant expression whether or not the
1767 // constructor is constexpr.
1768 if (!IsValueInitialization) {
1769 // FIXME: If DiagDecl is an implicitly-declared special member function,
1770 // we should be much more explicit about why it's not constexpr.
1771 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
1772 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
1773 Info.Note(CD->getLocation(), diag::note_declared_at);
1774 }
Richard Smithcc36f692011-12-22 02:22:31 +00001775 } else {
1776 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
1777 }
1778 }
1779 return true;
1780}
1781
Richard Smith357362d2011-12-13 06:39:58 +00001782/// CheckConstexprFunction - Check that a function can be called in a constant
1783/// expression.
1784static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1785 const FunctionDecl *Declaration,
1786 const FunctionDecl *Definition) {
1787 // Can we evaluate this function call?
1788 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1789 return true;
1790
1791 if (Info.getLangOpts().CPlusPlus0x) {
1792 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001793 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1794 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00001795 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1796 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1797 << DiagDecl;
1798 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1799 } else {
1800 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1801 }
1802 return false;
1803}
1804
Richard Smithd62306a2011-11-10 06:34:14 +00001805namespace {
Richard Smith60494462011-11-11 05:48:57 +00001806typedef SmallVector<CCValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00001807}
1808
1809/// EvaluateArgs - Evaluate the arguments to a function call.
1810static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1811 EvalInfo &Info) {
1812 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1813 I != E; ++I)
1814 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1815 return false;
1816 return true;
1817}
1818
Richard Smith254a73d2011-10-28 22:34:42 +00001819/// Evaluate a function call.
Richard Smithf6f003a2011-12-16 19:06:07 +00001820static bool HandleFunctionCall(const Expr *CallExpr, const FunctionDecl *Callee,
1821 const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00001822 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith357362d2011-12-13 06:39:58 +00001823 EvalInfo &Info, APValue &Result) {
1824 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smith254a73d2011-10-28 22:34:42 +00001825 return false;
1826
Richard Smithd62306a2011-11-10 06:34:14 +00001827 ArgVector ArgValues(Args.size());
1828 if (!EvaluateArgs(Args, ArgValues, Info))
1829 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00001830
Richard Smithf6f003a2011-12-16 19:06:07 +00001831 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Callee, This,
1832 ArgValues.data());
Richard Smith254a73d2011-10-28 22:34:42 +00001833 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1834}
1835
Richard Smithd62306a2011-11-10 06:34:14 +00001836/// Evaluate a constructor call.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001837static bool HandleConstructorCall(const Expr *CallExpr, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00001838 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00001839 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00001840 EvalInfo &Info, APValue &Result) {
Richard Smith357362d2011-12-13 06:39:58 +00001841 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smithd62306a2011-11-10 06:34:14 +00001842 return false;
1843
1844 ArgVector ArgValues(Args.size());
1845 if (!EvaluateArgs(Args, ArgValues, Info))
1846 return false;
1847
Richard Smithf6f003a2011-12-16 19:06:07 +00001848 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Definition,
1849 &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00001850
1851 // If it's a delegating constructor, just delegate.
1852 if (Definition->isDelegatingConstructor()) {
1853 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1854 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1855 }
1856
Richard Smith1bc5c2c2012-01-10 04:32:03 +00001857 // For a trivial copy or move constructor, perform an APValue copy. This is
1858 // essential for unions, where the operations performed by the constructor
1859 // cannot be represented by ctor-initializers.
Richard Smithd62306a2011-11-10 06:34:14 +00001860 const CXXRecordDecl *RD = Definition->getParent();
Richard Smith1bc5c2c2012-01-10 04:32:03 +00001861 if (Definition->isDefaulted() &&
1862 ((Definition->isCopyConstructor() && RD->hasTrivialCopyConstructor()) ||
1863 (Definition->isMoveConstructor() && RD->hasTrivialMoveConstructor()))) {
1864 LValue RHS;
1865 RHS.setFrom(ArgValues[0]);
1866 CCValue Value;
1867 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
1868 RHS, Value) &&
1869 CheckConstantExpression(Info, CallExpr, Value, Result);
1870 }
1871
1872 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00001873 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00001874 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1875 std::distance(RD->field_begin(), RD->field_end()));
1876
1877 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1878
1879 unsigned BasesSeen = 0;
1880#ifndef NDEBUG
1881 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1882#endif
1883 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1884 E = Definition->init_end(); I != E; ++I) {
1885 if ((*I)->isBaseInitializer()) {
1886 QualType BaseType((*I)->getBaseClass(), 0);
1887#ifndef NDEBUG
1888 // Non-virtual base classes are initialized in the order in the class
1889 // definition. We cannot have a virtual base class for a literal type.
1890 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1891 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1892 "base class initializers not in expected order");
1893 ++BaseIt;
1894#endif
1895 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00001896 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smithd62306a2011-11-10 06:34:14 +00001897 BaseType->getAsCXXRecordDecl(), &Layout);
1898 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1899 Subobject, (*I)->getInit()))
1900 return false;
1901 } else if (FieldDecl *FD = (*I)->getMember()) {
1902 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00001903 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smithd62306a2011-11-10 06:34:14 +00001904 if (RD->isUnion()) {
1905 Result = APValue(FD);
Richard Smith357362d2011-12-13 06:39:58 +00001906 if (!EvaluateConstantExpression(Result.getUnionValue(), Info, Subobject,
1907 (*I)->getInit(), CCEK_MemberInit))
Richard Smithd62306a2011-11-10 06:34:14 +00001908 return false;
1909 } else if (!EvaluateConstantExpression(
1910 Result.getStructField(FD->getFieldIndex()),
Richard Smith357362d2011-12-13 06:39:58 +00001911 Info, Subobject, (*I)->getInit(), CCEK_MemberInit))
Richard Smithd62306a2011-11-10 06:34:14 +00001912 return false;
1913 } else {
1914 // FIXME: handle indirect field initializers
Richard Smith92b1ce02011-12-12 09:28:41 +00001915 Info.Diag((*I)->getInit()->getExprLoc(),
Richard Smithf57d8cb2011-12-09 22:58:01 +00001916 diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +00001917 return false;
1918 }
1919 }
1920
1921 return true;
1922}
1923
Richard Smith254a73d2011-10-28 22:34:42 +00001924namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001925class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +00001926 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +00001927 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +00001928public:
1929
Richard Smith725810a2011-10-16 21:26:27 +00001930 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +00001931
1932 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +00001933 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +00001934 return true;
1935 }
1936
Peter Collingbournee9200682011-05-13 03:29:01 +00001937 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1938 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001939 return Visit(E->getResultExpr());
1940 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001941 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001942 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001943 return true;
1944 return false;
1945 }
John McCall31168b02011-06-15 23:02:42 +00001946 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001947 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001948 return true;
1949 return false;
1950 }
1951 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001952 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001953 return true;
1954 return false;
1955 }
1956
Mike Stump876387b2009-10-27 22:09:17 +00001957 // We don't want to evaluate BlockExprs multiple times, as they generate
1958 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +00001959 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1960 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1961 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +00001962 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001963 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1964 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1965 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1966 bool VisitStringLiteral(const StringLiteral *E) { return false; }
1967 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1968 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +00001969 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +00001970 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001971 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001972 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +00001973 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001974 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
1975 bool VisitBinAssign(const BinaryOperator *E) { return true; }
1976 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
1977 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001978 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001979 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
1980 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
1981 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
1982 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
1983 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001984 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001985 return true;
Mike Stumpfa502902009-10-29 20:48:09 +00001986 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +00001987 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001988 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +00001989
1990 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +00001991 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +00001992 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
1993 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00001994 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +00001995 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +00001996 return false;
1997 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001998
Peter Collingbournee9200682011-05-13 03:29:01 +00001999 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +00002000};
2001
John McCallc07a0c72011-02-17 10:25:35 +00002002class OpaqueValueEvaluation {
2003 EvalInfo &info;
2004 OpaqueValueExpr *opaqueValue;
2005
2006public:
2007 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2008 Expr *value)
2009 : info(info), opaqueValue(opaqueValue) {
2010
2011 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +00002012 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +00002013 this->opaqueValue = 0;
2014 return;
2015 }
John McCallc07a0c72011-02-17 10:25:35 +00002016 }
2017
2018 bool hasError() const { return opaqueValue == 0; }
2019
2020 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +00002021 // FIXME: This will not work for recursive constexpr functions using opaque
2022 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +00002023 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2024 }
2025};
2026
Mike Stump876387b2009-10-27 22:09:17 +00002027} // end anonymous namespace
2028
Eli Friedman9a156e52008-11-12 09:44:48 +00002029//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00002030// Generic Evaluation
2031//===----------------------------------------------------------------------===//
2032namespace {
2033
Richard Smithf57d8cb2011-12-09 22:58:01 +00002034// FIXME: RetTy is always bool. Remove it.
2035template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00002036class ExprEvaluatorBase
2037 : public ConstStmtVisitor<Derived, RetTy> {
2038private:
Richard Smith0b0a0b62011-10-29 20:57:55 +00002039 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002040 return static_cast<Derived*>(this)->Success(V, E);
2041 }
Richard Smithfddd3842011-12-30 21:15:51 +00002042 RetTy DerivedZeroInitialization(const Expr *E) {
2043 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002044 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002045
2046protected:
2047 EvalInfo &Info;
2048 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2049 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2050
Richard Smith92b1ce02011-12-12 09:28:41 +00002051 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith187ef012011-12-12 09:41:58 +00002052 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002053 }
2054
2055 /// Report an evaluation error. This should only be called when an error is
2056 /// first discovered. When propagating an error, just return false.
2057 bool Error(const Expr *E, diag::kind D) {
Richard Smith92b1ce02011-12-12 09:28:41 +00002058 Info.Diag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002059 return false;
2060 }
2061 bool Error(const Expr *E) {
2062 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2063 }
2064
Richard Smithfddd3842011-12-30 21:15:51 +00002065 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00002066
Peter Collingbournee9200682011-05-13 03:29:01 +00002067public:
2068 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2069
2070 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00002071 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00002072 }
2073 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002074 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002075 }
2076
2077 RetTy VisitParenExpr(const ParenExpr *E)
2078 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2079 RetTy VisitUnaryExtension(const UnaryOperator *E)
2080 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2081 RetTy VisitUnaryPlus(const UnaryOperator *E)
2082 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2083 RetTy VisitChooseExpr(const ChooseExpr *E)
2084 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2085 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2086 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00002087 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2088 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00002089 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2090 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00002091 // We cannot create any objects for which cleanups are required, so there is
2092 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2093 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2094 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002095
Richard Smith6d6ecc32011-12-12 12:46:16 +00002096 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2097 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2098 return static_cast<Derived*>(this)->VisitCastExpr(E);
2099 }
2100 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2101 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2102 return static_cast<Derived*>(this)->VisitCastExpr(E);
2103 }
2104
Richard Smith027bf112011-11-17 22:56:20 +00002105 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2106 switch (E->getOpcode()) {
2107 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00002108 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002109
2110 case BO_Comma:
2111 VisitIgnoredValue(E->getLHS());
2112 return StmtVisitorTy::Visit(E->getRHS());
2113
2114 case BO_PtrMemD:
2115 case BO_PtrMemI: {
2116 LValue Obj;
2117 if (!HandleMemberPointerAccess(Info, E, Obj))
2118 return false;
2119 CCValue Result;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002120 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00002121 return false;
2122 return DerivedSuccess(Result, E);
2123 }
2124 }
2125 }
2126
Peter Collingbournee9200682011-05-13 03:29:01 +00002127 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2128 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2129 if (opaque.hasError())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002130 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002131
2132 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +00002133 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002134 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002135
2136 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
2137 }
2138
2139 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
2140 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00002141 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002142 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002143
Richard Smith11562c52011-10-28 17:51:58 +00002144 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +00002145 return StmtVisitorTy::Visit(EvalExpr);
2146 }
2147
2148 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002149 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002150 if (!Value) {
2151 const Expr *Source = E->getSourceExpr();
2152 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002153 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002154 if (Source == E) { // sanity checking.
2155 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00002156 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002157 }
2158 return StmtVisitorTy::Visit(Source);
2159 }
Richard Smith0b0a0b62011-10-29 20:57:55 +00002160 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002161 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002162
Richard Smith254a73d2011-10-28 22:34:42 +00002163 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002164 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00002165 QualType CalleeType = Callee->getType();
2166
Richard Smith254a73d2011-10-28 22:34:42 +00002167 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00002168 LValue *This = 0, ThisVal;
2169 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith656d49d2011-11-10 09:31:24 +00002170
Richard Smithe97cbd72011-11-11 04:05:33 +00002171 // Extract function decl and 'this' pointer from the callee.
2172 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002173 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00002174 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2175 // Explicit bound member calls, such as x.f() or p->g();
2176 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002177 return false;
2178 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00002179 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00002180 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2181 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00002182 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2183 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00002184 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00002185 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002186 return Error(Callee);
2187
2188 FD = dyn_cast<FunctionDecl>(Member);
2189 if (!FD)
2190 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002191 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002192 LValue Call;
2193 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002194 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00002195
Richard Smitha8105bc2012-01-06 16:39:00 +00002196 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002197 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00002198 FD = dyn_cast_or_null<FunctionDecl>(
2199 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00002200 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002201 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002202
2203 // Overloaded operator calls to member functions are represented as normal
2204 // calls with '*this' as the first argument.
2205 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2206 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002207 // FIXME: When selecting an implicit conversion for an overloaded
2208 // operator delete, we sometimes try to evaluate calls to conversion
2209 // operators without a 'this' parameter!
2210 if (Args.empty())
2211 return Error(E);
2212
Richard Smithe97cbd72011-11-11 04:05:33 +00002213 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2214 return false;
2215 This = &ThisVal;
2216 Args = Args.slice(1);
2217 }
2218
2219 // Don't call function pointers which have been cast to some other type.
2220 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002221 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00002222 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002223 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00002224
Richard Smith357362d2011-12-13 06:39:58 +00002225 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00002226 Stmt *Body = FD->getBody(Definition);
Richard Smithed5165f2011-11-04 05:33:44 +00002227 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00002228
Richard Smith357362d2011-12-13 06:39:58 +00002229 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smithf6f003a2011-12-16 19:06:07 +00002230 !HandleFunctionCall(E, Definition, This, Args, Body, Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002231 return false;
2232
Richard Smitha8105bc2012-01-06 16:39:00 +00002233 return DerivedSuccess(CCValue(Info.Ctx, Result, CCValue::GlobalValue()), E);
Richard Smith254a73d2011-10-28 22:34:42 +00002234 }
2235
Richard Smith11562c52011-10-28 17:51:58 +00002236 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2237 return StmtVisitorTy::Visit(E->getInitializer());
2238 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002239 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00002240 if (E->getNumInits() == 0)
2241 return DerivedZeroInitialization(E);
2242 if (E->getNumInits() == 1)
2243 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00002244 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002245 }
2246 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002247 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002248 }
2249 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002250 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002251 }
Richard Smith027bf112011-11-17 22:56:20 +00002252 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002253 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00002254 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002255
Richard Smithd62306a2011-11-10 06:34:14 +00002256 /// A member expression where the object is a prvalue is itself a prvalue.
2257 RetTy VisitMemberExpr(const MemberExpr *E) {
2258 assert(!E->isArrow() && "missing call to bound member function?");
2259
2260 CCValue Val;
2261 if (!Evaluate(Val, Info, E->getBase()))
2262 return false;
2263
2264 QualType BaseTy = E->getBase()->getType();
2265
2266 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00002267 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002268 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2269 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2270 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2271
Richard Smitha8105bc2012-01-06 16:39:00 +00002272 SubobjectDesignator Designator(BaseTy);
2273 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00002274
Richard Smithf57d8cb2011-12-09 22:58:01 +00002275 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smithd62306a2011-11-10 06:34:14 +00002276 DerivedSuccess(Val, E);
2277 }
2278
Richard Smith11562c52011-10-28 17:51:58 +00002279 RetTy VisitCastExpr(const CastExpr *E) {
2280 switch (E->getCastKind()) {
2281 default:
2282 break;
2283
2284 case CK_NoOp:
2285 return StmtVisitorTy::Visit(E->getSubExpr());
2286
2287 case CK_LValueToRValue: {
2288 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002289 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2290 return false;
2291 CCValue RVal;
2292 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2293 return false;
2294 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00002295 }
2296 }
2297
Richard Smithf57d8cb2011-12-09 22:58:01 +00002298 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002299 }
2300
Richard Smith4a678122011-10-24 18:44:57 +00002301 /// Visit a value which is evaluated, but whose value is ignored.
2302 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002303 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +00002304 if (!Evaluate(Scratch, Info, E))
2305 Info.EvalStatus.HasSideEffects = true;
2306 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002307};
2308
2309}
2310
2311//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002312// Common base class for lvalue and temporary evaluation.
2313//===----------------------------------------------------------------------===//
2314namespace {
2315template<class Derived>
2316class LValueExprEvaluatorBase
2317 : public ExprEvaluatorBase<Derived, bool> {
2318protected:
2319 LValue &Result;
2320 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2321 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2322
2323 bool Success(APValue::LValueBase B) {
2324 Result.set(B);
2325 return true;
2326 }
2327
2328public:
2329 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2330 ExprEvaluatorBaseTy(Info), Result(Result) {}
2331
2332 bool Success(const CCValue &V, const Expr *E) {
2333 Result.setFrom(V);
2334 return true;
2335 }
Richard Smith027bf112011-11-17 22:56:20 +00002336
Richard Smith027bf112011-11-17 22:56:20 +00002337 bool VisitMemberExpr(const MemberExpr *E) {
2338 // Handle non-static data members.
2339 QualType BaseTy;
2340 if (E->isArrow()) {
2341 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2342 return false;
2343 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00002344 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002345 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00002346 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2347 return false;
2348 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00002349 } else {
2350 if (!this->Visit(E->getBase()))
2351 return false;
2352 BaseTy = E->getBase()->getType();
2353 }
Richard Smith027bf112011-11-17 22:56:20 +00002354
2355 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2356 // FIXME: Handle IndirectFieldDecls
Richard Smithf57d8cb2011-12-09 22:58:01 +00002357 if (!FD) return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002358 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2359 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2360 (void)BaseTy;
2361
Richard Smitha8105bc2012-01-06 16:39:00 +00002362 HandleLValueMember(this->Info, E, Result, FD);
Richard Smith027bf112011-11-17 22:56:20 +00002363
2364 if (FD->getType()->isReferenceType()) {
2365 CCValue RefValue;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002366 if (!HandleLValueToRValueConversion(this->Info, E, FD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002367 RefValue))
2368 return false;
2369 return Success(RefValue, E);
2370 }
2371 return true;
2372 }
2373
2374 bool VisitBinaryOperator(const BinaryOperator *E) {
2375 switch (E->getOpcode()) {
2376 default:
2377 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2378
2379 case BO_PtrMemD:
2380 case BO_PtrMemI:
2381 return HandleMemberPointerAccess(this->Info, E, Result);
2382 }
2383 }
2384
2385 bool VisitCastExpr(const CastExpr *E) {
2386 switch (E->getCastKind()) {
2387 default:
2388 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2389
2390 case CK_DerivedToBase:
2391 case CK_UncheckedDerivedToBase: {
2392 if (!this->Visit(E->getSubExpr()))
2393 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002394
2395 // Now figure out the necessary offset to add to the base LV to get from
2396 // the derived class to the base class.
2397 QualType Type = E->getSubExpr()->getType();
2398
2399 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2400 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002401 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smith027bf112011-11-17 22:56:20 +00002402 *PathI))
2403 return false;
2404 Type = (*PathI)->getType();
2405 }
2406
2407 return true;
2408 }
2409 }
2410 }
2411};
2412}
2413
2414//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00002415// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00002416//
2417// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2418// function designators (in C), decl references to void objects (in C), and
2419// temporaries (if building with -Wno-address-of-temporary).
2420//
2421// LValue evaluation produces values comprising a base expression of one of the
2422// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00002423// - Declarations
2424// * VarDecl
2425// * FunctionDecl
2426// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00002427// * CompoundLiteralExpr in C
2428// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00002429// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00002430// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00002431// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00002432// * ObjCEncodeExpr
2433// * AddrLabelExpr
2434// * BlockExpr
2435// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00002436// - Locals and temporaries
2437// * Any Expr, with a Frame indicating the function in which the temporary was
2438// evaluated.
2439// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00002440//===----------------------------------------------------------------------===//
2441namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002442class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00002443 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00002444public:
Richard Smith027bf112011-11-17 22:56:20 +00002445 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2446 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00002447
Richard Smith11562c52011-10-28 17:51:58 +00002448 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2449
Peter Collingbournee9200682011-05-13 03:29:01 +00002450 bool VisitDeclRefExpr(const DeclRefExpr *E);
2451 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002452 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002453 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2454 bool VisitMemberExpr(const MemberExpr *E);
2455 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2456 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00002457 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002458 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2459 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002460
Peter Collingbournee9200682011-05-13 03:29:01 +00002461 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00002462 switch (E->getCastKind()) {
2463 default:
Richard Smith027bf112011-11-17 22:56:20 +00002464 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002465
Eli Friedmance3e02a2011-10-11 00:13:24 +00002466 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002467 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00002468 if (!Visit(E->getSubExpr()))
2469 return false;
2470 Result.Designator.setInvalid();
2471 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00002472
Richard Smith027bf112011-11-17 22:56:20 +00002473 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00002474 if (!Visit(E->getSubExpr()))
2475 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002476 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00002477 }
2478 }
Sebastian Redl12757ab2011-09-24 17:48:14 +00002479
Eli Friedman449fe542009-03-23 04:56:01 +00002480 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +00002481
Eli Friedman9a156e52008-11-12 09:44:48 +00002482};
2483} // end anonymous namespace
2484
Richard Smith11562c52011-10-28 17:51:58 +00002485/// Evaluate an expression as an lvalue. This can be legitimately called on
2486/// expressions which are not glvalues, in a few cases:
2487/// * function designators in C,
2488/// * "extern void" objects,
2489/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +00002490static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002491 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2492 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2493 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +00002494 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002495}
2496
Peter Collingbournee9200682011-05-13 03:29:01 +00002497bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002498 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2499 return Success(FD);
2500 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00002501 return VisitVarDecl(E, VD);
2502 return Error(E);
2503}
Richard Smith733237d2011-10-24 23:14:33 +00002504
Richard Smith11562c52011-10-28 17:51:58 +00002505bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +00002506 if (!VD->getType()->isReferenceType()) {
2507 if (isa<ParmVarDecl>(VD)) {
Richard Smithce40ad62011-11-12 22:28:03 +00002508 Result.set(VD, Info.CurrentCall);
Richard Smithfec09922011-11-01 16:57:24 +00002509 return true;
2510 }
Richard Smithce40ad62011-11-12 22:28:03 +00002511 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00002512 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00002513
Richard Smith0b0a0b62011-10-29 20:57:55 +00002514 CCValue V;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002515 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2516 return false;
2517 return Success(V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00002518}
2519
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002520bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2521 const MaterializeTemporaryExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002522 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002523 if (E->getType()->isRecordType())
Richard Smith027bf112011-11-17 22:56:20 +00002524 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2525
2526 Result.set(E, Info.CurrentCall);
2527 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2528 Result, E->GetTemporaryExpr());
2529 }
2530
2531 // Materialization of an lvalue temporary occurs when we need to force a copy
2532 // (for instance, if it's a bitfield).
2533 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2534 if (!Visit(E->GetTemporaryExpr()))
2535 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002536 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002537 Info.CurrentCall->Temporaries[E]))
2538 return false;
Richard Smithce40ad62011-11-12 22:28:03 +00002539 Result.set(E, Info.CurrentCall);
Richard Smith027bf112011-11-17 22:56:20 +00002540 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002541}
2542
Peter Collingbournee9200682011-05-13 03:29:01 +00002543bool
2544LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002545 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2546 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2547 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00002548 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002549}
2550
Richard Smith6e525142011-12-27 12:18:28 +00002551bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2552 if (E->isTypeOperand())
2553 return Success(E);
2554 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2555 if (RD && RD->isPolymorphic()) {
2556 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2557 << E->getExprOperand()->getType()
2558 << E->getExprOperand()->getSourceRange();
2559 return false;
2560 }
2561 return Success(E);
2562}
2563
Peter Collingbournee9200682011-05-13 03:29:01 +00002564bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002565 // Handle static data members.
2566 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2567 VisitIgnoredValue(E->getBase());
2568 return VisitVarDecl(E, VD);
2569 }
2570
Richard Smith254a73d2011-10-28 22:34:42 +00002571 // Handle static member functions.
2572 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2573 if (MD->isStatic()) {
2574 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00002575 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00002576 }
2577 }
2578
Richard Smithd62306a2011-11-10 06:34:14 +00002579 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00002580 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002581}
2582
Peter Collingbournee9200682011-05-13 03:29:01 +00002583bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002584 // FIXME: Deal with vectors as array subscript bases.
2585 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002586 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002587
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002588 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00002589 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002590
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002591 APSInt Index;
2592 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00002593 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002594 int64_t IndexValue
2595 = Index.isSigned() ? Index.getSExtValue()
2596 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002597
Richard Smitha8105bc2012-01-06 16:39:00 +00002598 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002599}
Eli Friedman9a156e52008-11-12 09:44:48 +00002600
Peter Collingbournee9200682011-05-13 03:29:01 +00002601bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00002602 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00002603}
2604
Eli Friedman9a156e52008-11-12 09:44:48 +00002605//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00002606// Pointer Evaluation
2607//===----------------------------------------------------------------------===//
2608
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002609namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002610class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002611 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00002612 LValue &Result;
2613
Peter Collingbournee9200682011-05-13 03:29:01 +00002614 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002615 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00002616 return true;
2617 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002618public:
Mike Stump11289f42009-09-09 15:08:12 +00002619
John McCall45d55e42010-05-07 21:00:08 +00002620 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002621 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00002622
Richard Smith0b0a0b62011-10-29 20:57:55 +00002623 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002624 Result.setFrom(V);
2625 return true;
2626 }
Richard Smithfddd3842011-12-30 21:15:51 +00002627 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00002628 return Success((Expr*)0);
2629 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002630
John McCall45d55e42010-05-07 21:00:08 +00002631 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002632 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00002633 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002634 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00002635 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002636 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00002637 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002638 bool VisitCallExpr(const CallExpr *E);
2639 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00002640 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00002641 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002642 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00002643 }
Richard Smithd62306a2011-11-10 06:34:14 +00002644 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2645 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002646 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002647 Result = *Info.CurrentCall->This;
2648 return true;
2649 }
John McCallc07a0c72011-02-17 10:25:35 +00002650
Eli Friedman449fe542009-03-23 04:56:01 +00002651 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002652};
Chris Lattner05706e882008-07-11 18:11:29 +00002653} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002654
John McCall45d55e42010-05-07 21:00:08 +00002655static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002656 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00002657 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00002658}
2659
John McCall45d55e42010-05-07 21:00:08 +00002660bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002661 if (E->getOpcode() != BO_Add &&
2662 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00002663 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00002664
Chris Lattner05706e882008-07-11 18:11:29 +00002665 const Expr *PExp = E->getLHS();
2666 const Expr *IExp = E->getRHS();
2667 if (IExp->getType()->isPointerType())
2668 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00002669
John McCall45d55e42010-05-07 21:00:08 +00002670 if (!EvaluatePointer(PExp, Result, Info))
2671 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002672
John McCall45d55e42010-05-07 21:00:08 +00002673 llvm::APSInt Offset;
2674 if (!EvaluateInteger(IExp, Offset, Info))
2675 return false;
2676 int64_t AdditionalOffset
2677 = Offset.isSigned() ? Offset.getSExtValue()
2678 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00002679 if (E->getOpcode() == BO_Sub)
2680 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00002681
Richard Smithd62306a2011-11-10 06:34:14 +00002682 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00002683 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
2684 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00002685}
Eli Friedman9a156e52008-11-12 09:44:48 +00002686
John McCall45d55e42010-05-07 21:00:08 +00002687bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2688 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002689}
Mike Stump11289f42009-09-09 15:08:12 +00002690
Peter Collingbournee9200682011-05-13 03:29:01 +00002691bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2692 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00002693
Eli Friedman847a2bc2009-12-27 05:43:15 +00002694 switch (E->getCastKind()) {
2695 default:
2696 break;
2697
John McCalle3027922010-08-25 11:45:40 +00002698 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00002699 case CK_CPointerToObjCPointerCast:
2700 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00002701 case CK_AnyPointerToBlockPointerCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002702 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2703 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2704 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00002705 if (!E->getType()->isVoidPointerType()) {
2706 if (SubExpr->getType()->isVoidPointerType())
2707 CCEDiag(E, diag::note_constexpr_invalid_cast)
2708 << 3 << SubExpr->getType();
2709 else
2710 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2711 }
Richard Smith96e0c102011-11-04 02:25:55 +00002712 if (!Visit(SubExpr))
2713 return false;
2714 Result.Designator.setInvalid();
2715 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00002716
Anders Carlsson18275092010-10-31 20:41:46 +00002717 case CK_DerivedToBase:
2718 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002719 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00002720 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002721 if (!Result.Base && Result.Offset.isZero())
2722 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00002723
Richard Smithd62306a2011-11-10 06:34:14 +00002724 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00002725 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00002726 QualType Type =
2727 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00002728
Richard Smithd62306a2011-11-10 06:34:14 +00002729 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00002730 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002731 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2732 *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00002733 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002734 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00002735 }
2736
Anders Carlsson18275092010-10-31 20:41:46 +00002737 return true;
2738 }
2739
Richard Smith027bf112011-11-17 22:56:20 +00002740 case CK_BaseToDerived:
2741 if (!Visit(E->getSubExpr()))
2742 return false;
2743 if (!Result.Base && Result.Offset.isZero())
2744 return true;
2745 return HandleBaseToDerivedCast(Info, E, Result);
2746
Richard Smith0b0a0b62011-10-29 20:57:55 +00002747 case CK_NullToPointer:
Richard Smithfddd3842011-12-30 21:15:51 +00002748 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00002749
John McCalle3027922010-08-25 11:45:40 +00002750 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00002751 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2752
Richard Smith0b0a0b62011-10-29 20:57:55 +00002753 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00002754 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00002755 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00002756
John McCall45d55e42010-05-07 21:00:08 +00002757 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002758 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2759 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00002760 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002761 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithfec09922011-11-01 16:57:24 +00002762 Result.Frame = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00002763 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00002764 return true;
2765 } else {
2766 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002767 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00002768 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00002769 }
2770 }
John McCalle3027922010-08-25 11:45:40 +00002771 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00002772 if (SubExpr->isGLValue()) {
2773 if (!EvaluateLValue(SubExpr, Result, Info))
2774 return false;
2775 } else {
2776 Result.set(SubExpr, Info.CurrentCall);
2777 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2778 Info, Result, SubExpr))
2779 return false;
2780 }
Richard Smith96e0c102011-11-04 02:25:55 +00002781 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00002782 if (const ConstantArrayType *CAT
2783 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
2784 Result.addArray(Info, E, CAT);
2785 else
2786 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00002787 return true;
Richard Smithdd785442011-10-31 20:57:44 +00002788
John McCalle3027922010-08-25 11:45:40 +00002789 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00002790 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002791 }
2792
Richard Smith11562c52011-10-28 17:51:58 +00002793 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00002794}
Chris Lattner05706e882008-07-11 18:11:29 +00002795
Peter Collingbournee9200682011-05-13 03:29:01 +00002796bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00002797 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00002798 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00002799
Peter Collingbournee9200682011-05-13 03:29:01 +00002800 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002801}
Chris Lattner05706e882008-07-11 18:11:29 +00002802
2803//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002804// Member Pointer Evaluation
2805//===----------------------------------------------------------------------===//
2806
2807namespace {
2808class MemberPointerExprEvaluator
2809 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2810 MemberPtr &Result;
2811
2812 bool Success(const ValueDecl *D) {
2813 Result = MemberPtr(D);
2814 return true;
2815 }
2816public:
2817
2818 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2819 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2820
2821 bool Success(const CCValue &V, const Expr *E) {
2822 Result.setFrom(V);
2823 return true;
2824 }
Richard Smithfddd3842011-12-30 21:15:51 +00002825 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002826 return Success((const ValueDecl*)0);
2827 }
2828
2829 bool VisitCastExpr(const CastExpr *E);
2830 bool VisitUnaryAddrOf(const UnaryOperator *E);
2831};
2832} // end anonymous namespace
2833
2834static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2835 EvalInfo &Info) {
2836 assert(E->isRValue() && E->getType()->isMemberPointerType());
2837 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2838}
2839
2840bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2841 switch (E->getCastKind()) {
2842 default:
2843 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2844
2845 case CK_NullToMemberPointer:
Richard Smithfddd3842011-12-30 21:15:51 +00002846 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00002847
2848 case CK_BaseToDerivedMemberPointer: {
2849 if (!Visit(E->getSubExpr()))
2850 return false;
2851 if (E->path_empty())
2852 return true;
2853 // Base-to-derived member pointer casts store the path in derived-to-base
2854 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2855 // the wrong end of the derived->base arc, so stagger the path by one class.
2856 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2857 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2858 PathI != PathE; ++PathI) {
2859 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2860 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2861 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002862 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002863 }
2864 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2865 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002866 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002867 return true;
2868 }
2869
2870 case CK_DerivedToBaseMemberPointer:
2871 if (!Visit(E->getSubExpr()))
2872 return false;
2873 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2874 PathE = E->path_end(); PathI != PathE; ++PathI) {
2875 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2876 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2877 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002878 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002879 }
2880 return true;
2881 }
2882}
2883
2884bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2885 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
2886 // member can be formed.
2887 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
2888}
2889
2890//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00002891// Record Evaluation
2892//===----------------------------------------------------------------------===//
2893
2894namespace {
2895 class RecordExprEvaluator
2896 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
2897 const LValue &This;
2898 APValue &Result;
2899 public:
2900
2901 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
2902 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
2903
2904 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002905 return CheckConstantExpression(Info, E, V, Result);
Richard Smithd62306a2011-11-10 06:34:14 +00002906 }
Richard Smithfddd3842011-12-30 21:15:51 +00002907 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00002908
Richard Smithe97cbd72011-11-11 04:05:33 +00002909 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00002910 bool VisitInitListExpr(const InitListExpr *E);
2911 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
2912 };
2913}
2914
Richard Smithfddd3842011-12-30 21:15:51 +00002915/// Perform zero-initialization on an object of non-union class type.
2916/// C++11 [dcl.init]p5:
2917/// To zero-initialize an object or reference of type T means:
2918/// [...]
2919/// -- if T is a (possibly cv-qualified) non-union class type,
2920/// each non-static data member and each base-class subobject is
2921/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00002922static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
2923 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00002924 const LValue &This, APValue &Result) {
2925 assert(!RD->isUnion() && "Expected non-union class type");
2926 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
2927 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
2928 std::distance(RD->field_begin(), RD->field_end()));
2929
2930 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2931
2932 if (CD) {
2933 unsigned Index = 0;
2934 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00002935 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00002936 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
2937 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00002938 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
2939 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00002940 Result.getStructBase(Index)))
2941 return false;
2942 }
2943 }
2944
Richard Smitha8105bc2012-01-06 16:39:00 +00002945 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
2946 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00002947 // -- if T is a reference type, no initialization is performed.
2948 if ((*I)->getType()->isReferenceType())
2949 continue;
2950
2951 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00002952 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smithfddd3842011-12-30 21:15:51 +00002953
2954 ImplicitValueInitExpr VIE((*I)->getType());
2955 if (!EvaluateConstantExpression(
2956 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
2957 return false;
2958 }
2959
2960 return true;
2961}
2962
2963bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
2964 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2965 if (RD->isUnion()) {
2966 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
2967 // object's first non-static named data member is zero-initialized
2968 RecordDecl::field_iterator I = RD->field_begin();
2969 if (I == RD->field_end()) {
2970 Result = APValue((const FieldDecl*)0);
2971 return true;
2972 }
2973
2974 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00002975 HandleLValueMember(Info, E, Subobject, *I);
Richard Smithfddd3842011-12-30 21:15:51 +00002976 Result = APValue(*I);
2977 ImplicitValueInitExpr VIE((*I)->getType());
2978 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2979 Subobject, &VIE);
2980 }
2981
Richard Smitha8105bc2012-01-06 16:39:00 +00002982 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00002983}
2984
Richard Smithe97cbd72011-11-11 04:05:33 +00002985bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
2986 switch (E->getCastKind()) {
2987 default:
2988 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2989
2990 case CK_ConstructorConversion:
2991 return Visit(E->getSubExpr());
2992
2993 case CK_DerivedToBase:
2994 case CK_UncheckedDerivedToBase: {
2995 CCValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002996 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00002997 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002998 if (!DerivedObject.isStruct())
2999 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00003000
3001 // Derived-to-base rvalue conversion: just slice off the derived part.
3002 APValue *Value = &DerivedObject;
3003 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3004 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3005 PathE = E->path_end(); PathI != PathE; ++PathI) {
3006 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3007 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3008 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3009 RD = Base;
3010 }
3011 Result = *Value;
3012 return true;
3013 }
3014 }
3015}
3016
Richard Smithd62306a2011-11-10 06:34:14 +00003017bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3018 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3019 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3020
3021 if (RD->isUnion()) {
3022 Result = APValue(E->getInitializedFieldInUnion());
3023 if (!E->getNumInits())
3024 return true;
3025 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00003026 HandleLValueMember(Info, E->getInit(0), Subobject,
3027 E->getInitializedFieldInUnion(), &Layout);
Richard Smithd62306a2011-11-10 06:34:14 +00003028 return EvaluateConstantExpression(Result.getUnionValue(), Info,
3029 Subobject, E->getInit(0));
3030 }
3031
3032 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3033 "initializer list for class with base classes");
3034 Result = APValue(APValue::UninitStruct(), 0,
3035 std::distance(RD->field_begin(), RD->field_end()));
3036 unsigned ElementNo = 0;
3037 for (RecordDecl::field_iterator Field = RD->field_begin(),
3038 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3039 // Anonymous bit-fields are not considered members of the class for
3040 // purposes of aggregate initialization.
3041 if (Field->isUnnamedBitfield())
3042 continue;
3043
3044 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00003045
3046 if (ElementNo < E->getNumInits()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003047 HandleLValueMember(Info, E->getInit(ElementNo), Subobject, *Field,
3048 &Layout);
Richard Smithd62306a2011-11-10 06:34:14 +00003049 if (!EvaluateConstantExpression(
3050 Result.getStructField((*Field)->getFieldIndex()),
3051 Info, Subobject, E->getInit(ElementNo++)))
3052 return false;
3053 } else {
3054 // Perform an implicit value-initialization for members beyond the end of
3055 // the initializer list.
Richard Smitha8105bc2012-01-06 16:39:00 +00003056 HandleLValueMember(Info, E, Subobject, *Field, &Layout);
Richard Smithd62306a2011-11-10 06:34:14 +00003057 ImplicitValueInitExpr VIE(Field->getType());
3058 if (!EvaluateConstantExpression(
3059 Result.getStructField((*Field)->getFieldIndex()),
3060 Info, Subobject, &VIE))
3061 return false;
3062 }
3063 }
3064
3065 return true;
3066}
3067
3068bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3069 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithfddd3842011-12-30 21:15:51 +00003070 bool ZeroInit = E->requiresZeroInitialization();
3071 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
3072 if (ZeroInit)
3073 return ZeroInitialization(E);
3074
Richard Smithcc36f692011-12-22 02:22:31 +00003075 const CXXRecordDecl *RD = FD->getParent();
3076 if (RD->isUnion())
3077 Result = APValue((FieldDecl*)0);
3078 else
3079 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3080 std::distance(RD->field_begin(), RD->field_end()));
3081 return true;
3082 }
3083
Richard Smithd62306a2011-11-10 06:34:14 +00003084 const FunctionDecl *Definition = 0;
3085 FD->getBody(Definition);
3086
Richard Smith357362d2011-12-13 06:39:58 +00003087 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3088 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003089
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003090 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00003091 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00003092 if (const MaterializeTemporaryExpr *ME
3093 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3094 return Visit(ME->GetTemporaryExpr());
3095
Richard Smithfddd3842011-12-30 21:15:51 +00003096 if (ZeroInit && !ZeroInitialization(E))
3097 return false;
3098
Richard Smithd62306a2011-11-10 06:34:14 +00003099 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003100 return HandleConstructorCall(E, This, Args,
3101 cast<CXXConstructorDecl>(Definition), Info,
3102 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00003103}
3104
3105static bool EvaluateRecord(const Expr *E, const LValue &This,
3106 APValue &Result, EvalInfo &Info) {
3107 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00003108 "can't evaluate expression as a record rvalue");
3109 return RecordExprEvaluator(Info, This, Result).Visit(E);
3110}
3111
3112//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003113// Temporary Evaluation
3114//
3115// Temporaries are represented in the AST as rvalues, but generally behave like
3116// lvalues. The full-object of which the temporary is a subobject is implicitly
3117// materialized so that a reference can bind to it.
3118//===----------------------------------------------------------------------===//
3119namespace {
3120class TemporaryExprEvaluator
3121 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3122public:
3123 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3124 LValueExprEvaluatorBaseTy(Info, Result) {}
3125
3126 /// Visit an expression which constructs the value of this temporary.
3127 bool VisitConstructExpr(const Expr *E) {
3128 Result.set(E, Info.CurrentCall);
3129 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
3130 Result, E);
3131 }
3132
3133 bool VisitCastExpr(const CastExpr *E) {
3134 switch (E->getCastKind()) {
3135 default:
3136 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3137
3138 case CK_ConstructorConversion:
3139 return VisitConstructExpr(E->getSubExpr());
3140 }
3141 }
3142 bool VisitInitListExpr(const InitListExpr *E) {
3143 return VisitConstructExpr(E);
3144 }
3145 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3146 return VisitConstructExpr(E);
3147 }
3148 bool VisitCallExpr(const CallExpr *E) {
3149 return VisitConstructExpr(E);
3150 }
3151};
3152} // end anonymous namespace
3153
3154/// Evaluate an expression of record type as a temporary.
3155static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00003156 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00003157 return TemporaryExprEvaluator(Info, Result).Visit(E);
3158}
3159
3160//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003161// Vector Evaluation
3162//===----------------------------------------------------------------------===//
3163
3164namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003165 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00003166 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3167 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003168 public:
Mike Stump11289f42009-09-09 15:08:12 +00003169
Richard Smith2d406342011-10-22 21:10:00 +00003170 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3171 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00003172
Richard Smith2d406342011-10-22 21:10:00 +00003173 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3174 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3175 // FIXME: remove this APValue copy.
3176 Result = APValue(V.data(), V.size());
3177 return true;
3178 }
Richard Smithed5165f2011-11-04 05:33:44 +00003179 bool Success(const CCValue &V, const Expr *E) {
3180 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00003181 Result = V;
3182 return true;
3183 }
Richard Smithfddd3842011-12-30 21:15:51 +00003184 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00003185
Richard Smith2d406342011-10-22 21:10:00 +00003186 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00003187 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00003188 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00003189 bool VisitInitListExpr(const InitListExpr *E);
3190 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003191 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00003192 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00003193 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003194 };
3195} // end anonymous namespace
3196
3197static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003198 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00003199 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003200}
3201
Richard Smith2d406342011-10-22 21:10:00 +00003202bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3203 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00003204 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00003205
Richard Smith161f09a2011-12-06 22:44:34 +00003206 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00003207 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003208
Eli Friedmanc757de22011-03-25 00:43:55 +00003209 switch (E->getCastKind()) {
3210 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00003211 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00003212 if (SETy->isIntegerType()) {
3213 APSInt IntResult;
3214 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003215 return false;
Richard Smith2d406342011-10-22 21:10:00 +00003216 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00003217 } else if (SETy->isRealFloatingType()) {
3218 APFloat F(0.0);
3219 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003220 return false;
Richard Smith2d406342011-10-22 21:10:00 +00003221 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00003222 } else {
Richard Smith2d406342011-10-22 21:10:00 +00003223 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003224 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00003225
3226 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00003227 SmallVector<APValue, 4> Elts(NElts, Val);
3228 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00003229 }
Eli Friedman803acb32011-12-22 03:51:45 +00003230 case CK_BitCast: {
3231 // Evaluate the operand into an APInt we can extract from.
3232 llvm::APInt SValInt;
3233 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3234 return false;
3235 // Extract the elements
3236 QualType EltTy = VTy->getElementType();
3237 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3238 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3239 SmallVector<APValue, 4> Elts;
3240 if (EltTy->isRealFloatingType()) {
3241 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3242 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3243 unsigned FloatEltSize = EltSize;
3244 if (&Sem == &APFloat::x87DoubleExtended)
3245 FloatEltSize = 80;
3246 for (unsigned i = 0; i < NElts; i++) {
3247 llvm::APInt Elt;
3248 if (BigEndian)
3249 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3250 else
3251 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3252 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3253 }
3254 } else if (EltTy->isIntegerType()) {
3255 for (unsigned i = 0; i < NElts; i++) {
3256 llvm::APInt Elt;
3257 if (BigEndian)
3258 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3259 else
3260 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3261 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3262 }
3263 } else {
3264 return Error(E);
3265 }
3266 return Success(Elts, E);
3267 }
Eli Friedmanc757de22011-03-25 00:43:55 +00003268 default:
Richard Smith11562c52011-10-28 17:51:58 +00003269 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003270 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003271}
3272
Richard Smith2d406342011-10-22 21:10:00 +00003273bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003274VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00003275 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003276 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00003277 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00003278
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003279 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003280 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003281
Eli Friedmanb9c71292012-01-03 23:24:20 +00003282 // The number of initializers can be less than the number of
3283 // vector elements. For OpenCL, this can be due to nested vector
3284 // initialization. For GCC compatibility, missing trailing elements
3285 // should be initialized with zeroes.
3286 unsigned CountInits = 0, CountElts = 0;
3287 while (CountElts < NumElements) {
3288 // Handle nested vector initialization.
3289 if (CountInits < NumInits
3290 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3291 APValue v;
3292 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3293 return Error(E);
3294 unsigned vlen = v.getVectorLength();
3295 for (unsigned j = 0; j < vlen; j++)
3296 Elements.push_back(v.getVectorElt(j));
3297 CountElts += vlen;
3298 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003299 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00003300 if (CountInits < NumInits) {
3301 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3302 return Error(E);
3303 } else // trailing integer zero.
3304 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3305 Elements.push_back(APValue(sInt));
3306 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003307 } else {
3308 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00003309 if (CountInits < NumInits) {
3310 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3311 return Error(E);
3312 } else // trailing float zero.
3313 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3314 Elements.push_back(APValue(f));
3315 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00003316 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00003317 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003318 }
Richard Smith2d406342011-10-22 21:10:00 +00003319 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003320}
3321
Richard Smith2d406342011-10-22 21:10:00 +00003322bool
Richard Smithfddd3842011-12-30 21:15:51 +00003323VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00003324 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00003325 QualType EltTy = VT->getElementType();
3326 APValue ZeroElement;
3327 if (EltTy->isIntegerType())
3328 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3329 else
3330 ZeroElement =
3331 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3332
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003333 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00003334 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003335}
3336
Richard Smith2d406342011-10-22 21:10:00 +00003337bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00003338 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00003339 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003340}
3341
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003342//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00003343// Array Evaluation
3344//===----------------------------------------------------------------------===//
3345
3346namespace {
3347 class ArrayExprEvaluator
3348 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00003349 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00003350 APValue &Result;
3351 public:
3352
Richard Smithd62306a2011-11-10 06:34:14 +00003353 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3354 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00003355
3356 bool Success(const APValue &V, const Expr *E) {
3357 assert(V.isArray() && "Expected array type");
3358 Result = V;
3359 return true;
3360 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003361
Richard Smithfddd3842011-12-30 21:15:51 +00003362 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003363 const ConstantArrayType *CAT =
3364 Info.Ctx.getAsConstantArrayType(E->getType());
3365 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003366 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003367
3368 Result = APValue(APValue::UninitArray(), 0,
3369 CAT->getSize().getZExtValue());
3370 if (!Result.hasArrayFiller()) return true;
3371
Richard Smithfddd3842011-12-30 21:15:51 +00003372 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00003373 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00003374 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00003375 ImplicitValueInitExpr VIE(CAT->getElementType());
3376 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3377 Subobject, &VIE);
3378 }
3379
Richard Smithf3e9e432011-11-07 09:22:26 +00003380 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00003381 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003382 };
3383} // end anonymous namespace
3384
Richard Smithd62306a2011-11-10 06:34:14 +00003385static bool EvaluateArray(const Expr *E, const LValue &This,
3386 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00003387 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00003388 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003389}
3390
3391bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3392 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3393 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003394 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003395
Richard Smithca2cfbf2011-12-22 01:07:19 +00003396 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3397 // an appropriately-typed string literal enclosed in braces.
3398 if (E->getNumInits() == 1 && CAT->getElementType()->isAnyCharacterType() &&
3399 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3400 LValue LV;
3401 if (!EvaluateLValue(E->getInit(0), LV, Info))
3402 return false;
3403 uint64_t NumElements = CAT->getSize().getZExtValue();
3404 Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3405
3406 // Copy the string literal into the array. FIXME: Do this better.
Richard Smitha8105bc2012-01-06 16:39:00 +00003407 LV.addArray(Info, E, CAT);
Richard Smithca2cfbf2011-12-22 01:07:19 +00003408 for (uint64_t I = 0; I < NumElements; ++I) {
3409 CCValue Char;
3410 if (!HandleLValueToRValueConversion(Info, E->getInit(0),
3411 CAT->getElementType(), LV, Char))
3412 return false;
3413 if (!CheckConstantExpression(Info, E->getInit(0), Char,
3414 Result.getArrayInitializedElt(I)))
3415 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003416 if (!HandleLValueArrayAdjustment(Info, E->getInit(0), LV,
3417 CAT->getElementType(), 1))
Richard Smithca2cfbf2011-12-22 01:07:19 +00003418 return false;
3419 }
3420 return true;
3421 }
3422
Richard Smithf3e9e432011-11-07 09:22:26 +00003423 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3424 CAT->getSize().getZExtValue());
Richard Smithd62306a2011-11-10 06:34:14 +00003425 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00003426 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00003427 unsigned Index = 0;
Richard Smithf3e9e432011-11-07 09:22:26 +00003428 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smithd62306a2011-11-10 06:34:14 +00003429 I != End; ++I, ++Index) {
3430 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
3431 Info, Subobject, cast<Expr>(*I)))
Richard Smithf3e9e432011-11-07 09:22:26 +00003432 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003433 if (!HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3434 CAT->getElementType(), 1))
Richard Smithd62306a2011-11-10 06:34:14 +00003435 return false;
3436 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003437
3438 if (!Result.hasArrayFiller()) return true;
3439 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smithd62306a2011-11-10 06:34:14 +00003440 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3441 // but sometimes does:
3442 // struct S { constexpr S() : p(&p) {} void *p; };
3443 // S s[10] = {};
Richard Smithf3e9e432011-11-07 09:22:26 +00003444 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smithd62306a2011-11-10 06:34:14 +00003445 Subobject, E->getArrayFiller());
Richard Smithf3e9e432011-11-07 09:22:26 +00003446}
3447
Richard Smith027bf112011-11-17 22:56:20 +00003448bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3449 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3450 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003451 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003452
3453 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3454 if (!Result.hasArrayFiller())
3455 return true;
3456
3457 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00003458
Richard Smithfddd3842011-12-30 21:15:51 +00003459 bool ZeroInit = E->requiresZeroInitialization();
3460 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
3461 if (ZeroInit) {
3462 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00003463 Subobject.addArray(Info, E, CAT);
Richard Smithfddd3842011-12-30 21:15:51 +00003464 ImplicitValueInitExpr VIE(CAT->getElementType());
3465 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3466 Subobject, &VIE);
3467 }
3468
Richard Smithcc36f692011-12-22 02:22:31 +00003469 const CXXRecordDecl *RD = FD->getParent();
3470 if (RD->isUnion())
3471 Result.getArrayFiller() = APValue((FieldDecl*)0);
3472 else
3473 Result.getArrayFiller() =
3474 APValue(APValue::UninitStruct(), RD->getNumBases(),
3475 std::distance(RD->field_begin(), RD->field_end()));
3476 return true;
3477 }
3478
Richard Smith027bf112011-11-17 22:56:20 +00003479 const FunctionDecl *Definition = 0;
3480 FD->getBody(Definition);
3481
Richard Smith357362d2011-12-13 06:39:58 +00003482 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3483 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003484
3485 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3486 // but sometimes does:
3487 // struct S { constexpr S() : p(&p) {} void *p; };
3488 // S s[10];
3489 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00003490 Subobject.addArray(Info, E, CAT);
Richard Smithfddd3842011-12-30 21:15:51 +00003491
3492 if (ZeroInit) {
3493 ImplicitValueInitExpr VIE(CAT->getElementType());
3494 if (!EvaluateConstantExpression(Result.getArrayFiller(), Info, Subobject,
3495 &VIE))
3496 return false;
3497 }
3498
Richard Smith027bf112011-11-17 22:56:20 +00003499 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003500 return HandleConstructorCall(E, Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00003501 cast<CXXConstructorDecl>(Definition),
3502 Info, Result.getArrayFiller());
3503}
3504
Richard Smithf3e9e432011-11-07 09:22:26 +00003505//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003506// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003507//
3508// As a GNU extension, we support casting pointers to sufficiently-wide integer
3509// types and back in constant folding. Integer values are thus represented
3510// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00003511//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003512
3513namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003514class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003515 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003516 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003517public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00003518 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003519 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00003520
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003521 bool Success(const llvm::APSInt &SI, const Expr *E) {
3522 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00003523 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003524 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003525 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003526 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003527 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003528 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003529 return true;
3530 }
3531
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003532 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003533 assert(E->getType()->isIntegralOrEnumerationType() &&
3534 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003535 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003536 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003537 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00003538 Result.getInt().setIsUnsigned(
3539 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003540 return true;
3541 }
3542
3543 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003544 assert(E->getType()->isIntegralOrEnumerationType() &&
3545 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003546 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003547 return true;
3548 }
3549
Ken Dyckdbc01912011-03-11 02:13:43 +00003550 bool Success(CharUnits Size, const Expr *E) {
3551 return Success(Size.getQuantity(), E);
3552 }
3553
Richard Smith0b0a0b62011-10-29 20:57:55 +00003554 bool Success(const CCValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00003555 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00003556 Result = V;
3557 return true;
3558 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003559 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00003560 }
Mike Stump11289f42009-09-09 15:08:12 +00003561
Richard Smithfddd3842011-12-30 21:15:51 +00003562 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00003563
Peter Collingbournee9200682011-05-13 03:29:01 +00003564 //===--------------------------------------------------------------------===//
3565 // Visitor Methods
3566 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003567
Chris Lattner7174bf32008-07-12 00:38:25 +00003568 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003569 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00003570 }
3571 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003572 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00003573 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003574
3575 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3576 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003577 if (CheckReferencedDecl(E, E->getDecl()))
3578 return true;
3579
3580 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003581 }
3582 bool VisitMemberExpr(const MemberExpr *E) {
3583 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00003584 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003585 return true;
3586 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003587
3588 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003589 }
3590
Peter Collingbournee9200682011-05-13 03:29:01 +00003591 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00003592 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00003593 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00003594 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00003595
Peter Collingbournee9200682011-05-13 03:29:01 +00003596 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003597 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00003598
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003599 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003600 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003601 }
Mike Stump11289f42009-09-09 15:08:12 +00003602
Richard Smith4ce706a2011-10-11 21:43:33 +00003603 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00003604 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003605 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003606 }
3607
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003608 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003609 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003610 }
3611
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003612 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3613 return Success(E->getValue(), E);
3614 }
3615
John Wiegley6242b6a2011-04-28 00:16:57 +00003616 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3617 return Success(E->getValue(), E);
3618 }
3619
John Wiegleyf9f65842011-04-25 06:54:41 +00003620 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3621 return Success(E->getValue(), E);
3622 }
3623
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003624 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003625 bool VisitUnaryImag(const UnaryOperator *E);
3626
Sebastian Redl5f0180d2010-09-10 20:55:47 +00003627 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003628 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00003629
Chris Lattnerf8d7f722008-07-11 21:24:13 +00003630private:
Ken Dyck160146e2010-01-27 17:10:57 +00003631 CharUnits GetAlignOfExpr(const Expr *E);
3632 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00003633 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00003634 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003635 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00003636};
Chris Lattner05706e882008-07-11 18:11:29 +00003637} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003638
Richard Smith11562c52011-10-28 17:51:58 +00003639/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3640/// produce either the integer value or a pointer.
3641///
3642/// GCC has a heinous extension which folds casts between pointer types and
3643/// pointer-sized integral types. We support this by allowing the evaluation of
3644/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3645/// Some simple arithmetic on such values is supported (they are treated much
3646/// like char*).
Richard Smithf57d8cb2011-12-09 22:58:01 +00003647static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00003648 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003649 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003650 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00003651}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003652
Richard Smithf57d8cb2011-12-09 22:58:01 +00003653static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003654 CCValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003655 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00003656 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003657 if (!Val.isInt()) {
3658 // FIXME: It would be better to produce the diagnostic for casting
3659 // a pointer to an integer.
Richard Smith92b1ce02011-12-12 09:28:41 +00003660 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003661 return false;
3662 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003663 Result = Val.getInt();
3664 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003665}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003666
Richard Smithf57d8cb2011-12-09 22:58:01 +00003667/// Check whether the given declaration can be directly converted to an integral
3668/// rvalue. If not, no diagnostic is produced; there are other things we can
3669/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003670bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00003671 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003672 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003673 // Check for signedness/width mismatches between E type and ECD value.
3674 bool SameSign = (ECD->getInitVal().isSigned()
3675 == E->getType()->isSignedIntegerOrEnumerationType());
3676 bool SameWidth = (ECD->getInitVal().getBitWidth()
3677 == Info.Ctx.getIntWidth(E->getType()));
3678 if (SameSign && SameWidth)
3679 return Success(ECD->getInitVal(), E);
3680 else {
3681 // Get rid of mismatch (otherwise Success assertions will fail)
3682 // by computing a new value matching the type of E.
3683 llvm::APSInt Val = ECD->getInitVal();
3684 if (!SameSign)
3685 Val.setIsSigned(!ECD->getInitVal().isSigned());
3686 if (!SameWidth)
3687 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3688 return Success(Val, E);
3689 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003690 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003691 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00003692}
3693
Chris Lattner86ee2862008-10-06 06:40:35 +00003694/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3695/// as GCC.
3696static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3697 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003698 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00003699 enum gcc_type_class {
3700 no_type_class = -1,
3701 void_type_class, integer_type_class, char_type_class,
3702 enumeral_type_class, boolean_type_class,
3703 pointer_type_class, reference_type_class, offset_type_class,
3704 real_type_class, complex_type_class,
3705 function_type_class, method_type_class,
3706 record_type_class, union_type_class,
3707 array_type_class, string_type_class,
3708 lang_type_class
3709 };
Mike Stump11289f42009-09-09 15:08:12 +00003710
3711 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00003712 // ideal, however it is what gcc does.
3713 if (E->getNumArgs() == 0)
3714 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00003715
Chris Lattner86ee2862008-10-06 06:40:35 +00003716 QualType ArgTy = E->getArg(0)->getType();
3717 if (ArgTy->isVoidType())
3718 return void_type_class;
3719 else if (ArgTy->isEnumeralType())
3720 return enumeral_type_class;
3721 else if (ArgTy->isBooleanType())
3722 return boolean_type_class;
3723 else if (ArgTy->isCharType())
3724 return string_type_class; // gcc doesn't appear to use char_type_class
3725 else if (ArgTy->isIntegerType())
3726 return integer_type_class;
3727 else if (ArgTy->isPointerType())
3728 return pointer_type_class;
3729 else if (ArgTy->isReferenceType())
3730 return reference_type_class;
3731 else if (ArgTy->isRealType())
3732 return real_type_class;
3733 else if (ArgTy->isComplexType())
3734 return complex_type_class;
3735 else if (ArgTy->isFunctionType())
3736 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00003737 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00003738 return record_type_class;
3739 else if (ArgTy->isUnionType())
3740 return union_type_class;
3741 else if (ArgTy->isArrayType())
3742 return array_type_class;
3743 else if (ArgTy->isUnionType())
3744 return union_type_class;
3745 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00003746 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00003747 return -1;
3748}
3749
Richard Smith5fab0c92011-12-28 19:48:30 +00003750/// EvaluateBuiltinConstantPForLValue - Determine the result of
3751/// __builtin_constant_p when applied to the given lvalue.
3752///
3753/// An lvalue is only "constant" if it is a pointer or reference to the first
3754/// character of a string literal.
3755template<typename LValue>
3756static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
3757 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
3758 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3759}
3760
3761/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
3762/// GCC as we can manage.
3763static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
3764 QualType ArgType = Arg->getType();
3765
3766 // __builtin_constant_p always has one operand. The rules which gcc follows
3767 // are not precisely documented, but are as follows:
3768 //
3769 // - If the operand is of integral, floating, complex or enumeration type,
3770 // and can be folded to a known value of that type, it returns 1.
3771 // - If the operand and can be folded to a pointer to the first character
3772 // of a string literal (or such a pointer cast to an integral type), it
3773 // returns 1.
3774 //
3775 // Otherwise, it returns 0.
3776 //
3777 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3778 // its support for this does not currently work.
3779 if (ArgType->isIntegralOrEnumerationType()) {
3780 Expr::EvalResult Result;
3781 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
3782 return false;
3783
3784 APValue &V = Result.Val;
3785 if (V.getKind() == APValue::Int)
3786 return true;
3787
3788 return EvaluateBuiltinConstantPForLValue(V);
3789 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3790 return Arg->isEvaluatable(Ctx);
3791 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3792 LValue LV;
3793 Expr::EvalStatus Status;
3794 EvalInfo Info(Ctx, Status);
3795 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
3796 : EvaluatePointer(Arg, LV, Info)) &&
3797 !Status.HasSideEffects)
3798 return EvaluateBuiltinConstantPForLValue(LV);
3799 }
3800
3801 // Anything else isn't considered to be sufficiently constant.
3802 return false;
3803}
3804
John McCall95007602010-05-10 23:27:23 +00003805/// Retrieves the "underlying object type" of the given expression,
3806/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00003807QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3808 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3809 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00003810 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00003811 } else if (const Expr *E = B.get<const Expr*>()) {
3812 if (isa<CompoundLiteralExpr>(E))
3813 return E->getType();
John McCall95007602010-05-10 23:27:23 +00003814 }
3815
3816 return QualType();
3817}
3818
Peter Collingbournee9200682011-05-13 03:29:01 +00003819bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00003820 // TODO: Perhaps we should let LLVM lower this?
3821 LValue Base;
3822 if (!EvaluatePointer(E->getArg(0), Base, Info))
3823 return false;
3824
3825 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00003826 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00003827
Richard Smithce40ad62011-11-12 22:28:03 +00003828 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00003829 if (T.isNull() ||
3830 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00003831 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00003832 T->isVariablyModifiedType() ||
3833 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003834 return Error(E);
John McCall95007602010-05-10 23:27:23 +00003835
3836 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3837 CharUnits Offset = Base.getLValueOffset();
3838
3839 if (!Offset.isNegative() && Offset <= Size)
3840 Size -= Offset;
3841 else
3842 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00003843 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00003844}
3845
Peter Collingbournee9200682011-05-13 03:29:01 +00003846bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003847 switch (E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003848 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00003849 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003850
3851 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00003852 if (TryEvaluateBuiltinObjectSize(E))
3853 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00003854
Eric Christopher99469702010-01-19 22:58:35 +00003855 // If evaluating the argument has side-effects we can't determine
3856 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003857 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00003858 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00003859 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00003860 return Success(0, E);
3861 }
Mike Stump876387b2009-10-27 22:09:17 +00003862
Richard Smithf57d8cb2011-12-09 22:58:01 +00003863 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003864 }
3865
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003866 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003867 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00003868
Richard Smith5fab0c92011-12-28 19:48:30 +00003869 case Builtin::BI__builtin_constant_p:
3870 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smith10c7c902011-12-09 02:04:48 +00003871
Chris Lattnerd545ad12009-09-23 06:06:36 +00003872 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00003873 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00003874 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00003875 return Success(Operand, E);
3876 }
Eli Friedmand5c93992010-02-13 00:10:10 +00003877
3878 case Builtin::BI__builtin_expect:
3879 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003880
3881 case Builtin::BIstrlen:
3882 case Builtin::BI__builtin_strlen:
3883 // As an extension, we support strlen() and __builtin_strlen() as constant
3884 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00003885 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003886 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
3887 // The string literal may have embedded null characters. Find the first
3888 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003889 StringRef Str = S->getString();
3890 StringRef::size_type Pos = Str.find(0);
3891 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003892 Str = Str.substr(0, Pos);
3893
3894 return Success(Str.size(), E);
3895 }
3896
Richard Smithf57d8cb2011-12-09 22:58:01 +00003897 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003898
3899 case Builtin::BI__atomic_is_lock_free: {
3900 APSInt SizeVal;
3901 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
3902 return false;
3903
3904 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
3905 // of two less than the maximum inline atomic width, we know it is
3906 // lock-free. If the size isn't a power of two, or greater than the
3907 // maximum alignment where we promote atomics, we know it is not lock-free
3908 // (at least not in the sense of atomic_is_lock_free). Otherwise,
3909 // the answer can only be determined at runtime; for example, 16-byte
3910 // atomics have lock-free implementations on some, but not all,
3911 // x86-64 processors.
3912
3913 // Check power-of-two.
3914 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
3915 if (!Size.isPowerOfTwo())
3916#if 0
3917 // FIXME: Suppress this folding until the ABI for the promotion width
3918 // settles.
3919 return Success(0, E);
3920#else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003921 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003922#endif
3923
3924#if 0
3925 // Check against promotion width.
3926 // FIXME: Suppress this folding until the ABI for the promotion width
3927 // settles.
3928 unsigned PromoteWidthBits =
3929 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
3930 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
3931 return Success(0, E);
3932#endif
3933
3934 // Check against inlining width.
3935 unsigned InlineWidthBits =
3936 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
3937 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
3938 return Success(1, E);
3939
Richard Smithf57d8cb2011-12-09 22:58:01 +00003940 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003941 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003942 }
Chris Lattner7174bf32008-07-12 00:38:25 +00003943}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003944
Richard Smith8b3497e2011-10-31 01:37:14 +00003945static bool HasSameBase(const LValue &A, const LValue &B) {
3946 if (!A.getLValueBase())
3947 return !B.getLValueBase();
3948 if (!B.getLValueBase())
3949 return false;
3950
Richard Smithce40ad62011-11-12 22:28:03 +00003951 if (A.getLValueBase().getOpaqueValue() !=
3952 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003953 const Decl *ADecl = GetLValueBaseDecl(A);
3954 if (!ADecl)
3955 return false;
3956 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00003957 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00003958 return false;
3959 }
3960
3961 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithfec09922011-11-01 16:57:24 +00003962 A.getLValueFrame() == B.getLValueFrame();
Richard Smith8b3497e2011-10-31 01:37:14 +00003963}
3964
Chris Lattnere13042c2008-07-11 19:10:17 +00003965bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003966 if (E->isAssignmentOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003967 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003968
John McCalle3027922010-08-25 11:45:40 +00003969 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00003970 VisitIgnoredValue(E->getLHS());
3971 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00003972 }
3973
3974 if (E->isLogicalOp()) {
3975 // These need to be handled specially because the operands aren't
3976 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003977 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00003978
Richard Smith11562c52011-10-28 17:51:58 +00003979 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00003980 // We were able to evaluate the LHS, see if we can get away with not
3981 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00003982 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003983 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003984
Richard Smith11562c52011-10-28 17:51:58 +00003985 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00003986 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003987 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003988 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003989 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003990 }
3991 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003992 // FIXME: If both evaluations fail, we should produce the diagnostic from
3993 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
3994 // less clear how to diagnose this.
Richard Smith11562c52011-10-28 17:51:58 +00003995 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00003996 // We can't evaluate the LHS; however, sometimes the result
3997 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003998 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003999 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00004000 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00004001 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004002
4003 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00004004 }
4005 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00004006 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00004007
Eli Friedman5a332ea2008-11-13 06:09:17 +00004008 return false;
4009 }
4010
Anders Carlssonacc79812008-11-16 07:17:21 +00004011 QualType LHSTy = E->getLHS()->getType();
4012 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004013
4014 if (LHSTy->isAnyComplexType()) {
4015 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00004016 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004017
4018 if (!EvaluateComplex(E->getLHS(), LHS, Info))
4019 return false;
4020
4021 if (!EvaluateComplex(E->getRHS(), RHS, Info))
4022 return false;
4023
4024 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00004025 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004026 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00004027 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004028 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4029
John McCalle3027922010-08-25 11:45:40 +00004030 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004031 return Success((CR_r == APFloat::cmpEqual &&
4032 CR_i == APFloat::cmpEqual), E);
4033 else {
John McCalle3027922010-08-25 11:45:40 +00004034 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004035 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00004036 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00004037 CR_r == APFloat::cmpLessThan ||
4038 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00004039 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00004040 CR_i == APFloat::cmpLessThan ||
4041 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004042 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004043 } else {
John McCalle3027922010-08-25 11:45:40 +00004044 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004045 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4046 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4047 else {
John McCalle3027922010-08-25 11:45:40 +00004048 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004049 "Invalid compex comparison.");
4050 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4051 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4052 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004053 }
4054 }
Mike Stump11289f42009-09-09 15:08:12 +00004055
Anders Carlssonacc79812008-11-16 07:17:21 +00004056 if (LHSTy->isRealFloatingType() &&
4057 RHSTy->isRealFloatingType()) {
4058 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00004059
Anders Carlssonacc79812008-11-16 07:17:21 +00004060 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4061 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004062
Anders Carlssonacc79812008-11-16 07:17:21 +00004063 if (!EvaluateFloat(E->getLHS(), LHS, Info))
4064 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004065
Anders Carlssonacc79812008-11-16 07:17:21 +00004066 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00004067
Anders Carlssonacc79812008-11-16 07:17:21 +00004068 switch (E->getOpcode()) {
4069 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004070 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00004071 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004072 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00004073 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004074 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00004075 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004076 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00004077 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00004078 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004079 E);
John McCalle3027922010-08-25 11:45:40 +00004080 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004081 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00004082 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00004083 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00004084 || CR == APFloat::cmpLessThan
4085 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00004086 }
Anders Carlssonacc79812008-11-16 07:17:21 +00004087 }
Mike Stump11289f42009-09-09 15:08:12 +00004088
Eli Friedmana38da572009-04-28 19:17:36 +00004089 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00004090 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCall45d55e42010-05-07 21:00:08 +00004091 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004092 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
4093 return false;
Eli Friedman64004332009-03-23 04:38:34 +00004094
John McCall45d55e42010-05-07 21:00:08 +00004095 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004096 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
4097 return false;
Eli Friedman64004332009-03-23 04:38:34 +00004098
Richard Smith8b3497e2011-10-31 01:37:14 +00004099 // Reject differing bases from the normal codepath; we special-case
4100 // comparisons to null.
4101 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004102 if (E->getOpcode() == BO_Sub) {
4103 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004104 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4105 return false;
4106 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4107 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4108 if (!LHSExpr || !RHSExpr)
4109 return false;
4110 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4111 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4112 if (!LHSAddrExpr || !RHSAddrExpr)
4113 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00004114 // Make sure both labels come from the same function.
4115 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4116 RHSAddrExpr->getLabel()->getDeclContext())
4117 return false;
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004118 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4119 return true;
4120 }
Richard Smith83c68212011-10-31 05:11:32 +00004121 // Inequalities and subtractions between unrelated pointers have
4122 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00004123 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004124 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00004125 // A constant address may compare equal to the address of a symbol.
4126 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00004127 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00004128 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4129 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004130 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00004131 // It's implementation-defined whether distinct literals will have
Eli Friedman42fbd622011-10-31 22:54:30 +00004132 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smithe9e20dd32011-11-04 01:10:57 +00004133 // distinct. However, we do know that the address of a literal will be
4134 // non-null.
4135 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4136 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004137 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00004138 // We can't tell whether weak symbols will end up pointing to the same
4139 // object.
4140 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004141 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00004142 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00004143 // (Note that clang defaults to -fmerge-all-constants, which can
4144 // lead to inconsistent results for comparisons involving the address
4145 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00004146 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00004147 }
Eli Friedman64004332009-03-23 04:38:34 +00004148
Richard Smithf3e9e432011-11-07 09:22:26 +00004149 // FIXME: Implement the C++11 restrictions:
4150 // - Pointer subtractions must be on elements of the same array.
4151 // - Pointer comparisons must be between members with the same access.
4152
John McCalle3027922010-08-25 11:45:40 +00004153 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00004154 QualType Type = E->getLHS()->getType();
4155 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004156
Richard Smithd62306a2011-11-10 06:34:14 +00004157 CharUnits ElementSize;
4158 if (!HandleSizeof(Info, ElementType, ElementSize))
4159 return false;
Eli Friedman64004332009-03-23 04:38:34 +00004160
Richard Smithd62306a2011-11-10 06:34:14 +00004161 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dyck02990832010-01-15 12:37:54 +00004162 RHSValue.getLValueOffset();
4163 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00004164 }
Richard Smith8b3497e2011-10-31 01:37:14 +00004165
4166 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4167 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4168 switch (E->getOpcode()) {
4169 default: llvm_unreachable("missing comparison operator");
4170 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4171 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4172 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4173 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4174 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4175 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmana38da572009-04-28 19:17:36 +00004176 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004177 }
4178 }
Douglas Gregorb90df602010-06-16 00:17:44 +00004179 if (!LHSTy->isIntegralOrEnumerationType() ||
4180 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smith027bf112011-11-17 22:56:20 +00004181 // We can't continue from here for non-integral types.
4182 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004183 }
4184
Anders Carlsson9c181652008-07-08 14:35:21 +00004185 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00004186 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00004187 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004188 return false;
Eli Friedmanbd840592008-07-27 05:46:18 +00004189
Richard Smith11562c52011-10-28 17:51:58 +00004190 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004191 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004192 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00004193
4194 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00004195 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00004196 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4197 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00004198 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00004199 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00004200 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00004201 LHSVal.getLValueOffset() -= AdditionalOffset;
4202 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00004203 return true;
4204 }
4205
4206 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00004207 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00004208 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004209 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4210 LHSVal.getInt().getZExtValue());
4211 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00004212 return true;
4213 }
4214
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004215 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4216 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004217 if (!LHSVal.getLValueOffset().isZero() ||
4218 !RHSVal.getLValueOffset().isZero())
4219 return false;
4220 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4221 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4222 if (!LHSExpr || !RHSExpr)
4223 return false;
4224 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4225 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4226 if (!LHSAddrExpr || !RHSAddrExpr)
4227 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00004228 // Make sure both labels come from the same function.
4229 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4230 RHSAddrExpr->getLabel()->getDeclContext())
4231 return false;
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004232 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4233 return true;
4234 }
4235
Eli Friedman94c25c62009-03-24 01:14:50 +00004236 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00004237 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004238 return Error(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004239
Richard Smith11562c52011-10-28 17:51:58 +00004240 APSInt &LHS = LHSVal.getInt();
4241 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00004242
Anders Carlsson9c181652008-07-08 14:35:21 +00004243 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00004244 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004245 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004246 case BO_Mul: return Success(LHS * RHS, E);
4247 case BO_Add: return Success(LHS + RHS, E);
4248 case BO_Sub: return Success(LHS - RHS, E);
4249 case BO_And: return Success(LHS & RHS, E);
4250 case BO_Xor: return Success(LHS ^ RHS, E);
4251 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00004252 case BO_Div:
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_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00004257 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004258 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00004259 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00004260 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00004261 // During constant-folding, a negative shift is an opposite shift.
4262 if (RHS.isSigned() && RHS.isNegative()) {
4263 RHS = -RHS;
4264 goto shift_right;
4265 }
4266
4267 shift_left:
4268 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00004269 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4270 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004271 }
John McCalle3027922010-08-25 11:45:40 +00004272 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00004273 // During constant-folding, a negative shift is an opposite shift.
4274 if (RHS.isSigned() && RHS.isNegative()) {
4275 RHS = -RHS;
4276 goto shift_left;
4277 }
4278
4279 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00004280 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00004281 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4282 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004283 }
Mike Stump11289f42009-09-09 15:08:12 +00004284
Richard Smith11562c52011-10-28 17:51:58 +00004285 case BO_LT: return Success(LHS < RHS, E);
4286 case BO_GT: return Success(LHS > RHS, E);
4287 case BO_LE: return Success(LHS <= RHS, E);
4288 case BO_GE: return Success(LHS >= RHS, E);
4289 case BO_EQ: return Success(LHS == RHS, E);
4290 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00004291 }
Anders Carlsson9c181652008-07-08 14:35:21 +00004292}
4293
Ken Dyck160146e2010-01-27 17:10:57 +00004294CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00004295 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4296 // the result is the size of the referenced type."
4297 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4298 // result shall be the alignment of the referenced type."
4299 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4300 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00004301
4302 // __alignof is defined to return the preferred alignment.
4303 return Info.Ctx.toCharUnitsFromBits(
4304 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00004305}
4306
Ken Dyck160146e2010-01-27 17:10:57 +00004307CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00004308 E = E->IgnoreParens();
4309
4310 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00004311 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00004312 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00004313 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4314 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00004315
Chris Lattner68061312009-01-24 21:53:27 +00004316 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00004317 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4318 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00004319
Chris Lattner24aeeab2009-01-24 21:09:06 +00004320 return GetAlignOfType(E->getType());
4321}
4322
4323
Peter Collingbournee190dee2011-03-11 19:24:49 +00004324/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4325/// a result as the expression's type.
4326bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4327 const UnaryExprOrTypeTraitExpr *E) {
4328 switch(E->getKind()) {
4329 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00004330 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00004331 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00004332 else
Ken Dyckdbc01912011-03-11 02:13:43 +00004333 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00004334 }
Eli Friedman64004332009-03-23 04:38:34 +00004335
Peter Collingbournee190dee2011-03-11 19:24:49 +00004336 case UETT_VecStep: {
4337 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00004338
Peter Collingbournee190dee2011-03-11 19:24:49 +00004339 if (Ty->isVectorType()) {
4340 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00004341
Peter Collingbournee190dee2011-03-11 19:24:49 +00004342 // The vec_step built-in functions that take a 3-component
4343 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4344 if (n == 3)
4345 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00004346
Peter Collingbournee190dee2011-03-11 19:24:49 +00004347 return Success(n, E);
4348 } else
4349 return Success(1, E);
4350 }
4351
4352 case UETT_SizeOf: {
4353 QualType SrcTy = E->getTypeOfArgument();
4354 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4355 // the result is the size of the referenced type."
4356 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4357 // result shall be the alignment of the referenced type."
4358 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4359 SrcTy = Ref->getPointeeType();
4360
Richard Smithd62306a2011-11-10 06:34:14 +00004361 CharUnits Sizeof;
4362 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00004363 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004364 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00004365 }
4366 }
4367
4368 llvm_unreachable("unknown expr/type trait");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004369 return Error(E);
Chris Lattnerf8d7f722008-07-11 21:24:13 +00004370}
4371
Peter Collingbournee9200682011-05-13 03:29:01 +00004372bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00004373 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00004374 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00004375 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004376 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00004377 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00004378 for (unsigned i = 0; i != n; ++i) {
4379 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4380 switch (ON.getKind()) {
4381 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00004382 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00004383 APSInt IdxResult;
4384 if (!EvaluateInteger(Idx, IdxResult, Info))
4385 return false;
4386 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4387 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004388 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004389 CurrentType = AT->getElementType();
4390 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4391 Result += IdxResult.getSExtValue() * ElementSize;
4392 break;
4393 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00004394
Douglas Gregor882211c2010-04-28 22:16:22 +00004395 case OffsetOfExpr::OffsetOfNode::Field: {
4396 FieldDecl *MemberDecl = ON.getField();
4397 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00004398 if (!RT)
4399 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004400 RecordDecl *RD = RT->getDecl();
4401 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00004402 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00004403 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00004404 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00004405 CurrentType = MemberDecl->getType().getNonReferenceType();
4406 break;
4407 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00004408
Douglas Gregor882211c2010-04-28 22:16:22 +00004409 case OffsetOfExpr::OffsetOfNode::Identifier:
4410 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004411 return Error(OOE);
4412
Douglas Gregord1702062010-04-29 00:18:15 +00004413 case OffsetOfExpr::OffsetOfNode::Base: {
4414 CXXBaseSpecifier *BaseSpec = ON.getBase();
4415 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004416 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004417
4418 // Find the layout of the class whose base we are looking into.
4419 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00004420 if (!RT)
4421 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004422 RecordDecl *RD = RT->getDecl();
4423 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4424
4425 // Find the base class itself.
4426 CurrentType = BaseSpec->getType();
4427 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4428 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004429 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004430
4431 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00004432 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00004433 break;
4434 }
Douglas Gregor882211c2010-04-28 22:16:22 +00004435 }
4436 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004437 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004438}
4439
Chris Lattnere13042c2008-07-11 19:10:17 +00004440bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004441 switch (E->getOpcode()) {
4442 default:
4443 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4444 // See C99 6.6p3.
4445 return Error(E);
4446 case UO_Extension:
4447 // FIXME: Should extension allow i-c-e extension expressions in its scope?
4448 // If so, we could clear the diagnostic ID.
4449 return Visit(E->getSubExpr());
4450 case UO_Plus:
4451 // The result is just the value.
4452 return Visit(E->getSubExpr());
4453 case UO_Minus: {
4454 if (!Visit(E->getSubExpr()))
4455 return false;
4456 if (!Result.isInt()) return Error(E);
4457 return Success(-Result.getInt(), E);
4458 }
4459 case UO_Not: {
4460 if (!Visit(E->getSubExpr()))
4461 return false;
4462 if (!Result.isInt()) return Error(E);
4463 return Success(~Result.getInt(), E);
4464 }
4465 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00004466 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00004467 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00004468 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004469 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004470 }
Anders Carlsson9c181652008-07-08 14:35:21 +00004471 }
Anders Carlsson9c181652008-07-08 14:35:21 +00004472}
Mike Stump11289f42009-09-09 15:08:12 +00004473
Chris Lattner477c4be2008-07-12 01:15:53 +00004474/// HandleCast - This is used to evaluate implicit or explicit casts where the
4475/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00004476bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4477 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00004478 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00004479 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00004480
Eli Friedmanc757de22011-03-25 00:43:55 +00004481 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00004482 case CK_BaseToDerived:
4483 case CK_DerivedToBase:
4484 case CK_UncheckedDerivedToBase:
4485 case CK_Dynamic:
4486 case CK_ToUnion:
4487 case CK_ArrayToPointerDecay:
4488 case CK_FunctionToPointerDecay:
4489 case CK_NullToPointer:
4490 case CK_NullToMemberPointer:
4491 case CK_BaseToDerivedMemberPointer:
4492 case CK_DerivedToBaseMemberPointer:
4493 case CK_ConstructorConversion:
4494 case CK_IntegralToPointer:
4495 case CK_ToVoid:
4496 case CK_VectorSplat:
4497 case CK_IntegralToFloating:
4498 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00004499 case CK_CPointerToObjCPointerCast:
4500 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00004501 case CK_AnyPointerToBlockPointerCast:
4502 case CK_ObjCObjectLValueCast:
4503 case CK_FloatingRealToComplex:
4504 case CK_FloatingComplexToReal:
4505 case CK_FloatingComplexCast:
4506 case CK_FloatingComplexToIntegralComplex:
4507 case CK_IntegralRealToComplex:
4508 case CK_IntegralComplexCast:
4509 case CK_IntegralComplexToFloatingComplex:
4510 llvm_unreachable("invalid cast kind for integral value");
4511
Eli Friedman9faf2f92011-03-25 19:07:11 +00004512 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00004513 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004514 case CK_LValueBitCast:
4515 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00004516 case CK_ARCProduceObject:
4517 case CK_ARCConsumeObject:
4518 case CK_ARCReclaimReturnedObject:
4519 case CK_ARCExtendBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004520 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004521
4522 case CK_LValueToRValue:
4523 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004524 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004525
4526 case CK_MemberPointerToBoolean:
4527 case CK_PointerToBoolean:
4528 case CK_IntegralToBoolean:
4529 case CK_FloatingToBoolean:
4530 case CK_FloatingComplexToBoolean:
4531 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004532 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00004533 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00004534 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004535 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004536 }
4537
Eli Friedmanc757de22011-03-25 00:43:55 +00004538 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00004539 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00004540 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00004541
Eli Friedman742421e2009-02-20 01:15:07 +00004542 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004543 // Allow casts of address-of-label differences if they are no-ops
4544 // or narrowing. (The narrowing case isn't actually guaranteed to
4545 // be constant-evaluatable except in some narrow cases which are hard
4546 // to detect here. We let it through on the assumption the user knows
4547 // what they are doing.)
4548 if (Result.isAddrLabelDiff())
4549 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00004550 // Only allow casts of lvalues if they are lossless.
4551 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
4552 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004553
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004554 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004555 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00004556 }
Mike Stump11289f42009-09-09 15:08:12 +00004557
Eli Friedmanc757de22011-03-25 00:43:55 +00004558 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004559 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4560
John McCall45d55e42010-05-07 21:00:08 +00004561 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00004562 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00004563 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00004564
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004565 if (LV.getLValueBase()) {
4566 // Only allow based lvalue casts if they are lossless.
4567 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004568 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004569
Richard Smithcf74da72011-11-16 07:18:12 +00004570 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004571 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004572 return true;
4573 }
4574
Ken Dyck02990832010-01-15 12:37:54 +00004575 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
4576 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004577 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004578 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004579
Eli Friedmanc757de22011-03-25 00:43:55 +00004580 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00004581 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00004582 if (!EvaluateComplex(SubExpr, C, Info))
4583 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00004584 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00004585 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00004586
Eli Friedmanc757de22011-03-25 00:43:55 +00004587 case CK_FloatingToIntegral: {
4588 APFloat F(0.0);
4589 if (!EvaluateFloat(SubExpr, F, Info))
4590 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00004591
Richard Smith357362d2011-12-13 06:39:58 +00004592 APSInt Value;
4593 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
4594 return false;
4595 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004596 }
4597 }
Mike Stump11289f42009-09-09 15:08:12 +00004598
Eli Friedmanc757de22011-03-25 00:43:55 +00004599 llvm_unreachable("unknown cast resulting in integral value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004600 return Error(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00004601}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004602
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004603bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4604 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00004605 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004606 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4607 return false;
4608 if (!LV.isComplexInt())
4609 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004610 return Success(LV.getComplexIntReal(), E);
4611 }
4612
4613 return Visit(E->getSubExpr());
4614}
4615
Eli Friedman4e7a2412009-02-27 04:45:43 +00004616bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004617 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00004618 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004619 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4620 return false;
4621 if (!LV.isComplexInt())
4622 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004623 return Success(LV.getComplexIntImag(), E);
4624 }
4625
Richard Smith4a678122011-10-24 18:44:57 +00004626 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00004627 return Success(0, E);
4628}
4629
Douglas Gregor820ba7b2011-01-04 17:33:58 +00004630bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4631 return Success(E->getPackLength(), E);
4632}
4633
Sebastian Redl5f0180d2010-09-10 20:55:47 +00004634bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4635 return Success(E->getValue(), E);
4636}
4637
Chris Lattner05706e882008-07-11 18:11:29 +00004638//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00004639// Float Evaluation
4640//===----------------------------------------------------------------------===//
4641
4642namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004643class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004644 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00004645 APFloat &Result;
4646public:
4647 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004648 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00004649
Richard Smith0b0a0b62011-10-29 20:57:55 +00004650 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004651 Result = V.getFloat();
4652 return true;
4653 }
Eli Friedman24c01542008-08-22 00:06:13 +00004654
Richard Smithfddd3842011-12-30 21:15:51 +00004655 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00004656 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4657 return true;
4658 }
4659
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004660 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00004661
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004662 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00004663 bool VisitBinaryOperator(const BinaryOperator *E);
4664 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004665 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00004666
John McCallb1fb0d32010-05-07 22:08:54 +00004667 bool VisitUnaryReal(const UnaryOperator *E);
4668 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00004669
Richard Smithfddd3842011-12-30 21:15:51 +00004670 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00004671};
4672} // end anonymous namespace
4673
4674static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004675 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004676 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00004677}
4678
Jay Foad39c79802011-01-12 09:06:06 +00004679static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00004680 QualType ResultTy,
4681 const Expr *Arg,
4682 bool SNaN,
4683 llvm::APFloat &Result) {
4684 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4685 if (!S) return false;
4686
4687 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4688
4689 llvm::APInt fill;
4690
4691 // Treat empty strings as if they were zero.
4692 if (S->getString().empty())
4693 fill = llvm::APInt(32, 0);
4694 else if (S->getString().getAsInteger(0, fill))
4695 return false;
4696
4697 if (SNaN)
4698 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
4699 else
4700 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
4701 return true;
4702}
4703
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004704bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004705 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004706 default:
4707 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4708
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004709 case Builtin::BI__builtin_huge_val:
4710 case Builtin::BI__builtin_huge_valf:
4711 case Builtin::BI__builtin_huge_vall:
4712 case Builtin::BI__builtin_inf:
4713 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00004714 case Builtin::BI__builtin_infl: {
4715 const llvm::fltSemantics &Sem =
4716 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00004717 Result = llvm::APFloat::getInf(Sem);
4718 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00004719 }
Mike Stump11289f42009-09-09 15:08:12 +00004720
John McCall16291492010-02-28 13:00:19 +00004721 case Builtin::BI__builtin_nans:
4722 case Builtin::BI__builtin_nansf:
4723 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004724 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4725 true, Result))
4726 return Error(E);
4727 return true;
John McCall16291492010-02-28 13:00:19 +00004728
Chris Lattner0b7282e2008-10-06 06:31:58 +00004729 case Builtin::BI__builtin_nan:
4730 case Builtin::BI__builtin_nanf:
4731 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00004732 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00004733 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004734 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4735 false, Result))
4736 return Error(E);
4737 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004738
4739 case Builtin::BI__builtin_fabs:
4740 case Builtin::BI__builtin_fabsf:
4741 case Builtin::BI__builtin_fabsl:
4742 if (!EvaluateFloat(E->getArg(0), Result, Info))
4743 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004744
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004745 if (Result.isNegative())
4746 Result.changeSign();
4747 return true;
4748
Mike Stump11289f42009-09-09 15:08:12 +00004749 case Builtin::BI__builtin_copysign:
4750 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004751 case Builtin::BI__builtin_copysignl: {
4752 APFloat RHS(0.);
4753 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4754 !EvaluateFloat(E->getArg(1), RHS, Info))
4755 return false;
4756 Result.copySign(RHS);
4757 return true;
4758 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004759 }
4760}
4761
John McCallb1fb0d32010-05-07 22:08:54 +00004762bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004763 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4764 ComplexValue CV;
4765 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4766 return false;
4767 Result = CV.FloatReal;
4768 return true;
4769 }
4770
4771 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00004772}
4773
4774bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004775 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4776 ComplexValue CV;
4777 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4778 return false;
4779 Result = CV.FloatImag;
4780 return true;
4781 }
4782
Richard Smith4a678122011-10-24 18:44:57 +00004783 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00004784 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4785 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00004786 return true;
4787}
4788
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004789bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004790 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004791 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004792 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00004793 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00004794 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00004795 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
4796 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004797 Result.changeSign();
4798 return true;
4799 }
4800}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004801
Eli Friedman24c01542008-08-22 00:06:13 +00004802bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004803 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
4804 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00004805
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004806 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00004807 if (!EvaluateFloat(E->getLHS(), Result, Info))
4808 return false;
4809 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4810 return false;
4811
4812 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004813 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004814 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00004815 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
4816 return true;
John McCalle3027922010-08-25 11:45:40 +00004817 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00004818 Result.add(RHS, APFloat::rmNearestTiesToEven);
4819 return true;
John McCalle3027922010-08-25 11:45:40 +00004820 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00004821 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
4822 return true;
John McCalle3027922010-08-25 11:45:40 +00004823 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00004824 Result.divide(RHS, APFloat::rmNearestTiesToEven);
4825 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00004826 }
4827}
4828
4829bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
4830 Result = E->getValue();
4831 return true;
4832}
4833
Peter Collingbournee9200682011-05-13 03:29:01 +00004834bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4835 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00004836
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004837 switch (E->getCastKind()) {
4838 default:
Richard Smith11562c52011-10-28 17:51:58 +00004839 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004840
4841 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004842 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00004843 return EvaluateInteger(SubExpr, IntResult, Info) &&
4844 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
4845 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00004846 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004847
4848 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004849 if (!Visit(SubExpr))
4850 return false;
Richard Smith357362d2011-12-13 06:39:58 +00004851 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
4852 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00004853 }
John McCalld7646252010-11-14 08:17:51 +00004854
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004855 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00004856 ComplexValue V;
4857 if (!EvaluateComplex(SubExpr, V, Info))
4858 return false;
4859 Result = V.getComplexFloatReal();
4860 return true;
4861 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004862 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004863
Richard Smithf57d8cb2011-12-09 22:58:01 +00004864 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004865}
4866
Eli Friedman24c01542008-08-22 00:06:13 +00004867//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004868// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00004869//===----------------------------------------------------------------------===//
4870
4871namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004872class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004873 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00004874 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00004875
Anders Carlsson537969c2008-11-16 20:27:53 +00004876public:
John McCall93d91dc2010-05-07 17:22:02 +00004877 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004878 : ExprEvaluatorBaseTy(info), Result(Result) {}
4879
Richard Smith0b0a0b62011-10-29 20:57:55 +00004880 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004881 Result.setFrom(V);
4882 return true;
4883 }
Mike Stump11289f42009-09-09 15:08:12 +00004884
Eli Friedmanc4b251d2012-01-10 04:58:17 +00004885 bool ZeroInitialization(const Expr *E);
4886
Anders Carlsson537969c2008-11-16 20:27:53 +00004887 //===--------------------------------------------------------------------===//
4888 // Visitor Methods
4889 //===--------------------------------------------------------------------===//
4890
Peter Collingbournee9200682011-05-13 03:29:01 +00004891 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004892 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00004893 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004894 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00004895 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00004896};
4897} // end anonymous namespace
4898
John McCall93d91dc2010-05-07 17:22:02 +00004899static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
4900 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004901 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004902 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00004903}
4904
Eli Friedmanc4b251d2012-01-10 04:58:17 +00004905bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
4906 QualType ElemTy = cast<ComplexType>(E->getType())->getElementType();
4907 if (ElemTy->isRealFloatingType()) {
4908 Result.makeComplexFloat();
4909 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
4910 Result.FloatReal = Zero;
4911 Result.FloatImag = Zero;
4912 } else {
4913 Result.makeComplexInt();
4914 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
4915 Result.IntReal = Zero;
4916 Result.IntImag = Zero;
4917 }
4918 return true;
4919}
4920
Peter Collingbournee9200682011-05-13 03:29:01 +00004921bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
4922 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004923
4924 if (SubExpr->getType()->isRealFloatingType()) {
4925 Result.makeComplexFloat();
4926 APFloat &Imag = Result.FloatImag;
4927 if (!EvaluateFloat(SubExpr, Imag, Info))
4928 return false;
4929
4930 Result.FloatReal = APFloat(Imag.getSemantics());
4931 return true;
4932 } else {
4933 assert(SubExpr->getType()->isIntegerType() &&
4934 "Unexpected imaginary literal.");
4935
4936 Result.makeComplexInt();
4937 APSInt &Imag = Result.IntImag;
4938 if (!EvaluateInteger(SubExpr, Imag, Info))
4939 return false;
4940
4941 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
4942 return true;
4943 }
4944}
4945
Peter Collingbournee9200682011-05-13 03:29:01 +00004946bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004947
John McCallfcef3cf2010-12-14 17:51:41 +00004948 switch (E->getCastKind()) {
4949 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004950 case CK_BaseToDerived:
4951 case CK_DerivedToBase:
4952 case CK_UncheckedDerivedToBase:
4953 case CK_Dynamic:
4954 case CK_ToUnion:
4955 case CK_ArrayToPointerDecay:
4956 case CK_FunctionToPointerDecay:
4957 case CK_NullToPointer:
4958 case CK_NullToMemberPointer:
4959 case CK_BaseToDerivedMemberPointer:
4960 case CK_DerivedToBaseMemberPointer:
4961 case CK_MemberPointerToBoolean:
4962 case CK_ConstructorConversion:
4963 case CK_IntegralToPointer:
4964 case CK_PointerToIntegral:
4965 case CK_PointerToBoolean:
4966 case CK_ToVoid:
4967 case CK_VectorSplat:
4968 case CK_IntegralCast:
4969 case CK_IntegralToBoolean:
4970 case CK_IntegralToFloating:
4971 case CK_FloatingToIntegral:
4972 case CK_FloatingToBoolean:
4973 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00004974 case CK_CPointerToObjCPointerCast:
4975 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004976 case CK_AnyPointerToBlockPointerCast:
4977 case CK_ObjCObjectLValueCast:
4978 case CK_FloatingComplexToReal:
4979 case CK_FloatingComplexToBoolean:
4980 case CK_IntegralComplexToReal:
4981 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00004982 case CK_ARCProduceObject:
4983 case CK_ARCConsumeObject:
4984 case CK_ARCReclaimReturnedObject:
4985 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00004986 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00004987
John McCallfcef3cf2010-12-14 17:51:41 +00004988 case CK_LValueToRValue:
4989 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004990 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004991
4992 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004993 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004994 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004995 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004996
4997 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004998 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00004999 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00005000 return false;
5001
John McCallfcef3cf2010-12-14 17:51:41 +00005002 Result.makeComplexFloat();
5003 Result.FloatImag = APFloat(Real.getSemantics());
5004 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00005005 }
5006
John McCallfcef3cf2010-12-14 17:51:41 +00005007 case CK_FloatingComplexCast: {
5008 if (!Visit(E->getSubExpr()))
5009 return false;
5010
5011 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5012 QualType From
5013 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5014
Richard Smith357362d2011-12-13 06:39:58 +00005015 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5016 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00005017 }
5018
5019 case CK_FloatingComplexToIntegralComplex: {
5020 if (!Visit(E->getSubExpr()))
5021 return false;
5022
5023 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5024 QualType From
5025 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5026 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00005027 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5028 To, Result.IntReal) &&
5029 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5030 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00005031 }
5032
5033 case CK_IntegralRealToComplex: {
5034 APSInt &Real = Result.IntReal;
5035 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5036 return false;
5037
5038 Result.makeComplexInt();
5039 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5040 return true;
5041 }
5042
5043 case CK_IntegralComplexCast: {
5044 if (!Visit(E->getSubExpr()))
5045 return false;
5046
5047 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5048 QualType From
5049 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5050
5051 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
5052 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
5053 return true;
5054 }
5055
5056 case CK_IntegralComplexToFloatingComplex: {
5057 if (!Visit(E->getSubExpr()))
5058 return false;
5059
5060 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5061 QualType From
5062 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5063 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00005064 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5065 To, Result.FloatReal) &&
5066 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5067 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00005068 }
5069 }
5070
5071 llvm_unreachable("unknown cast resulting in complex value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00005072 return Error(E);
Eli Friedmanc3e9df32010-08-16 23:27:44 +00005073}
5074
John McCall93d91dc2010-05-07 17:22:02 +00005075bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005076 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00005077 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5078
John McCall93d91dc2010-05-07 17:22:02 +00005079 if (!Visit(E->getLHS()))
5080 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005081
John McCall93d91dc2010-05-07 17:22:02 +00005082 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00005083 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00005084 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00005085
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005086 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5087 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00005088 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005089 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00005090 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00005091 if (Result.isComplexFloat()) {
5092 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5093 APFloat::rmNearestTiesToEven);
5094 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5095 APFloat::rmNearestTiesToEven);
5096 } else {
5097 Result.getComplexIntReal() += RHS.getComplexIntReal();
5098 Result.getComplexIntImag() += RHS.getComplexIntImag();
5099 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005100 break;
John McCalle3027922010-08-25 11:45:40 +00005101 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00005102 if (Result.isComplexFloat()) {
5103 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5104 APFloat::rmNearestTiesToEven);
5105 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5106 APFloat::rmNearestTiesToEven);
5107 } else {
5108 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5109 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5110 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005111 break;
John McCalle3027922010-08-25 11:45:40 +00005112 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005113 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00005114 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005115 APFloat &LHS_r = LHS.getComplexFloatReal();
5116 APFloat &LHS_i = LHS.getComplexFloatImag();
5117 APFloat &RHS_r = RHS.getComplexFloatReal();
5118 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00005119
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005120 APFloat Tmp = LHS_r;
5121 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5122 Result.getComplexFloatReal() = Tmp;
5123 Tmp = LHS_i;
5124 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5125 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5126
5127 Tmp = LHS_r;
5128 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5129 Result.getComplexFloatImag() = Tmp;
5130 Tmp = LHS_i;
5131 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5132 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5133 } else {
John McCall93d91dc2010-05-07 17:22:02 +00005134 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00005135 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005136 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5137 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00005138 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005139 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5140 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5141 }
5142 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005143 case BO_Div:
5144 if (Result.isComplexFloat()) {
5145 ComplexValue LHS = Result;
5146 APFloat &LHS_r = LHS.getComplexFloatReal();
5147 APFloat &LHS_i = LHS.getComplexFloatImag();
5148 APFloat &RHS_r = RHS.getComplexFloatReal();
5149 APFloat &RHS_i = RHS.getComplexFloatImag();
5150 APFloat &Res_r = Result.getComplexFloatReal();
5151 APFloat &Res_i = Result.getComplexFloatImag();
5152
5153 APFloat Den = RHS_r;
5154 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5155 APFloat Tmp = RHS_i;
5156 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5157 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5158
5159 Res_r = LHS_r;
5160 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5161 Tmp = LHS_i;
5162 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5163 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5164 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5165
5166 Res_i = LHS_i;
5167 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5168 Tmp = LHS_r;
5169 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5170 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5171 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5172 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005173 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5174 return Error(E, diag::note_expr_divide_by_zero);
5175
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005176 ComplexValue LHS = Result;
5177 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5178 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5179 Result.getComplexIntReal() =
5180 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5181 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5182 Result.getComplexIntImag() =
5183 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5184 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5185 }
5186 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00005187 }
5188
John McCall93d91dc2010-05-07 17:22:02 +00005189 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00005190}
5191
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005192bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5193 // Get the operand value into 'Result'.
5194 if (!Visit(E->getSubExpr()))
5195 return false;
5196
5197 switch (E->getOpcode()) {
5198 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00005199 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005200 case UO_Extension:
5201 return true;
5202 case UO_Plus:
5203 // The result is always just the subexpr.
5204 return true;
5205 case UO_Minus:
5206 if (Result.isComplexFloat()) {
5207 Result.getComplexFloatReal().changeSign();
5208 Result.getComplexFloatImag().changeSign();
5209 }
5210 else {
5211 Result.getComplexIntReal() = -Result.getComplexIntReal();
5212 Result.getComplexIntImag() = -Result.getComplexIntImag();
5213 }
5214 return true;
5215 case UO_Not:
5216 if (Result.isComplexFloat())
5217 Result.getComplexFloatImag().changeSign();
5218 else
5219 Result.getComplexIntImag() = -Result.getComplexIntImag();
5220 return true;
5221 }
5222}
5223
Eli Friedmanc4b251d2012-01-10 04:58:17 +00005224bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5225 if (E->getNumInits() == 2) {
5226 if (E->getType()->isComplexType()) {
5227 Result.makeComplexFloat();
5228 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5229 return false;
5230 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5231 return false;
5232 } else {
5233 Result.makeComplexInt();
5234 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5235 return false;
5236 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5237 return false;
5238 }
5239 return true;
5240 }
5241 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5242}
5243
Anders Carlsson537969c2008-11-16 20:27:53 +00005244//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00005245// Void expression evaluation, primarily for a cast to void on the LHS of a
5246// comma operator
5247//===----------------------------------------------------------------------===//
5248
5249namespace {
5250class VoidExprEvaluator
5251 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5252public:
5253 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5254
5255 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00005256
5257 bool VisitCastExpr(const CastExpr *E) {
5258 switch (E->getCastKind()) {
5259 default:
5260 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5261 case CK_ToVoid:
5262 VisitIgnoredValue(E->getSubExpr());
5263 return true;
5264 }
5265 }
5266};
5267} // end anonymous namespace
5268
5269static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5270 assert(E->isRValue() && E->getType()->isVoidType());
5271 return VoidExprEvaluator(Info).Visit(E);
5272}
5273
5274//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00005275// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00005276//===----------------------------------------------------------------------===//
5277
Richard Smith0b0a0b62011-10-29 20:57:55 +00005278static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005279 // In C, function designators are not lvalues, but we evaluate them as if they
5280 // are.
5281 if (E->isGLValue() || E->getType()->isFunctionType()) {
5282 LValue LV;
5283 if (!EvaluateLValue(E, LV, Info))
5284 return false;
5285 LV.moveInto(Result);
5286 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00005287 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005288 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005289 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00005290 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005291 return false;
John McCall45d55e42010-05-07 21:00:08 +00005292 } else if (E->getType()->hasPointerRepresentation()) {
5293 LValue LV;
5294 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005295 return false;
Richard Smith725810a2011-10-16 21:26:27 +00005296 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00005297 } else if (E->getType()->isRealFloatingType()) {
5298 llvm::APFloat F(0.0);
5299 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005300 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005301 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00005302 } else if (E->getType()->isAnyComplexType()) {
5303 ComplexValue C;
5304 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005305 return false;
Richard Smith725810a2011-10-16 21:26:27 +00005306 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00005307 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00005308 MemberPtr P;
5309 if (!EvaluateMemberPointer(E, P, Info))
5310 return false;
5311 P.moveInto(Result);
5312 return true;
Richard Smithfddd3842011-12-30 21:15:51 +00005313 } else if (E->getType()->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005314 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00005315 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00005316 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00005317 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005318 Result = Info.CurrentCall->Temporaries[E];
Richard Smithfddd3842011-12-30 21:15:51 +00005319 } else if (E->getType()->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005320 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00005321 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00005322 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5323 return false;
5324 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00005325 } else if (E->getType()->isVoidType()) {
Richard Smith357362d2011-12-13 06:39:58 +00005326 if (Info.getLangOpts().CPlusPlus0x)
5327 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5328 << E->getType();
5329 else
5330 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith42d3af92011-12-07 00:43:50 +00005331 if (!EvaluateVoid(E, Info))
5332 return false;
Richard Smith357362d2011-12-13 06:39:58 +00005333 } else if (Info.getLangOpts().CPlusPlus0x) {
5334 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5335 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005336 } else {
Richard Smith92b1ce02011-12-12 09:28:41 +00005337 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00005338 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005339 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005340
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00005341 return true;
5342}
5343
Richard Smithed5165f2011-11-04 05:33:44 +00005344/// EvaluateConstantExpression - Evaluate an expression as a constant expression
5345/// in-place in an APValue. In some cases, the in-place evaluation is essential,
5346/// since later initializers for an object can indirectly refer to subobjects
5347/// which were initialized earlier.
5348static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smith357362d2011-12-13 06:39:58 +00005349 const LValue &This, const Expr *E,
5350 CheckConstantExpressionKind CCEK) {
Richard Smithfddd3842011-12-30 21:15:51 +00005351 if (!CheckLiteralType(Info, E))
5352 return false;
5353
5354 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00005355 // Evaluate arrays and record types in-place, so that later initializers can
5356 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00005357 if (E->getType()->isArrayType())
5358 return EvaluateArray(E, This, Result, Info);
5359 else if (E->getType()->isRecordType())
5360 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00005361 }
5362
5363 // For any other type, in-place evaluation is unimportant.
5364 CCValue CoreConstResult;
5365 return Evaluate(CoreConstResult, Info, E) &&
Richard Smith357362d2011-12-13 06:39:58 +00005366 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smithed5165f2011-11-04 05:33:44 +00005367}
5368
Richard Smithf57d8cb2011-12-09 22:58:01 +00005369/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5370/// lvalue-to-rvalue cast if it is an lvalue.
5371static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00005372 if (!CheckLiteralType(Info, E))
5373 return false;
5374
Richard Smithf57d8cb2011-12-09 22:58:01 +00005375 CCValue Value;
5376 if (!::Evaluate(Value, Info, E))
5377 return false;
5378
5379 if (E->isGLValue()) {
5380 LValue LV;
5381 LV.setFrom(Value);
5382 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
5383 return false;
5384 }
5385
5386 // Check this core constant expression is a constant expression, and if so,
5387 // convert it to one.
5388 return CheckConstantExpression(Info, E, Value, Result);
5389}
Richard Smith11562c52011-10-28 17:51:58 +00005390
Richard Smith7b553f12011-10-29 00:50:52 +00005391/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00005392/// any crazy technique (that has nothing to do with language standards) that
5393/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00005394/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
5395/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00005396bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith036e2bd2011-12-10 01:10:13 +00005397 // Fast-path evaluations of integer literals, since we sometimes see files
5398 // containing vast quantities of these.
5399 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
5400 Result.Val = APValue(APSInt(L->getValue(),
5401 L->getType()->isUnsignedIntegerType()));
5402 return true;
5403 }
5404
Richard Smith5686e752011-11-10 03:30:42 +00005405 // FIXME: Evaluating initializers for large arrays can cause performance
5406 // problems, and we don't use such values yet. Once we have a more efficient
5407 // array representation, this should be reinstated, and used by CodeGen.
Richard Smith027bf112011-11-17 22:56:20 +00005408 // The same problem affects large records.
5409 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5410 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith5686e752011-11-10 03:30:42 +00005411 return false;
5412
Richard Smithd62306a2011-11-10 06:34:14 +00005413 // FIXME: If this is the initializer for an lvalue, pass that in.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005414 EvalInfo Info(Ctx, Result);
5415 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00005416}
5417
Jay Foad39c79802011-01-12 09:06:06 +00005418bool Expr::EvaluateAsBooleanCondition(bool &Result,
5419 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00005420 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00005421 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00005422 HandleConversionToBool(CCValue(const_cast<ASTContext&>(Ctx),
5423 Scratch.Val, CCValue::GlobalValue()),
Richard Smith0b0a0b62011-10-29 20:57:55 +00005424 Result);
John McCall1be1c632010-01-05 23:42:56 +00005425}
5426
Richard Smith5fab0c92011-12-28 19:48:30 +00005427bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
5428 SideEffectsKind AllowSideEffects) const {
5429 if (!getType()->isIntegralOrEnumerationType())
5430 return false;
5431
Richard Smith11562c52011-10-28 17:51:58 +00005432 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00005433 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
5434 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00005435 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005436
Richard Smith11562c52011-10-28 17:51:58 +00005437 Result = ExprResult.Val.getInt();
5438 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00005439}
5440
Jay Foad39c79802011-01-12 09:06:06 +00005441bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00005442 EvalInfo Info(Ctx, Result);
5443
John McCall45d55e42010-05-07 21:00:08 +00005444 LValue LV;
Richard Smith80815602011-11-07 05:07:52 +00005445 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smith357362d2011-12-13 06:39:58 +00005446 CheckLValueConstantExpression(Info, this, LV, Result.Val,
5447 CCEK_Constant);
Eli Friedman7d45c482009-09-13 10:17:44 +00005448}
5449
Richard Smithd0b4dd62011-12-19 06:19:21 +00005450bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
5451 const VarDecl *VD,
5452 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
5453 Expr::EvalStatus EStatus;
5454 EStatus.Diag = &Notes;
5455
5456 EvalInfo InitInfo(Ctx, EStatus);
5457 InitInfo.setEvaluatingDecl(VD, Value);
5458
Richard Smithfddd3842011-12-30 21:15:51 +00005459 if (!CheckLiteralType(InitInfo, this))
5460 return false;
5461
Richard Smithd0b4dd62011-12-19 06:19:21 +00005462 LValue LVal;
5463 LVal.set(VD);
5464
Richard Smithfddd3842011-12-30 21:15:51 +00005465 // C++11 [basic.start.init]p2:
5466 // Variables with static storage duration or thread storage duration shall be
5467 // zero-initialized before any other initialization takes place.
5468 // This behavior is not present in C.
5469 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
5470 !VD->getType()->isReferenceType()) {
5471 ImplicitValueInitExpr VIE(VD->getType());
5472 if (!EvaluateConstantExpression(Value, InitInfo, LVal, &VIE))
5473 return false;
5474 }
5475
Richard Smithd0b4dd62011-12-19 06:19:21 +00005476 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
5477 !EStatus.HasSideEffects;
5478}
5479
Richard Smith7b553f12011-10-29 00:50:52 +00005480/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
5481/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00005482bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00005483 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00005484 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00005485}
Anders Carlsson59689ed2008-11-22 21:04:56 +00005486
Jay Foad39c79802011-01-12 09:06:06 +00005487bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00005488 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005489}
5490
Richard Smithcaf33902011-10-10 18:28:20 +00005491APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005492 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005493 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00005494 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00005495 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005496 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00005497
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005498 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00005499}
John McCall864e3962010-05-07 05:32:02 +00005500
Abramo Bagnaraf8199452010-05-14 17:07:14 +00005501 bool Expr::EvalResult::isGlobalLValue() const {
5502 assert(Val.isLValue());
5503 return IsGlobalLValue(Val.getLValueBase());
5504 }
5505
5506
John McCall864e3962010-05-07 05:32:02 +00005507/// isIntegerConstantExpr - this recursive routine will test if an expression is
5508/// an integer constant expression.
5509
5510/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
5511/// comma, etc
5512///
5513/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
5514/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
5515/// cast+dereference.
5516
5517// CheckICE - This function does the fundamental ICE checking: the returned
5518// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
5519// Note that to reduce code duplication, this helper does no evaluation
5520// itself; the caller checks whether the expression is evaluatable, and
5521// in the rare cases where CheckICE actually cares about the evaluated
5522// value, it calls into Evalute.
5523//
5524// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00005525// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00005526// 1: This expression is not an ICE, but if it isn't evaluated, it's
5527// a legal subexpression for an ICE. This return value is used to handle
5528// the comma operator in C99 mode.
5529// 2: This expression is not an ICE, and is not a legal subexpression for one.
5530
Dan Gohman28ade552010-07-26 21:25:24 +00005531namespace {
5532
John McCall864e3962010-05-07 05:32:02 +00005533struct ICEDiag {
5534 unsigned Val;
5535 SourceLocation Loc;
5536
5537 public:
5538 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
5539 ICEDiag() : Val(0) {}
5540};
5541
Dan Gohman28ade552010-07-26 21:25:24 +00005542}
5543
5544static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00005545
5546static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
5547 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005548 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00005549 !EVResult.Val.isInt()) {
5550 return ICEDiag(2, E->getLocStart());
5551 }
5552 return NoDiag();
5553}
5554
5555static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
5556 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00005557 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00005558 return ICEDiag(2, E->getLocStart());
5559 }
5560
5561 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00005562#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00005563#define STMT(Node, Base) case Expr::Node##Class:
5564#define EXPR(Node, Base)
5565#include "clang/AST/StmtNodes.inc"
5566 case Expr::PredefinedExprClass:
5567 case Expr::FloatingLiteralClass:
5568 case Expr::ImaginaryLiteralClass:
5569 case Expr::StringLiteralClass:
5570 case Expr::ArraySubscriptExprClass:
5571 case Expr::MemberExprClass:
5572 case Expr::CompoundAssignOperatorClass:
5573 case Expr::CompoundLiteralExprClass:
5574 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00005575 case Expr::DesignatedInitExprClass:
5576 case Expr::ImplicitValueInitExprClass:
5577 case Expr::ParenListExprClass:
5578 case Expr::VAArgExprClass:
5579 case Expr::AddrLabelExprClass:
5580 case Expr::StmtExprClass:
5581 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00005582 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00005583 case Expr::CXXDynamicCastExprClass:
5584 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00005585 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00005586 case Expr::CXXNullPtrLiteralExprClass:
5587 case Expr::CXXThisExprClass:
5588 case Expr::CXXThrowExprClass:
5589 case Expr::CXXNewExprClass:
5590 case Expr::CXXDeleteExprClass:
5591 case Expr::CXXPseudoDestructorExprClass:
5592 case Expr::UnresolvedLookupExprClass:
5593 case Expr::DependentScopeDeclRefExprClass:
5594 case Expr::CXXConstructExprClass:
5595 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00005596 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00005597 case Expr::CXXTemporaryObjectExprClass:
5598 case Expr::CXXUnresolvedConstructExprClass:
5599 case Expr::CXXDependentScopeMemberExprClass:
5600 case Expr::UnresolvedMemberExprClass:
5601 case Expr::ObjCStringLiteralClass:
5602 case Expr::ObjCEncodeExprClass:
5603 case Expr::ObjCMessageExprClass:
5604 case Expr::ObjCSelectorExprClass:
5605 case Expr::ObjCProtocolExprClass:
5606 case Expr::ObjCIvarRefExprClass:
5607 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00005608 case Expr::ObjCIsaExprClass:
5609 case Expr::ShuffleVectorExprClass:
5610 case Expr::BlockExprClass:
5611 case Expr::BlockDeclRefExprClass:
5612 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00005613 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00005614 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00005615 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00005616 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00005617 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00005618 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00005619 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00005620 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00005621 case Expr::InitListExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00005622 return ICEDiag(2, E->getLocStart());
5623
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005624 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00005625 case Expr::GNUNullExprClass:
5626 // GCC considers the GNU __null value to be an integral constant expression.
5627 return NoDiag();
5628
John McCall7c454bb2011-07-15 05:09:51 +00005629 case Expr::SubstNonTypeTemplateParmExprClass:
5630 return
5631 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
5632
John McCall864e3962010-05-07 05:32:02 +00005633 case Expr::ParenExprClass:
5634 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00005635 case Expr::GenericSelectionExprClass:
5636 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005637 case Expr::IntegerLiteralClass:
5638 case Expr::CharacterLiteralClass:
5639 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00005640 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00005641 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005642 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00005643 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00005644 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00005645 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00005646 return NoDiag();
5647 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00005648 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00005649 // C99 6.6/3 allows function calls within unevaluated subexpressions of
5650 // constant expressions, but they can never be ICEs because an ICE cannot
5651 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00005652 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005653 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00005654 return CheckEvalInICE(E, Ctx);
5655 return ICEDiag(2, E->getLocStart());
5656 }
5657 case Expr::DeclRefExprClass:
5658 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
5659 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00005660 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00005661 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
5662
5663 // Parameter variables are never constants. Without this check,
5664 // getAnyInitializer() can find a default argument, which leads
5665 // to chaos.
5666 if (isa<ParmVarDecl>(D))
5667 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5668
5669 // C++ 7.1.5.1p2
5670 // A variable of non-volatile const-qualified integral or enumeration
5671 // type initialized by an ICE can be used in ICEs.
5672 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00005673 if (!Dcl->getType()->isIntegralOrEnumerationType())
5674 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5675
Richard Smithd0b4dd62011-12-19 06:19:21 +00005676 const VarDecl *VD;
5677 // Look for a declaration of this variable that has an initializer, and
5678 // check whether it is an ICE.
5679 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
5680 return NoDiag();
5681 else
5682 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00005683 }
5684 }
5685 return ICEDiag(2, E->getLocStart());
5686 case Expr::UnaryOperatorClass: {
5687 const UnaryOperator *Exp = cast<UnaryOperator>(E);
5688 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00005689 case UO_PostInc:
5690 case UO_PostDec:
5691 case UO_PreInc:
5692 case UO_PreDec:
5693 case UO_AddrOf:
5694 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00005695 // C99 6.6/3 allows increment and decrement within unevaluated
5696 // subexpressions of constant expressions, but they can never be ICEs
5697 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00005698 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00005699 case UO_Extension:
5700 case UO_LNot:
5701 case UO_Plus:
5702 case UO_Minus:
5703 case UO_Not:
5704 case UO_Real:
5705 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00005706 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005707 }
5708
5709 // OffsetOf falls through here.
5710 }
5711 case Expr::OffsetOfExprClass: {
5712 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00005713 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00005714 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00005715 // compliance: we should warn earlier for offsetof expressions with
5716 // array subscripts that aren't ICEs, and if the array subscripts
5717 // are ICEs, the value of the offsetof must be an integer constant.
5718 return CheckEvalInICE(E, Ctx);
5719 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00005720 case Expr::UnaryExprOrTypeTraitExprClass: {
5721 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
5722 if ((Exp->getKind() == UETT_SizeOf) &&
5723 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00005724 return ICEDiag(2, E->getLocStart());
5725 return NoDiag();
5726 }
5727 case Expr::BinaryOperatorClass: {
5728 const BinaryOperator *Exp = cast<BinaryOperator>(E);
5729 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00005730 case BO_PtrMemD:
5731 case BO_PtrMemI:
5732 case BO_Assign:
5733 case BO_MulAssign:
5734 case BO_DivAssign:
5735 case BO_RemAssign:
5736 case BO_AddAssign:
5737 case BO_SubAssign:
5738 case BO_ShlAssign:
5739 case BO_ShrAssign:
5740 case BO_AndAssign:
5741 case BO_XorAssign:
5742 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00005743 // C99 6.6/3 allows assignments within unevaluated subexpressions of
5744 // constant expressions, but they can never be ICEs because an ICE cannot
5745 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00005746 return ICEDiag(2, E->getLocStart());
5747
John McCalle3027922010-08-25 11:45:40 +00005748 case BO_Mul:
5749 case BO_Div:
5750 case BO_Rem:
5751 case BO_Add:
5752 case BO_Sub:
5753 case BO_Shl:
5754 case BO_Shr:
5755 case BO_LT:
5756 case BO_GT:
5757 case BO_LE:
5758 case BO_GE:
5759 case BO_EQ:
5760 case BO_NE:
5761 case BO_And:
5762 case BO_Xor:
5763 case BO_Or:
5764 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00005765 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5766 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00005767 if (Exp->getOpcode() == BO_Div ||
5768 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00005769 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00005770 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00005771 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00005772 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00005773 if (REval == 0)
5774 return ICEDiag(1, E->getLocStart());
5775 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00005776 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00005777 if (LEval.isMinSignedValue())
5778 return ICEDiag(1, E->getLocStart());
5779 }
5780 }
5781 }
John McCalle3027922010-08-25 11:45:40 +00005782 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00005783 if (Ctx.getLangOptions().C99) {
5784 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
5785 // if it isn't evaluated.
5786 if (LHSResult.Val == 0 && RHSResult.Val == 0)
5787 return ICEDiag(1, E->getLocStart());
5788 } else {
5789 // In both C89 and C++, commas in ICEs are illegal.
5790 return ICEDiag(2, E->getLocStart());
5791 }
5792 }
5793 if (LHSResult.Val >= RHSResult.Val)
5794 return LHSResult;
5795 return RHSResult;
5796 }
John McCalle3027922010-08-25 11:45:40 +00005797 case BO_LAnd:
5798 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00005799 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5800 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
5801 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
5802 // Rare case where the RHS has a comma "side-effect"; we need
5803 // to actually check the condition to see whether the side
5804 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00005805 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00005806 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00005807 return RHSResult;
5808 return NoDiag();
5809 }
5810
5811 if (LHSResult.Val >= RHSResult.Val)
5812 return LHSResult;
5813 return RHSResult;
5814 }
5815 }
5816 }
5817 case Expr::ImplicitCastExprClass:
5818 case Expr::CStyleCastExprClass:
5819 case Expr::CXXFunctionalCastExprClass:
5820 case Expr::CXXStaticCastExprClass:
5821 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00005822 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005823 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00005824 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00005825 if (isa<ExplicitCastExpr>(E)) {
5826 if (const FloatingLiteral *FL
5827 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
5828 unsigned DestWidth = Ctx.getIntWidth(E->getType());
5829 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
5830 APSInt IgnoredVal(DestWidth, !DestSigned);
5831 bool Ignored;
5832 // If the value does not fit in the destination type, the behavior is
5833 // undefined, so we are not required to treat it as a constant
5834 // expression.
5835 if (FL->getValue().convertToInteger(IgnoredVal,
5836 llvm::APFloat::rmTowardZero,
5837 &Ignored) & APFloat::opInvalidOp)
5838 return ICEDiag(2, E->getLocStart());
5839 return NoDiag();
5840 }
5841 }
Eli Friedman76d4e432011-09-29 21:49:34 +00005842 switch (cast<CastExpr>(E)->getCastKind()) {
5843 case CK_LValueToRValue:
5844 case CK_NoOp:
5845 case CK_IntegralToBoolean:
5846 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00005847 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00005848 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00005849 return ICEDiag(2, E->getLocStart());
5850 }
John McCall864e3962010-05-07 05:32:02 +00005851 }
John McCallc07a0c72011-02-17 10:25:35 +00005852 case Expr::BinaryConditionalOperatorClass: {
5853 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
5854 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
5855 if (CommonResult.Val == 2) return CommonResult;
5856 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
5857 if (FalseResult.Val == 2) return FalseResult;
5858 if (CommonResult.Val == 1) return CommonResult;
5859 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00005860 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00005861 return FalseResult;
5862 }
John McCall864e3962010-05-07 05:32:02 +00005863 case Expr::ConditionalOperatorClass: {
5864 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
5865 // If the condition (ignoring parens) is a __builtin_constant_p call,
5866 // then only the true side is actually considered in an integer constant
5867 // expression, and it is fully evaluated. This is an important GNU
5868 // extension. See GCC PR38377 for discussion.
5869 if (const CallExpr *CallCE
5870 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00005871 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
5872 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00005873 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005874 if (CondResult.Val == 2)
5875 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005876
Richard Smithf57d8cb2011-12-09 22:58:01 +00005877 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
5878 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005879
John McCall864e3962010-05-07 05:32:02 +00005880 if (TrueResult.Val == 2)
5881 return TrueResult;
5882 if (FalseResult.Val == 2)
5883 return FalseResult;
5884 if (CondResult.Val == 1)
5885 return CondResult;
5886 if (TrueResult.Val == 0 && FalseResult.Val == 0)
5887 return NoDiag();
5888 // Rare case where the diagnostics depend on which side is evaluated
5889 // Note that if we get here, CondResult is 0, and at least one of
5890 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00005891 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00005892 return FalseResult;
5893 }
5894 return TrueResult;
5895 }
5896 case Expr::CXXDefaultArgExprClass:
5897 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
5898 case Expr::ChooseExprClass: {
5899 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
5900 }
5901 }
5902
5903 // Silence a GCC warning
5904 return ICEDiag(2, E->getLocStart());
5905}
5906
Richard Smithf57d8cb2011-12-09 22:58:01 +00005907/// Evaluate an expression as a C++11 integral constant expression.
5908static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
5909 const Expr *E,
5910 llvm::APSInt *Value,
5911 SourceLocation *Loc) {
5912 if (!E->getType()->isIntegralOrEnumerationType()) {
5913 if (Loc) *Loc = E->getExprLoc();
5914 return false;
5915 }
5916
5917 Expr::EvalResult Result;
Richard Smith92b1ce02011-12-12 09:28:41 +00005918 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
5919 Result.Diag = &Diags;
5920 EvalInfo Info(Ctx, Result);
5921
5922 bool IsICE = EvaluateAsRValue(Info, E, Result.Val);
5923 if (!Diags.empty()) {
5924 IsICE = false;
5925 if (Loc) *Loc = Diags[0].first;
5926 } else if (!IsICE && Loc) {
5927 *Loc = E->getExprLoc();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005928 }
Richard Smith92b1ce02011-12-12 09:28:41 +00005929
5930 if (!IsICE)
5931 return false;
5932
5933 assert(Result.Val.isInt() && "pointer cast to int is not an ICE");
5934 if (Value) *Value = Result.Val.getInt();
5935 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005936}
5937
Richard Smith92b1ce02011-12-12 09:28:41 +00005938bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005939 if (Ctx.getLangOptions().CPlusPlus0x)
5940 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
5941
John McCall864e3962010-05-07 05:32:02 +00005942 ICEDiag d = CheckICE(this, Ctx);
5943 if (d.Val != 0) {
5944 if (Loc) *Loc = d.Loc;
5945 return false;
5946 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005947 return true;
5948}
5949
5950bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
5951 SourceLocation *Loc, bool isEvaluated) const {
5952 if (Ctx.getLangOptions().CPlusPlus0x)
5953 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
5954
5955 if (!isIntegerConstantExpr(Ctx, Loc))
5956 return false;
5957 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00005958 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00005959 return true;
5960}