blob: 1ad17ea376ed166de27109290b018f1f4e8fa334 [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
1857 // Reserve space for the struct members.
1858 const CXXRecordDecl *RD = Definition->getParent();
Richard Smithfddd3842011-12-30 21:15:51 +00001859 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00001860 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1861 std::distance(RD->field_begin(), RD->field_end()));
1862
1863 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1864
1865 unsigned BasesSeen = 0;
1866#ifndef NDEBUG
1867 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1868#endif
1869 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1870 E = Definition->init_end(); I != E; ++I) {
1871 if ((*I)->isBaseInitializer()) {
1872 QualType BaseType((*I)->getBaseClass(), 0);
1873#ifndef NDEBUG
1874 // Non-virtual base classes are initialized in the order in the class
1875 // definition. We cannot have a virtual base class for a literal type.
1876 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1877 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1878 "base class initializers not in expected order");
1879 ++BaseIt;
1880#endif
1881 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00001882 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smithd62306a2011-11-10 06:34:14 +00001883 BaseType->getAsCXXRecordDecl(), &Layout);
1884 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1885 Subobject, (*I)->getInit()))
1886 return false;
1887 } else if (FieldDecl *FD = (*I)->getMember()) {
1888 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00001889 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smithd62306a2011-11-10 06:34:14 +00001890 if (RD->isUnion()) {
1891 Result = APValue(FD);
Richard Smith357362d2011-12-13 06:39:58 +00001892 if (!EvaluateConstantExpression(Result.getUnionValue(), Info, Subobject,
1893 (*I)->getInit(), CCEK_MemberInit))
Richard Smithd62306a2011-11-10 06:34:14 +00001894 return false;
1895 } else if (!EvaluateConstantExpression(
1896 Result.getStructField(FD->getFieldIndex()),
Richard Smith357362d2011-12-13 06:39:58 +00001897 Info, Subobject, (*I)->getInit(), CCEK_MemberInit))
Richard Smithd62306a2011-11-10 06:34:14 +00001898 return false;
1899 } else {
1900 // FIXME: handle indirect field initializers
Richard Smith92b1ce02011-12-12 09:28:41 +00001901 Info.Diag((*I)->getInit()->getExprLoc(),
Richard Smithf57d8cb2011-12-09 22:58:01 +00001902 diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +00001903 return false;
1904 }
1905 }
1906
1907 return true;
1908}
1909
Richard Smith254a73d2011-10-28 22:34:42 +00001910namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001911class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +00001912 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +00001913 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +00001914public:
1915
Richard Smith725810a2011-10-16 21:26:27 +00001916 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +00001917
1918 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +00001919 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +00001920 return true;
1921 }
1922
Peter Collingbournee9200682011-05-13 03:29:01 +00001923 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1924 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001925 return Visit(E->getResultExpr());
1926 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001927 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001928 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001929 return true;
1930 return false;
1931 }
John McCall31168b02011-06-15 23:02:42 +00001932 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001933 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001934 return true;
1935 return false;
1936 }
1937 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001938 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001939 return true;
1940 return false;
1941 }
1942
Mike Stump876387b2009-10-27 22:09:17 +00001943 // We don't want to evaluate BlockExprs multiple times, as they generate
1944 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +00001945 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1946 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1947 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +00001948 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001949 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1950 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1951 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1952 bool VisitStringLiteral(const StringLiteral *E) { return false; }
1953 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1954 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +00001955 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +00001956 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001957 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001958 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +00001959 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001960 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
1961 bool VisitBinAssign(const BinaryOperator *E) { return true; }
1962 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
1963 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001964 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001965 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
1966 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
1967 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
1968 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
1969 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001970 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001971 return true;
Mike Stumpfa502902009-10-29 20:48:09 +00001972 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +00001973 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001974 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +00001975
1976 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +00001977 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +00001978 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
1979 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00001980 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +00001981 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +00001982 return false;
1983 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001984
Peter Collingbournee9200682011-05-13 03:29:01 +00001985 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +00001986};
1987
John McCallc07a0c72011-02-17 10:25:35 +00001988class OpaqueValueEvaluation {
1989 EvalInfo &info;
1990 OpaqueValueExpr *opaqueValue;
1991
1992public:
1993 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
1994 Expr *value)
1995 : info(info), opaqueValue(opaqueValue) {
1996
1997 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +00001998 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +00001999 this->opaqueValue = 0;
2000 return;
2001 }
John McCallc07a0c72011-02-17 10:25:35 +00002002 }
2003
2004 bool hasError() const { return opaqueValue == 0; }
2005
2006 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +00002007 // FIXME: This will not work for recursive constexpr functions using opaque
2008 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +00002009 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2010 }
2011};
2012
Mike Stump876387b2009-10-27 22:09:17 +00002013} // end anonymous namespace
2014
Eli Friedman9a156e52008-11-12 09:44:48 +00002015//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00002016// Generic Evaluation
2017//===----------------------------------------------------------------------===//
2018namespace {
2019
Richard Smithf57d8cb2011-12-09 22:58:01 +00002020// FIXME: RetTy is always bool. Remove it.
2021template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00002022class ExprEvaluatorBase
2023 : public ConstStmtVisitor<Derived, RetTy> {
2024private:
Richard Smith0b0a0b62011-10-29 20:57:55 +00002025 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002026 return static_cast<Derived*>(this)->Success(V, E);
2027 }
Richard Smithfddd3842011-12-30 21:15:51 +00002028 RetTy DerivedZeroInitialization(const Expr *E) {
2029 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002030 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002031
2032protected:
2033 EvalInfo &Info;
2034 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2035 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2036
Richard Smith92b1ce02011-12-12 09:28:41 +00002037 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith187ef012011-12-12 09:41:58 +00002038 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002039 }
2040
2041 /// Report an evaluation error. This should only be called when an error is
2042 /// first discovered. When propagating an error, just return false.
2043 bool Error(const Expr *E, diag::kind D) {
Richard Smith92b1ce02011-12-12 09:28:41 +00002044 Info.Diag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002045 return false;
2046 }
2047 bool Error(const Expr *E) {
2048 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2049 }
2050
Richard Smithfddd3842011-12-30 21:15:51 +00002051 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00002052
Peter Collingbournee9200682011-05-13 03:29:01 +00002053public:
2054 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2055
2056 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00002057 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00002058 }
2059 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002060 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002061 }
2062
2063 RetTy VisitParenExpr(const ParenExpr *E)
2064 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2065 RetTy VisitUnaryExtension(const UnaryOperator *E)
2066 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2067 RetTy VisitUnaryPlus(const UnaryOperator *E)
2068 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2069 RetTy VisitChooseExpr(const ChooseExpr *E)
2070 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2071 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2072 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00002073 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2074 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00002075 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2076 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00002077 // We cannot create any objects for which cleanups are required, so there is
2078 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2079 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2080 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002081
Richard Smith6d6ecc32011-12-12 12:46:16 +00002082 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2083 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2084 return static_cast<Derived*>(this)->VisitCastExpr(E);
2085 }
2086 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2087 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2088 return static_cast<Derived*>(this)->VisitCastExpr(E);
2089 }
2090
Richard Smith027bf112011-11-17 22:56:20 +00002091 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2092 switch (E->getOpcode()) {
2093 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00002094 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002095
2096 case BO_Comma:
2097 VisitIgnoredValue(E->getLHS());
2098 return StmtVisitorTy::Visit(E->getRHS());
2099
2100 case BO_PtrMemD:
2101 case BO_PtrMemI: {
2102 LValue Obj;
2103 if (!HandleMemberPointerAccess(Info, E, Obj))
2104 return false;
2105 CCValue Result;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002106 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00002107 return false;
2108 return DerivedSuccess(Result, E);
2109 }
2110 }
2111 }
2112
Peter Collingbournee9200682011-05-13 03:29:01 +00002113 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2114 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2115 if (opaque.hasError())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002116 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002117
2118 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +00002119 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002120 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002121
2122 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
2123 }
2124
2125 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
2126 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00002127 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002128 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002129
Richard Smith11562c52011-10-28 17:51:58 +00002130 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +00002131 return StmtVisitorTy::Visit(EvalExpr);
2132 }
2133
2134 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002135 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002136 if (!Value) {
2137 const Expr *Source = E->getSourceExpr();
2138 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002139 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002140 if (Source == E) { // sanity checking.
2141 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00002142 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002143 }
2144 return StmtVisitorTy::Visit(Source);
2145 }
Richard Smith0b0a0b62011-10-29 20:57:55 +00002146 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002147 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002148
Richard Smith254a73d2011-10-28 22:34:42 +00002149 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002150 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00002151 QualType CalleeType = Callee->getType();
2152
Richard Smith254a73d2011-10-28 22:34:42 +00002153 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00002154 LValue *This = 0, ThisVal;
2155 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith656d49d2011-11-10 09:31:24 +00002156
Richard Smithe97cbd72011-11-11 04:05:33 +00002157 // Extract function decl and 'this' pointer from the callee.
2158 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002159 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00002160 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2161 // Explicit bound member calls, such as x.f() or p->g();
2162 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002163 return false;
2164 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00002165 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00002166 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2167 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00002168 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2169 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00002170 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00002171 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002172 return Error(Callee);
2173
2174 FD = dyn_cast<FunctionDecl>(Member);
2175 if (!FD)
2176 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002177 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002178 LValue Call;
2179 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002180 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00002181
Richard Smitha8105bc2012-01-06 16:39:00 +00002182 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002183 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00002184 FD = dyn_cast_or_null<FunctionDecl>(
2185 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00002186 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002187 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002188
2189 // Overloaded operator calls to member functions are represented as normal
2190 // calls with '*this' as the first argument.
2191 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2192 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002193 // FIXME: When selecting an implicit conversion for an overloaded
2194 // operator delete, we sometimes try to evaluate calls to conversion
2195 // operators without a 'this' parameter!
2196 if (Args.empty())
2197 return Error(E);
2198
Richard Smithe97cbd72011-11-11 04:05:33 +00002199 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2200 return false;
2201 This = &ThisVal;
2202 Args = Args.slice(1);
2203 }
2204
2205 // Don't call function pointers which have been cast to some other type.
2206 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002207 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00002208 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002209 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00002210
Richard Smith357362d2011-12-13 06:39:58 +00002211 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00002212 Stmt *Body = FD->getBody(Definition);
Richard Smithed5165f2011-11-04 05:33:44 +00002213 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00002214
Richard Smith357362d2011-12-13 06:39:58 +00002215 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smithf6f003a2011-12-16 19:06:07 +00002216 !HandleFunctionCall(E, Definition, This, Args, Body, Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002217 return false;
2218
Richard Smitha8105bc2012-01-06 16:39:00 +00002219 return DerivedSuccess(CCValue(Info.Ctx, Result, CCValue::GlobalValue()), E);
Richard Smith254a73d2011-10-28 22:34:42 +00002220 }
2221
Richard Smith11562c52011-10-28 17:51:58 +00002222 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2223 return StmtVisitorTy::Visit(E->getInitializer());
2224 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002225 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00002226 if (E->getNumInits() == 0)
2227 return DerivedZeroInitialization(E);
2228 if (E->getNumInits() == 1)
2229 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00002230 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002231 }
2232 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002233 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002234 }
2235 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002236 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002237 }
Richard Smith027bf112011-11-17 22:56:20 +00002238 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002239 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00002240 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002241
Richard Smithd62306a2011-11-10 06:34:14 +00002242 /// A member expression where the object is a prvalue is itself a prvalue.
2243 RetTy VisitMemberExpr(const MemberExpr *E) {
2244 assert(!E->isArrow() && "missing call to bound member function?");
2245
2246 CCValue Val;
2247 if (!Evaluate(Val, Info, E->getBase()))
2248 return false;
2249
2250 QualType BaseTy = E->getBase()->getType();
2251
2252 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00002253 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002254 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2255 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2256 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2257
Richard Smitha8105bc2012-01-06 16:39:00 +00002258 SubobjectDesignator Designator(BaseTy);
2259 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00002260
Richard Smithf57d8cb2011-12-09 22:58:01 +00002261 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smithd62306a2011-11-10 06:34:14 +00002262 DerivedSuccess(Val, E);
2263 }
2264
Richard Smith11562c52011-10-28 17:51:58 +00002265 RetTy VisitCastExpr(const CastExpr *E) {
2266 switch (E->getCastKind()) {
2267 default:
2268 break;
2269
2270 case CK_NoOp:
2271 return StmtVisitorTy::Visit(E->getSubExpr());
2272
2273 case CK_LValueToRValue: {
2274 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002275 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2276 return false;
2277 CCValue RVal;
2278 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2279 return false;
2280 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00002281 }
2282 }
2283
Richard Smithf57d8cb2011-12-09 22:58:01 +00002284 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002285 }
2286
Richard Smith4a678122011-10-24 18:44:57 +00002287 /// Visit a value which is evaluated, but whose value is ignored.
2288 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002289 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +00002290 if (!Evaluate(Scratch, Info, E))
2291 Info.EvalStatus.HasSideEffects = true;
2292 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002293};
2294
2295}
2296
2297//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002298// Common base class for lvalue and temporary evaluation.
2299//===----------------------------------------------------------------------===//
2300namespace {
2301template<class Derived>
2302class LValueExprEvaluatorBase
2303 : public ExprEvaluatorBase<Derived, bool> {
2304protected:
2305 LValue &Result;
2306 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2307 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2308
2309 bool Success(APValue::LValueBase B) {
2310 Result.set(B);
2311 return true;
2312 }
2313
2314public:
2315 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2316 ExprEvaluatorBaseTy(Info), Result(Result) {}
2317
2318 bool Success(const CCValue &V, const Expr *E) {
2319 Result.setFrom(V);
2320 return true;
2321 }
Richard Smith027bf112011-11-17 22:56:20 +00002322
Richard Smith027bf112011-11-17 22:56:20 +00002323 bool VisitMemberExpr(const MemberExpr *E) {
2324 // Handle non-static data members.
2325 QualType BaseTy;
2326 if (E->isArrow()) {
2327 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2328 return false;
2329 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00002330 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002331 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00002332 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2333 return false;
2334 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00002335 } else {
2336 if (!this->Visit(E->getBase()))
2337 return false;
2338 BaseTy = E->getBase()->getType();
2339 }
Richard Smith027bf112011-11-17 22:56:20 +00002340
2341 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2342 // FIXME: Handle IndirectFieldDecls
Richard Smithf57d8cb2011-12-09 22:58:01 +00002343 if (!FD) return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002344 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2345 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2346 (void)BaseTy;
2347
Richard Smitha8105bc2012-01-06 16:39:00 +00002348 HandleLValueMember(this->Info, E, Result, FD);
Richard Smith027bf112011-11-17 22:56:20 +00002349
2350 if (FD->getType()->isReferenceType()) {
2351 CCValue RefValue;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002352 if (!HandleLValueToRValueConversion(this->Info, E, FD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002353 RefValue))
2354 return false;
2355 return Success(RefValue, E);
2356 }
2357 return true;
2358 }
2359
2360 bool VisitBinaryOperator(const BinaryOperator *E) {
2361 switch (E->getOpcode()) {
2362 default:
2363 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2364
2365 case BO_PtrMemD:
2366 case BO_PtrMemI:
2367 return HandleMemberPointerAccess(this->Info, E, Result);
2368 }
2369 }
2370
2371 bool VisitCastExpr(const CastExpr *E) {
2372 switch (E->getCastKind()) {
2373 default:
2374 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2375
2376 case CK_DerivedToBase:
2377 case CK_UncheckedDerivedToBase: {
2378 if (!this->Visit(E->getSubExpr()))
2379 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002380
2381 // Now figure out the necessary offset to add to the base LV to get from
2382 // the derived class to the base class.
2383 QualType Type = E->getSubExpr()->getType();
2384
2385 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2386 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002387 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smith027bf112011-11-17 22:56:20 +00002388 *PathI))
2389 return false;
2390 Type = (*PathI)->getType();
2391 }
2392
2393 return true;
2394 }
2395 }
2396 }
2397};
2398}
2399
2400//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00002401// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00002402//
2403// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2404// function designators (in C), decl references to void objects (in C), and
2405// temporaries (if building with -Wno-address-of-temporary).
2406//
2407// LValue evaluation produces values comprising a base expression of one of the
2408// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00002409// - Declarations
2410// * VarDecl
2411// * FunctionDecl
2412// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00002413// * CompoundLiteralExpr in C
2414// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00002415// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00002416// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00002417// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00002418// * ObjCEncodeExpr
2419// * AddrLabelExpr
2420// * BlockExpr
2421// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00002422// - Locals and temporaries
2423// * Any Expr, with a Frame indicating the function in which the temporary was
2424// evaluated.
2425// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00002426//===----------------------------------------------------------------------===//
2427namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002428class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00002429 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00002430public:
Richard Smith027bf112011-11-17 22:56:20 +00002431 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2432 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00002433
Richard Smith11562c52011-10-28 17:51:58 +00002434 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2435
Peter Collingbournee9200682011-05-13 03:29:01 +00002436 bool VisitDeclRefExpr(const DeclRefExpr *E);
2437 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002438 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002439 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2440 bool VisitMemberExpr(const MemberExpr *E);
2441 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2442 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00002443 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002444 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2445 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002446
Peter Collingbournee9200682011-05-13 03:29:01 +00002447 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00002448 switch (E->getCastKind()) {
2449 default:
Richard Smith027bf112011-11-17 22:56:20 +00002450 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002451
Eli Friedmance3e02a2011-10-11 00:13:24 +00002452 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002453 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00002454 if (!Visit(E->getSubExpr()))
2455 return false;
2456 Result.Designator.setInvalid();
2457 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00002458
Richard Smith027bf112011-11-17 22:56:20 +00002459 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00002460 if (!Visit(E->getSubExpr()))
2461 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002462 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00002463 }
2464 }
Sebastian Redl12757ab2011-09-24 17:48:14 +00002465
Eli Friedman449fe542009-03-23 04:56:01 +00002466 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +00002467
Eli Friedman9a156e52008-11-12 09:44:48 +00002468};
2469} // end anonymous namespace
2470
Richard Smith11562c52011-10-28 17:51:58 +00002471/// Evaluate an expression as an lvalue. This can be legitimately called on
2472/// expressions which are not glvalues, in a few cases:
2473/// * function designators in C,
2474/// * "extern void" objects,
2475/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +00002476static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002477 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2478 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2479 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +00002480 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002481}
2482
Peter Collingbournee9200682011-05-13 03:29:01 +00002483bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002484 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2485 return Success(FD);
2486 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00002487 return VisitVarDecl(E, VD);
2488 return Error(E);
2489}
Richard Smith733237d2011-10-24 23:14:33 +00002490
Richard Smith11562c52011-10-28 17:51:58 +00002491bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +00002492 if (!VD->getType()->isReferenceType()) {
2493 if (isa<ParmVarDecl>(VD)) {
Richard Smithce40ad62011-11-12 22:28:03 +00002494 Result.set(VD, Info.CurrentCall);
Richard Smithfec09922011-11-01 16:57:24 +00002495 return true;
2496 }
Richard Smithce40ad62011-11-12 22:28:03 +00002497 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00002498 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00002499
Richard Smith0b0a0b62011-10-29 20:57:55 +00002500 CCValue V;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002501 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2502 return false;
2503 return Success(V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00002504}
2505
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002506bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2507 const MaterializeTemporaryExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002508 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002509 if (E->getType()->isRecordType())
Richard Smith027bf112011-11-17 22:56:20 +00002510 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2511
2512 Result.set(E, Info.CurrentCall);
2513 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2514 Result, E->GetTemporaryExpr());
2515 }
2516
2517 // Materialization of an lvalue temporary occurs when we need to force a copy
2518 // (for instance, if it's a bitfield).
2519 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2520 if (!Visit(E->GetTemporaryExpr()))
2521 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002522 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002523 Info.CurrentCall->Temporaries[E]))
2524 return false;
Richard Smithce40ad62011-11-12 22:28:03 +00002525 Result.set(E, Info.CurrentCall);
Richard Smith027bf112011-11-17 22:56:20 +00002526 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002527}
2528
Peter Collingbournee9200682011-05-13 03:29:01 +00002529bool
2530LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002531 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2532 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2533 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00002534 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002535}
2536
Richard Smith6e525142011-12-27 12:18:28 +00002537bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2538 if (E->isTypeOperand())
2539 return Success(E);
2540 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2541 if (RD && RD->isPolymorphic()) {
2542 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2543 << E->getExprOperand()->getType()
2544 << E->getExprOperand()->getSourceRange();
2545 return false;
2546 }
2547 return Success(E);
2548}
2549
Peter Collingbournee9200682011-05-13 03:29:01 +00002550bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002551 // Handle static data members.
2552 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2553 VisitIgnoredValue(E->getBase());
2554 return VisitVarDecl(E, VD);
2555 }
2556
Richard Smith254a73d2011-10-28 22:34:42 +00002557 // Handle static member functions.
2558 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2559 if (MD->isStatic()) {
2560 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00002561 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00002562 }
2563 }
2564
Richard Smithd62306a2011-11-10 06:34:14 +00002565 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00002566 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002567}
2568
Peter Collingbournee9200682011-05-13 03:29:01 +00002569bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002570 // FIXME: Deal with vectors as array subscript bases.
2571 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002572 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002573
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002574 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00002575 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002576
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002577 APSInt Index;
2578 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00002579 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002580 int64_t IndexValue
2581 = Index.isSigned() ? Index.getSExtValue()
2582 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002583
Richard Smitha8105bc2012-01-06 16:39:00 +00002584 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002585}
Eli Friedman9a156e52008-11-12 09:44:48 +00002586
Peter Collingbournee9200682011-05-13 03:29:01 +00002587bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00002588 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00002589}
2590
Eli Friedman9a156e52008-11-12 09:44:48 +00002591//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00002592// Pointer Evaluation
2593//===----------------------------------------------------------------------===//
2594
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002595namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002596class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002597 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00002598 LValue &Result;
2599
Peter Collingbournee9200682011-05-13 03:29:01 +00002600 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002601 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00002602 return true;
2603 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002604public:
Mike Stump11289f42009-09-09 15:08:12 +00002605
John McCall45d55e42010-05-07 21:00:08 +00002606 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002607 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00002608
Richard Smith0b0a0b62011-10-29 20:57:55 +00002609 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002610 Result.setFrom(V);
2611 return true;
2612 }
Richard Smithfddd3842011-12-30 21:15:51 +00002613 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00002614 return Success((Expr*)0);
2615 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002616
John McCall45d55e42010-05-07 21:00:08 +00002617 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002618 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00002619 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002620 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00002621 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002622 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00002623 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002624 bool VisitCallExpr(const CallExpr *E);
2625 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00002626 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00002627 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002628 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00002629 }
Richard Smithd62306a2011-11-10 06:34:14 +00002630 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2631 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002632 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002633 Result = *Info.CurrentCall->This;
2634 return true;
2635 }
John McCallc07a0c72011-02-17 10:25:35 +00002636
Eli Friedman449fe542009-03-23 04:56:01 +00002637 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002638};
Chris Lattner05706e882008-07-11 18:11:29 +00002639} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002640
John McCall45d55e42010-05-07 21:00:08 +00002641static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002642 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00002643 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00002644}
2645
John McCall45d55e42010-05-07 21:00:08 +00002646bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002647 if (E->getOpcode() != BO_Add &&
2648 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00002649 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00002650
Chris Lattner05706e882008-07-11 18:11:29 +00002651 const Expr *PExp = E->getLHS();
2652 const Expr *IExp = E->getRHS();
2653 if (IExp->getType()->isPointerType())
2654 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00002655
John McCall45d55e42010-05-07 21:00:08 +00002656 if (!EvaluatePointer(PExp, Result, Info))
2657 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002658
John McCall45d55e42010-05-07 21:00:08 +00002659 llvm::APSInt Offset;
2660 if (!EvaluateInteger(IExp, Offset, Info))
2661 return false;
2662 int64_t AdditionalOffset
2663 = Offset.isSigned() ? Offset.getSExtValue()
2664 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00002665 if (E->getOpcode() == BO_Sub)
2666 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00002667
Richard Smithd62306a2011-11-10 06:34:14 +00002668 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00002669 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
2670 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00002671}
Eli Friedman9a156e52008-11-12 09:44:48 +00002672
John McCall45d55e42010-05-07 21:00:08 +00002673bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2674 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002675}
Mike Stump11289f42009-09-09 15:08:12 +00002676
Peter Collingbournee9200682011-05-13 03:29:01 +00002677bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2678 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00002679
Eli Friedman847a2bc2009-12-27 05:43:15 +00002680 switch (E->getCastKind()) {
2681 default:
2682 break;
2683
John McCalle3027922010-08-25 11:45:40 +00002684 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00002685 case CK_CPointerToObjCPointerCast:
2686 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00002687 case CK_AnyPointerToBlockPointerCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002688 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2689 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2690 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00002691 if (!E->getType()->isVoidPointerType()) {
2692 if (SubExpr->getType()->isVoidPointerType())
2693 CCEDiag(E, diag::note_constexpr_invalid_cast)
2694 << 3 << SubExpr->getType();
2695 else
2696 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2697 }
Richard Smith96e0c102011-11-04 02:25:55 +00002698 if (!Visit(SubExpr))
2699 return false;
2700 Result.Designator.setInvalid();
2701 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00002702
Anders Carlsson18275092010-10-31 20:41:46 +00002703 case CK_DerivedToBase:
2704 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002705 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00002706 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002707 if (!Result.Base && Result.Offset.isZero())
2708 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00002709
Richard Smithd62306a2011-11-10 06:34:14 +00002710 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00002711 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00002712 QualType Type =
2713 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00002714
Richard Smithd62306a2011-11-10 06:34:14 +00002715 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00002716 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002717 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2718 *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00002719 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002720 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00002721 }
2722
Anders Carlsson18275092010-10-31 20:41:46 +00002723 return true;
2724 }
2725
Richard Smith027bf112011-11-17 22:56:20 +00002726 case CK_BaseToDerived:
2727 if (!Visit(E->getSubExpr()))
2728 return false;
2729 if (!Result.Base && Result.Offset.isZero())
2730 return true;
2731 return HandleBaseToDerivedCast(Info, E, Result);
2732
Richard Smith0b0a0b62011-10-29 20:57:55 +00002733 case CK_NullToPointer:
Richard Smithfddd3842011-12-30 21:15:51 +00002734 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00002735
John McCalle3027922010-08-25 11:45:40 +00002736 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00002737 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2738
Richard Smith0b0a0b62011-10-29 20:57:55 +00002739 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00002740 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00002741 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00002742
John McCall45d55e42010-05-07 21:00:08 +00002743 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002744 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2745 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00002746 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002747 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithfec09922011-11-01 16:57:24 +00002748 Result.Frame = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00002749 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00002750 return true;
2751 } else {
2752 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002753 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00002754 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00002755 }
2756 }
John McCalle3027922010-08-25 11:45:40 +00002757 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00002758 if (SubExpr->isGLValue()) {
2759 if (!EvaluateLValue(SubExpr, Result, Info))
2760 return false;
2761 } else {
2762 Result.set(SubExpr, Info.CurrentCall);
2763 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2764 Info, Result, SubExpr))
2765 return false;
2766 }
Richard Smith96e0c102011-11-04 02:25:55 +00002767 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00002768 if (const ConstantArrayType *CAT
2769 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
2770 Result.addArray(Info, E, CAT);
2771 else
2772 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00002773 return true;
Richard Smithdd785442011-10-31 20:57:44 +00002774
John McCalle3027922010-08-25 11:45:40 +00002775 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00002776 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002777 }
2778
Richard Smith11562c52011-10-28 17:51:58 +00002779 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00002780}
Chris Lattner05706e882008-07-11 18:11:29 +00002781
Peter Collingbournee9200682011-05-13 03:29:01 +00002782bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00002783 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00002784 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00002785
Peter Collingbournee9200682011-05-13 03:29:01 +00002786 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002787}
Chris Lattner05706e882008-07-11 18:11:29 +00002788
2789//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002790// Member Pointer Evaluation
2791//===----------------------------------------------------------------------===//
2792
2793namespace {
2794class MemberPointerExprEvaluator
2795 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2796 MemberPtr &Result;
2797
2798 bool Success(const ValueDecl *D) {
2799 Result = MemberPtr(D);
2800 return true;
2801 }
2802public:
2803
2804 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2805 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2806
2807 bool Success(const CCValue &V, const Expr *E) {
2808 Result.setFrom(V);
2809 return true;
2810 }
Richard Smithfddd3842011-12-30 21:15:51 +00002811 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002812 return Success((const ValueDecl*)0);
2813 }
2814
2815 bool VisitCastExpr(const CastExpr *E);
2816 bool VisitUnaryAddrOf(const UnaryOperator *E);
2817};
2818} // end anonymous namespace
2819
2820static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2821 EvalInfo &Info) {
2822 assert(E->isRValue() && E->getType()->isMemberPointerType());
2823 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2824}
2825
2826bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2827 switch (E->getCastKind()) {
2828 default:
2829 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2830
2831 case CK_NullToMemberPointer:
Richard Smithfddd3842011-12-30 21:15:51 +00002832 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00002833
2834 case CK_BaseToDerivedMemberPointer: {
2835 if (!Visit(E->getSubExpr()))
2836 return false;
2837 if (E->path_empty())
2838 return true;
2839 // Base-to-derived member pointer casts store the path in derived-to-base
2840 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2841 // the wrong end of the derived->base arc, so stagger the path by one class.
2842 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2843 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2844 PathI != PathE; ++PathI) {
2845 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2846 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2847 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002848 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002849 }
2850 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2851 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002852 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002853 return true;
2854 }
2855
2856 case CK_DerivedToBaseMemberPointer:
2857 if (!Visit(E->getSubExpr()))
2858 return false;
2859 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2860 PathE = E->path_end(); PathI != PathE; ++PathI) {
2861 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2862 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2863 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002864 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002865 }
2866 return true;
2867 }
2868}
2869
2870bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2871 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
2872 // member can be formed.
2873 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
2874}
2875
2876//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00002877// Record Evaluation
2878//===----------------------------------------------------------------------===//
2879
2880namespace {
2881 class RecordExprEvaluator
2882 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
2883 const LValue &This;
2884 APValue &Result;
2885 public:
2886
2887 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
2888 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
2889
2890 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002891 return CheckConstantExpression(Info, E, V, Result);
Richard Smithd62306a2011-11-10 06:34:14 +00002892 }
Richard Smithfddd3842011-12-30 21:15:51 +00002893 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00002894
Richard Smithe97cbd72011-11-11 04:05:33 +00002895 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00002896 bool VisitInitListExpr(const InitListExpr *E);
2897 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
2898 };
2899}
2900
Richard Smithfddd3842011-12-30 21:15:51 +00002901/// Perform zero-initialization on an object of non-union class type.
2902/// C++11 [dcl.init]p5:
2903/// To zero-initialize an object or reference of type T means:
2904/// [...]
2905/// -- if T is a (possibly cv-qualified) non-union class type,
2906/// each non-static data member and each base-class subobject is
2907/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00002908static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
2909 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00002910 const LValue &This, APValue &Result) {
2911 assert(!RD->isUnion() && "Expected non-union class type");
2912 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
2913 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
2914 std::distance(RD->field_begin(), RD->field_end()));
2915
2916 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2917
2918 if (CD) {
2919 unsigned Index = 0;
2920 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00002921 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00002922 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
2923 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00002924 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
2925 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00002926 Result.getStructBase(Index)))
2927 return false;
2928 }
2929 }
2930
Richard Smitha8105bc2012-01-06 16:39:00 +00002931 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
2932 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00002933 // -- if T is a reference type, no initialization is performed.
2934 if ((*I)->getType()->isReferenceType())
2935 continue;
2936
2937 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00002938 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smithfddd3842011-12-30 21:15:51 +00002939
2940 ImplicitValueInitExpr VIE((*I)->getType());
2941 if (!EvaluateConstantExpression(
2942 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
2943 return false;
2944 }
2945
2946 return true;
2947}
2948
2949bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
2950 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2951 if (RD->isUnion()) {
2952 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
2953 // object's first non-static named data member is zero-initialized
2954 RecordDecl::field_iterator I = RD->field_begin();
2955 if (I == RD->field_end()) {
2956 Result = APValue((const FieldDecl*)0);
2957 return true;
2958 }
2959
2960 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00002961 HandleLValueMember(Info, E, Subobject, *I);
Richard Smithfddd3842011-12-30 21:15:51 +00002962 Result = APValue(*I);
2963 ImplicitValueInitExpr VIE((*I)->getType());
2964 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2965 Subobject, &VIE);
2966 }
2967
Richard Smitha8105bc2012-01-06 16:39:00 +00002968 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00002969}
2970
Richard Smithe97cbd72011-11-11 04:05:33 +00002971bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
2972 switch (E->getCastKind()) {
2973 default:
2974 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2975
2976 case CK_ConstructorConversion:
2977 return Visit(E->getSubExpr());
2978
2979 case CK_DerivedToBase:
2980 case CK_UncheckedDerivedToBase: {
2981 CCValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002982 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00002983 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002984 if (!DerivedObject.isStruct())
2985 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00002986
2987 // Derived-to-base rvalue conversion: just slice off the derived part.
2988 APValue *Value = &DerivedObject;
2989 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
2990 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2991 PathE = E->path_end(); PathI != PathE; ++PathI) {
2992 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
2993 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2994 Value = &Value->getStructBase(getBaseIndex(RD, Base));
2995 RD = Base;
2996 }
2997 Result = *Value;
2998 return true;
2999 }
3000 }
3001}
3002
Richard Smithd62306a2011-11-10 06:34:14 +00003003bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3004 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3005 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3006
3007 if (RD->isUnion()) {
3008 Result = APValue(E->getInitializedFieldInUnion());
3009 if (!E->getNumInits())
3010 return true;
3011 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00003012 HandleLValueMember(Info, E->getInit(0), Subobject,
3013 E->getInitializedFieldInUnion(), &Layout);
Richard Smithd62306a2011-11-10 06:34:14 +00003014 return EvaluateConstantExpression(Result.getUnionValue(), Info,
3015 Subobject, E->getInit(0));
3016 }
3017
3018 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3019 "initializer list for class with base classes");
3020 Result = APValue(APValue::UninitStruct(), 0,
3021 std::distance(RD->field_begin(), RD->field_end()));
3022 unsigned ElementNo = 0;
3023 for (RecordDecl::field_iterator Field = RD->field_begin(),
3024 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3025 // Anonymous bit-fields are not considered members of the class for
3026 // purposes of aggregate initialization.
3027 if (Field->isUnnamedBitfield())
3028 continue;
3029
3030 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00003031
3032 if (ElementNo < E->getNumInits()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003033 HandleLValueMember(Info, E->getInit(ElementNo), Subobject, *Field,
3034 &Layout);
Richard Smithd62306a2011-11-10 06:34:14 +00003035 if (!EvaluateConstantExpression(
3036 Result.getStructField((*Field)->getFieldIndex()),
3037 Info, Subobject, E->getInit(ElementNo++)))
3038 return false;
3039 } else {
3040 // Perform an implicit value-initialization for members beyond the end of
3041 // the initializer list.
Richard Smitha8105bc2012-01-06 16:39:00 +00003042 HandleLValueMember(Info, E, Subobject, *Field, &Layout);
Richard Smithd62306a2011-11-10 06:34:14 +00003043 ImplicitValueInitExpr VIE(Field->getType());
3044 if (!EvaluateConstantExpression(
3045 Result.getStructField((*Field)->getFieldIndex()),
3046 Info, Subobject, &VIE))
3047 return false;
3048 }
3049 }
3050
3051 return true;
3052}
3053
3054bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3055 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithfddd3842011-12-30 21:15:51 +00003056 bool ZeroInit = E->requiresZeroInitialization();
3057 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
3058 if (ZeroInit)
3059 return ZeroInitialization(E);
3060
Richard Smithcc36f692011-12-22 02:22:31 +00003061 const CXXRecordDecl *RD = FD->getParent();
3062 if (RD->isUnion())
3063 Result = APValue((FieldDecl*)0);
3064 else
3065 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3066 std::distance(RD->field_begin(), RD->field_end()));
3067 return true;
3068 }
3069
Richard Smithd62306a2011-11-10 06:34:14 +00003070 const FunctionDecl *Definition = 0;
3071 FD->getBody(Definition);
3072
Richard Smith357362d2011-12-13 06:39:58 +00003073 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3074 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003075
3076 // FIXME: Elide the copy/move construction wherever we can.
Richard Smithfddd3842011-12-30 21:15:51 +00003077 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00003078 if (const MaterializeTemporaryExpr *ME
3079 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3080 return Visit(ME->GetTemporaryExpr());
3081
Richard Smithfddd3842011-12-30 21:15:51 +00003082 if (ZeroInit && !ZeroInitialization(E))
3083 return false;
3084
Richard Smithd62306a2011-11-10 06:34:14 +00003085 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003086 return HandleConstructorCall(E, This, Args,
3087 cast<CXXConstructorDecl>(Definition), Info,
3088 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00003089}
3090
3091static bool EvaluateRecord(const Expr *E, const LValue &This,
3092 APValue &Result, EvalInfo &Info) {
3093 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00003094 "can't evaluate expression as a record rvalue");
3095 return RecordExprEvaluator(Info, This, Result).Visit(E);
3096}
3097
3098//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003099// Temporary Evaluation
3100//
3101// Temporaries are represented in the AST as rvalues, but generally behave like
3102// lvalues. The full-object of which the temporary is a subobject is implicitly
3103// materialized so that a reference can bind to it.
3104//===----------------------------------------------------------------------===//
3105namespace {
3106class TemporaryExprEvaluator
3107 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3108public:
3109 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3110 LValueExprEvaluatorBaseTy(Info, Result) {}
3111
3112 /// Visit an expression which constructs the value of this temporary.
3113 bool VisitConstructExpr(const Expr *E) {
3114 Result.set(E, Info.CurrentCall);
3115 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
3116 Result, E);
3117 }
3118
3119 bool VisitCastExpr(const CastExpr *E) {
3120 switch (E->getCastKind()) {
3121 default:
3122 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3123
3124 case CK_ConstructorConversion:
3125 return VisitConstructExpr(E->getSubExpr());
3126 }
3127 }
3128 bool VisitInitListExpr(const InitListExpr *E) {
3129 return VisitConstructExpr(E);
3130 }
3131 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3132 return VisitConstructExpr(E);
3133 }
3134 bool VisitCallExpr(const CallExpr *E) {
3135 return VisitConstructExpr(E);
3136 }
3137};
3138} // end anonymous namespace
3139
3140/// Evaluate an expression of record type as a temporary.
3141static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00003142 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00003143 return TemporaryExprEvaluator(Info, Result).Visit(E);
3144}
3145
3146//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003147// Vector Evaluation
3148//===----------------------------------------------------------------------===//
3149
3150namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003151 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00003152 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3153 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003154 public:
Mike Stump11289f42009-09-09 15:08:12 +00003155
Richard Smith2d406342011-10-22 21:10:00 +00003156 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3157 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00003158
Richard Smith2d406342011-10-22 21:10:00 +00003159 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3160 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3161 // FIXME: remove this APValue copy.
3162 Result = APValue(V.data(), V.size());
3163 return true;
3164 }
Richard Smithed5165f2011-11-04 05:33:44 +00003165 bool Success(const CCValue &V, const Expr *E) {
3166 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00003167 Result = V;
3168 return true;
3169 }
Richard Smithfddd3842011-12-30 21:15:51 +00003170 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00003171
Richard Smith2d406342011-10-22 21:10:00 +00003172 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00003173 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00003174 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00003175 bool VisitInitListExpr(const InitListExpr *E);
3176 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003177 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00003178 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00003179 // shufflevector, ExtVectorElementExpr
3180 // (Note that these require implementing conversions
3181 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003182 };
3183} // end anonymous namespace
3184
3185static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003186 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00003187 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003188}
3189
Richard Smith2d406342011-10-22 21:10:00 +00003190bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3191 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00003192 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00003193
Richard Smith161f09a2011-12-06 22:44:34 +00003194 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00003195 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003196
Eli Friedmanc757de22011-03-25 00:43:55 +00003197 switch (E->getCastKind()) {
3198 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00003199 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00003200 if (SETy->isIntegerType()) {
3201 APSInt IntResult;
3202 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003203 return false;
Richard Smith2d406342011-10-22 21:10:00 +00003204 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00003205 } else if (SETy->isRealFloatingType()) {
3206 APFloat F(0.0);
3207 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003208 return false;
Richard Smith2d406342011-10-22 21:10:00 +00003209 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00003210 } else {
Richard Smith2d406342011-10-22 21:10:00 +00003211 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003212 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00003213
3214 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00003215 SmallVector<APValue, 4> Elts(NElts, Val);
3216 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00003217 }
Eli Friedman803acb32011-12-22 03:51:45 +00003218 case CK_BitCast: {
3219 // Evaluate the operand into an APInt we can extract from.
3220 llvm::APInt SValInt;
3221 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3222 return false;
3223 // Extract the elements
3224 QualType EltTy = VTy->getElementType();
3225 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3226 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3227 SmallVector<APValue, 4> Elts;
3228 if (EltTy->isRealFloatingType()) {
3229 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3230 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3231 unsigned FloatEltSize = EltSize;
3232 if (&Sem == &APFloat::x87DoubleExtended)
3233 FloatEltSize = 80;
3234 for (unsigned i = 0; i < NElts; i++) {
3235 llvm::APInt Elt;
3236 if (BigEndian)
3237 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3238 else
3239 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3240 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3241 }
3242 } else if (EltTy->isIntegerType()) {
3243 for (unsigned i = 0; i < NElts; i++) {
3244 llvm::APInt Elt;
3245 if (BigEndian)
3246 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3247 else
3248 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3249 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3250 }
3251 } else {
3252 return Error(E);
3253 }
3254 return Success(Elts, E);
3255 }
Eli Friedmanc757de22011-03-25 00:43:55 +00003256 default:
Richard Smith11562c52011-10-28 17:51:58 +00003257 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003258 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003259}
3260
Richard Smith2d406342011-10-22 21:10:00 +00003261bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003262VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00003263 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003264 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00003265 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00003266
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003267 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003268 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003269
Eli Friedmanb9c71292012-01-03 23:24:20 +00003270 // The number of initializers can be less than the number of
3271 // vector elements. For OpenCL, this can be due to nested vector
3272 // initialization. For GCC compatibility, missing trailing elements
3273 // should be initialized with zeroes.
3274 unsigned CountInits = 0, CountElts = 0;
3275 while (CountElts < NumElements) {
3276 // Handle nested vector initialization.
3277 if (CountInits < NumInits
3278 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3279 APValue v;
3280 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3281 return Error(E);
3282 unsigned vlen = v.getVectorLength();
3283 for (unsigned j = 0; j < vlen; j++)
3284 Elements.push_back(v.getVectorElt(j));
3285 CountElts += vlen;
3286 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003287 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00003288 if (CountInits < NumInits) {
3289 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3290 return Error(E);
3291 } else // trailing integer zero.
3292 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3293 Elements.push_back(APValue(sInt));
3294 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003295 } else {
3296 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00003297 if (CountInits < NumInits) {
3298 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3299 return Error(E);
3300 } else // trailing float zero.
3301 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3302 Elements.push_back(APValue(f));
3303 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00003304 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00003305 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003306 }
Richard Smith2d406342011-10-22 21:10:00 +00003307 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003308}
3309
Richard Smith2d406342011-10-22 21:10:00 +00003310bool
Richard Smithfddd3842011-12-30 21:15:51 +00003311VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00003312 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00003313 QualType EltTy = VT->getElementType();
3314 APValue ZeroElement;
3315 if (EltTy->isIntegerType())
3316 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3317 else
3318 ZeroElement =
3319 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3320
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003321 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00003322 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003323}
3324
Richard Smith2d406342011-10-22 21:10:00 +00003325bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00003326 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00003327 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003328}
3329
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003330//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00003331// Array Evaluation
3332//===----------------------------------------------------------------------===//
3333
3334namespace {
3335 class ArrayExprEvaluator
3336 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00003337 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00003338 APValue &Result;
3339 public:
3340
Richard Smithd62306a2011-11-10 06:34:14 +00003341 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3342 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00003343
3344 bool Success(const APValue &V, const Expr *E) {
3345 assert(V.isArray() && "Expected array type");
3346 Result = V;
3347 return true;
3348 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003349
Richard Smithfddd3842011-12-30 21:15:51 +00003350 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003351 const ConstantArrayType *CAT =
3352 Info.Ctx.getAsConstantArrayType(E->getType());
3353 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003354 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003355
3356 Result = APValue(APValue::UninitArray(), 0,
3357 CAT->getSize().getZExtValue());
3358 if (!Result.hasArrayFiller()) return true;
3359
Richard Smithfddd3842011-12-30 21:15:51 +00003360 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00003361 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00003362 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00003363 ImplicitValueInitExpr VIE(CAT->getElementType());
3364 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3365 Subobject, &VIE);
3366 }
3367
Richard Smithf3e9e432011-11-07 09:22:26 +00003368 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00003369 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003370 };
3371} // end anonymous namespace
3372
Richard Smithd62306a2011-11-10 06:34:14 +00003373static bool EvaluateArray(const Expr *E, const LValue &This,
3374 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00003375 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00003376 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003377}
3378
3379bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3380 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3381 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003382 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003383
Richard Smithca2cfbf2011-12-22 01:07:19 +00003384 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3385 // an appropriately-typed string literal enclosed in braces.
3386 if (E->getNumInits() == 1 && CAT->getElementType()->isAnyCharacterType() &&
3387 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3388 LValue LV;
3389 if (!EvaluateLValue(E->getInit(0), LV, Info))
3390 return false;
3391 uint64_t NumElements = CAT->getSize().getZExtValue();
3392 Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3393
3394 // Copy the string literal into the array. FIXME: Do this better.
Richard Smitha8105bc2012-01-06 16:39:00 +00003395 LV.addArray(Info, E, CAT);
Richard Smithca2cfbf2011-12-22 01:07:19 +00003396 for (uint64_t I = 0; I < NumElements; ++I) {
3397 CCValue Char;
3398 if (!HandleLValueToRValueConversion(Info, E->getInit(0),
3399 CAT->getElementType(), LV, Char))
3400 return false;
3401 if (!CheckConstantExpression(Info, E->getInit(0), Char,
3402 Result.getArrayInitializedElt(I)))
3403 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003404 if (!HandleLValueArrayAdjustment(Info, E->getInit(0), LV,
3405 CAT->getElementType(), 1))
Richard Smithca2cfbf2011-12-22 01:07:19 +00003406 return false;
3407 }
3408 return true;
3409 }
3410
Richard Smithf3e9e432011-11-07 09:22:26 +00003411 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3412 CAT->getSize().getZExtValue());
Richard Smithd62306a2011-11-10 06:34:14 +00003413 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00003414 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00003415 unsigned Index = 0;
Richard Smithf3e9e432011-11-07 09:22:26 +00003416 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smithd62306a2011-11-10 06:34:14 +00003417 I != End; ++I, ++Index) {
3418 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
3419 Info, Subobject, cast<Expr>(*I)))
Richard Smithf3e9e432011-11-07 09:22:26 +00003420 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003421 if (!HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3422 CAT->getElementType(), 1))
Richard Smithd62306a2011-11-10 06:34:14 +00003423 return false;
3424 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003425
3426 if (!Result.hasArrayFiller()) return true;
3427 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smithd62306a2011-11-10 06:34:14 +00003428 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3429 // but sometimes does:
3430 // struct S { constexpr S() : p(&p) {} void *p; };
3431 // S s[10] = {};
Richard Smithf3e9e432011-11-07 09:22:26 +00003432 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smithd62306a2011-11-10 06:34:14 +00003433 Subobject, E->getArrayFiller());
Richard Smithf3e9e432011-11-07 09:22:26 +00003434}
3435
Richard Smith027bf112011-11-17 22:56:20 +00003436bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3437 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3438 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003439 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003440
3441 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3442 if (!Result.hasArrayFiller())
3443 return true;
3444
3445 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00003446
Richard Smithfddd3842011-12-30 21:15:51 +00003447 bool ZeroInit = E->requiresZeroInitialization();
3448 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
3449 if (ZeroInit) {
3450 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00003451 Subobject.addArray(Info, E, CAT);
Richard Smithfddd3842011-12-30 21:15:51 +00003452 ImplicitValueInitExpr VIE(CAT->getElementType());
3453 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3454 Subobject, &VIE);
3455 }
3456
Richard Smithcc36f692011-12-22 02:22:31 +00003457 const CXXRecordDecl *RD = FD->getParent();
3458 if (RD->isUnion())
3459 Result.getArrayFiller() = APValue((FieldDecl*)0);
3460 else
3461 Result.getArrayFiller() =
3462 APValue(APValue::UninitStruct(), RD->getNumBases(),
3463 std::distance(RD->field_begin(), RD->field_end()));
3464 return true;
3465 }
3466
Richard Smith027bf112011-11-17 22:56:20 +00003467 const FunctionDecl *Definition = 0;
3468 FD->getBody(Definition);
3469
Richard Smith357362d2011-12-13 06:39:58 +00003470 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3471 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003472
3473 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3474 // but sometimes does:
3475 // struct S { constexpr S() : p(&p) {} void *p; };
3476 // S s[10];
3477 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00003478 Subobject.addArray(Info, E, CAT);
Richard Smithfddd3842011-12-30 21:15:51 +00003479
3480 if (ZeroInit) {
3481 ImplicitValueInitExpr VIE(CAT->getElementType());
3482 if (!EvaluateConstantExpression(Result.getArrayFiller(), Info, Subobject,
3483 &VIE))
3484 return false;
3485 }
3486
Richard Smith027bf112011-11-17 22:56:20 +00003487 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003488 return HandleConstructorCall(E, Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00003489 cast<CXXConstructorDecl>(Definition),
3490 Info, Result.getArrayFiller());
3491}
3492
Richard Smithf3e9e432011-11-07 09:22:26 +00003493//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003494// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003495//
3496// As a GNU extension, we support casting pointers to sufficiently-wide integer
3497// types and back in constant folding. Integer values are thus represented
3498// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00003499//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003500
3501namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003502class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003503 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003504 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003505public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00003506 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003507 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00003508
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003509 bool Success(const llvm::APSInt &SI, const Expr *E) {
3510 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00003511 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003512 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003513 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003514 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003515 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003516 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003517 return true;
3518 }
3519
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003520 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003521 assert(E->getType()->isIntegralOrEnumerationType() &&
3522 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003523 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003524 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003525 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00003526 Result.getInt().setIsUnsigned(
3527 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003528 return true;
3529 }
3530
3531 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003532 assert(E->getType()->isIntegralOrEnumerationType() &&
3533 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003534 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003535 return true;
3536 }
3537
Ken Dyckdbc01912011-03-11 02:13:43 +00003538 bool Success(CharUnits Size, const Expr *E) {
3539 return Success(Size.getQuantity(), E);
3540 }
3541
Richard Smith0b0a0b62011-10-29 20:57:55 +00003542 bool Success(const CCValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00003543 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00003544 Result = V;
3545 return true;
3546 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003547 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00003548 }
Mike Stump11289f42009-09-09 15:08:12 +00003549
Richard Smithfddd3842011-12-30 21:15:51 +00003550 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00003551
Peter Collingbournee9200682011-05-13 03:29:01 +00003552 //===--------------------------------------------------------------------===//
3553 // Visitor Methods
3554 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003555
Chris Lattner7174bf32008-07-12 00:38:25 +00003556 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003557 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00003558 }
3559 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003560 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00003561 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003562
3563 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3564 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003565 if (CheckReferencedDecl(E, E->getDecl()))
3566 return true;
3567
3568 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003569 }
3570 bool VisitMemberExpr(const MemberExpr *E) {
3571 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00003572 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003573 return true;
3574 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003575
3576 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003577 }
3578
Peter Collingbournee9200682011-05-13 03:29:01 +00003579 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00003580 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00003581 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00003582 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00003583
Peter Collingbournee9200682011-05-13 03:29:01 +00003584 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003585 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00003586
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003587 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003588 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003589 }
Mike Stump11289f42009-09-09 15:08:12 +00003590
Richard Smith4ce706a2011-10-11 21:43:33 +00003591 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00003592 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003593 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003594 }
3595
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003596 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003597 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003598 }
3599
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003600 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3601 return Success(E->getValue(), E);
3602 }
3603
John Wiegley6242b6a2011-04-28 00:16:57 +00003604 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3605 return Success(E->getValue(), E);
3606 }
3607
John Wiegleyf9f65842011-04-25 06:54:41 +00003608 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3609 return Success(E->getValue(), E);
3610 }
3611
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003612 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003613 bool VisitUnaryImag(const UnaryOperator *E);
3614
Sebastian Redl5f0180d2010-09-10 20:55:47 +00003615 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003616 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00003617
Chris Lattnerf8d7f722008-07-11 21:24:13 +00003618private:
Ken Dyck160146e2010-01-27 17:10:57 +00003619 CharUnits GetAlignOfExpr(const Expr *E);
3620 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00003621 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00003622 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003623 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00003624};
Chris Lattner05706e882008-07-11 18:11:29 +00003625} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003626
Richard Smith11562c52011-10-28 17:51:58 +00003627/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3628/// produce either the integer value or a pointer.
3629///
3630/// GCC has a heinous extension which folds casts between pointer types and
3631/// pointer-sized integral types. We support this by allowing the evaluation of
3632/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3633/// Some simple arithmetic on such values is supported (they are treated much
3634/// like char*).
Richard Smithf57d8cb2011-12-09 22:58:01 +00003635static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00003636 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003637 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003638 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00003639}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003640
Richard Smithf57d8cb2011-12-09 22:58:01 +00003641static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003642 CCValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003643 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00003644 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003645 if (!Val.isInt()) {
3646 // FIXME: It would be better to produce the diagnostic for casting
3647 // a pointer to an integer.
Richard Smith92b1ce02011-12-12 09:28:41 +00003648 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003649 return false;
3650 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003651 Result = Val.getInt();
3652 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003653}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003654
Richard Smithf57d8cb2011-12-09 22:58:01 +00003655/// Check whether the given declaration can be directly converted to an integral
3656/// rvalue. If not, no diagnostic is produced; there are other things we can
3657/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003658bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00003659 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003660 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003661 // Check for signedness/width mismatches between E type and ECD value.
3662 bool SameSign = (ECD->getInitVal().isSigned()
3663 == E->getType()->isSignedIntegerOrEnumerationType());
3664 bool SameWidth = (ECD->getInitVal().getBitWidth()
3665 == Info.Ctx.getIntWidth(E->getType()));
3666 if (SameSign && SameWidth)
3667 return Success(ECD->getInitVal(), E);
3668 else {
3669 // Get rid of mismatch (otherwise Success assertions will fail)
3670 // by computing a new value matching the type of E.
3671 llvm::APSInt Val = ECD->getInitVal();
3672 if (!SameSign)
3673 Val.setIsSigned(!ECD->getInitVal().isSigned());
3674 if (!SameWidth)
3675 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3676 return Success(Val, E);
3677 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003678 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003679 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00003680}
3681
Chris Lattner86ee2862008-10-06 06:40:35 +00003682/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3683/// as GCC.
3684static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3685 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003686 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00003687 enum gcc_type_class {
3688 no_type_class = -1,
3689 void_type_class, integer_type_class, char_type_class,
3690 enumeral_type_class, boolean_type_class,
3691 pointer_type_class, reference_type_class, offset_type_class,
3692 real_type_class, complex_type_class,
3693 function_type_class, method_type_class,
3694 record_type_class, union_type_class,
3695 array_type_class, string_type_class,
3696 lang_type_class
3697 };
Mike Stump11289f42009-09-09 15:08:12 +00003698
3699 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00003700 // ideal, however it is what gcc does.
3701 if (E->getNumArgs() == 0)
3702 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00003703
Chris Lattner86ee2862008-10-06 06:40:35 +00003704 QualType ArgTy = E->getArg(0)->getType();
3705 if (ArgTy->isVoidType())
3706 return void_type_class;
3707 else if (ArgTy->isEnumeralType())
3708 return enumeral_type_class;
3709 else if (ArgTy->isBooleanType())
3710 return boolean_type_class;
3711 else if (ArgTy->isCharType())
3712 return string_type_class; // gcc doesn't appear to use char_type_class
3713 else if (ArgTy->isIntegerType())
3714 return integer_type_class;
3715 else if (ArgTy->isPointerType())
3716 return pointer_type_class;
3717 else if (ArgTy->isReferenceType())
3718 return reference_type_class;
3719 else if (ArgTy->isRealType())
3720 return real_type_class;
3721 else if (ArgTy->isComplexType())
3722 return complex_type_class;
3723 else if (ArgTy->isFunctionType())
3724 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00003725 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00003726 return record_type_class;
3727 else if (ArgTy->isUnionType())
3728 return union_type_class;
3729 else if (ArgTy->isArrayType())
3730 return array_type_class;
3731 else if (ArgTy->isUnionType())
3732 return union_type_class;
3733 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00003734 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00003735 return -1;
3736}
3737
Richard Smith5fab0c92011-12-28 19:48:30 +00003738/// EvaluateBuiltinConstantPForLValue - Determine the result of
3739/// __builtin_constant_p when applied to the given lvalue.
3740///
3741/// An lvalue is only "constant" if it is a pointer or reference to the first
3742/// character of a string literal.
3743template<typename LValue>
3744static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
3745 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
3746 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3747}
3748
3749/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
3750/// GCC as we can manage.
3751static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
3752 QualType ArgType = Arg->getType();
3753
3754 // __builtin_constant_p always has one operand. The rules which gcc follows
3755 // are not precisely documented, but are as follows:
3756 //
3757 // - If the operand is of integral, floating, complex or enumeration type,
3758 // and can be folded to a known value of that type, it returns 1.
3759 // - If the operand and can be folded to a pointer to the first character
3760 // of a string literal (or such a pointer cast to an integral type), it
3761 // returns 1.
3762 //
3763 // Otherwise, it returns 0.
3764 //
3765 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3766 // its support for this does not currently work.
3767 if (ArgType->isIntegralOrEnumerationType()) {
3768 Expr::EvalResult Result;
3769 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
3770 return false;
3771
3772 APValue &V = Result.Val;
3773 if (V.getKind() == APValue::Int)
3774 return true;
3775
3776 return EvaluateBuiltinConstantPForLValue(V);
3777 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3778 return Arg->isEvaluatable(Ctx);
3779 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3780 LValue LV;
3781 Expr::EvalStatus Status;
3782 EvalInfo Info(Ctx, Status);
3783 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
3784 : EvaluatePointer(Arg, LV, Info)) &&
3785 !Status.HasSideEffects)
3786 return EvaluateBuiltinConstantPForLValue(LV);
3787 }
3788
3789 // Anything else isn't considered to be sufficiently constant.
3790 return false;
3791}
3792
John McCall95007602010-05-10 23:27:23 +00003793/// Retrieves the "underlying object type" of the given expression,
3794/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00003795QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3796 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3797 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00003798 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00003799 } else if (const Expr *E = B.get<const Expr*>()) {
3800 if (isa<CompoundLiteralExpr>(E))
3801 return E->getType();
John McCall95007602010-05-10 23:27:23 +00003802 }
3803
3804 return QualType();
3805}
3806
Peter Collingbournee9200682011-05-13 03:29:01 +00003807bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00003808 // TODO: Perhaps we should let LLVM lower this?
3809 LValue Base;
3810 if (!EvaluatePointer(E->getArg(0), Base, Info))
3811 return false;
3812
3813 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00003814 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00003815
Richard Smithce40ad62011-11-12 22:28:03 +00003816 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00003817 if (T.isNull() ||
3818 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00003819 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00003820 T->isVariablyModifiedType() ||
3821 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003822 return Error(E);
John McCall95007602010-05-10 23:27:23 +00003823
3824 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3825 CharUnits Offset = Base.getLValueOffset();
3826
3827 if (!Offset.isNegative() && Offset <= Size)
3828 Size -= Offset;
3829 else
3830 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00003831 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00003832}
3833
Peter Collingbournee9200682011-05-13 03:29:01 +00003834bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003835 switch (E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003836 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00003837 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003838
3839 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00003840 if (TryEvaluateBuiltinObjectSize(E))
3841 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00003842
Eric Christopher99469702010-01-19 22:58:35 +00003843 // If evaluating the argument has side-effects we can't determine
3844 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003845 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00003846 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00003847 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00003848 return Success(0, E);
3849 }
Mike Stump876387b2009-10-27 22:09:17 +00003850
Richard Smithf57d8cb2011-12-09 22:58:01 +00003851 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003852 }
3853
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003854 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003855 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00003856
Richard Smith5fab0c92011-12-28 19:48:30 +00003857 case Builtin::BI__builtin_constant_p:
3858 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smith10c7c902011-12-09 02:04:48 +00003859
Chris Lattnerd545ad12009-09-23 06:06:36 +00003860 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00003861 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00003862 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00003863 return Success(Operand, E);
3864 }
Eli Friedmand5c93992010-02-13 00:10:10 +00003865
3866 case Builtin::BI__builtin_expect:
3867 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003868
3869 case Builtin::BIstrlen:
3870 case Builtin::BI__builtin_strlen:
3871 // As an extension, we support strlen() and __builtin_strlen() as constant
3872 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00003873 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003874 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
3875 // The string literal may have embedded null characters. Find the first
3876 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003877 StringRef Str = S->getString();
3878 StringRef::size_type Pos = Str.find(0);
3879 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003880 Str = Str.substr(0, Pos);
3881
3882 return Success(Str.size(), E);
3883 }
3884
Richard Smithf57d8cb2011-12-09 22:58:01 +00003885 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003886
3887 case Builtin::BI__atomic_is_lock_free: {
3888 APSInt SizeVal;
3889 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
3890 return false;
3891
3892 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
3893 // of two less than the maximum inline atomic width, we know it is
3894 // lock-free. If the size isn't a power of two, or greater than the
3895 // maximum alignment where we promote atomics, we know it is not lock-free
3896 // (at least not in the sense of atomic_is_lock_free). Otherwise,
3897 // the answer can only be determined at runtime; for example, 16-byte
3898 // atomics have lock-free implementations on some, but not all,
3899 // x86-64 processors.
3900
3901 // Check power-of-two.
3902 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
3903 if (!Size.isPowerOfTwo())
3904#if 0
3905 // FIXME: Suppress this folding until the ABI for the promotion width
3906 // settles.
3907 return Success(0, E);
3908#else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003909 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003910#endif
3911
3912#if 0
3913 // Check against promotion width.
3914 // FIXME: Suppress this folding until the ABI for the promotion width
3915 // settles.
3916 unsigned PromoteWidthBits =
3917 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
3918 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
3919 return Success(0, E);
3920#endif
3921
3922 // Check against inlining width.
3923 unsigned InlineWidthBits =
3924 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
3925 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
3926 return Success(1, E);
3927
Richard Smithf57d8cb2011-12-09 22:58:01 +00003928 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003929 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003930 }
Chris Lattner7174bf32008-07-12 00:38:25 +00003931}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003932
Richard Smith8b3497e2011-10-31 01:37:14 +00003933static bool HasSameBase(const LValue &A, const LValue &B) {
3934 if (!A.getLValueBase())
3935 return !B.getLValueBase();
3936 if (!B.getLValueBase())
3937 return false;
3938
Richard Smithce40ad62011-11-12 22:28:03 +00003939 if (A.getLValueBase().getOpaqueValue() !=
3940 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003941 const Decl *ADecl = GetLValueBaseDecl(A);
3942 if (!ADecl)
3943 return false;
3944 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00003945 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00003946 return false;
3947 }
3948
3949 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithfec09922011-11-01 16:57:24 +00003950 A.getLValueFrame() == B.getLValueFrame();
Richard Smith8b3497e2011-10-31 01:37:14 +00003951}
3952
Chris Lattnere13042c2008-07-11 19:10:17 +00003953bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003954 if (E->isAssignmentOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003955 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003956
John McCalle3027922010-08-25 11:45:40 +00003957 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00003958 VisitIgnoredValue(E->getLHS());
3959 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00003960 }
3961
3962 if (E->isLogicalOp()) {
3963 // These need to be handled specially because the operands aren't
3964 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003965 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00003966
Richard Smith11562c52011-10-28 17:51:58 +00003967 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00003968 // We were able to evaluate the LHS, see if we can get away with not
3969 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00003970 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003971 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003972
Richard Smith11562c52011-10-28 17:51:58 +00003973 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00003974 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003975 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003976 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003977 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003978 }
3979 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003980 // FIXME: If both evaluations fail, we should produce the diagnostic from
3981 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
3982 // less clear how to diagnose this.
Richard Smith11562c52011-10-28 17:51:58 +00003983 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00003984 // We can't evaluate the LHS; however, sometimes the result
3985 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003986 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003987 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003988 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00003989 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003990
3991 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003992 }
3993 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00003994 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00003995
Eli Friedman5a332ea2008-11-13 06:09:17 +00003996 return false;
3997 }
3998
Anders Carlssonacc79812008-11-16 07:17:21 +00003999 QualType LHSTy = E->getLHS()->getType();
4000 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004001
4002 if (LHSTy->isAnyComplexType()) {
4003 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00004004 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004005
4006 if (!EvaluateComplex(E->getLHS(), LHS, Info))
4007 return false;
4008
4009 if (!EvaluateComplex(E->getRHS(), RHS, Info))
4010 return false;
4011
4012 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00004013 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004014 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00004015 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004016 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4017
John McCalle3027922010-08-25 11:45:40 +00004018 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004019 return Success((CR_r == APFloat::cmpEqual &&
4020 CR_i == APFloat::cmpEqual), E);
4021 else {
John McCalle3027922010-08-25 11:45:40 +00004022 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004023 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00004024 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00004025 CR_r == APFloat::cmpLessThan ||
4026 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00004027 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00004028 CR_i == APFloat::cmpLessThan ||
4029 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004030 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004031 } else {
John McCalle3027922010-08-25 11:45:40 +00004032 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004033 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4034 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4035 else {
John McCalle3027922010-08-25 11:45:40 +00004036 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004037 "Invalid compex comparison.");
4038 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4039 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4040 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004041 }
4042 }
Mike Stump11289f42009-09-09 15:08:12 +00004043
Anders Carlssonacc79812008-11-16 07:17:21 +00004044 if (LHSTy->isRealFloatingType() &&
4045 RHSTy->isRealFloatingType()) {
4046 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00004047
Anders Carlssonacc79812008-11-16 07:17:21 +00004048 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4049 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004050
Anders Carlssonacc79812008-11-16 07:17:21 +00004051 if (!EvaluateFloat(E->getLHS(), LHS, Info))
4052 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004053
Anders Carlssonacc79812008-11-16 07:17:21 +00004054 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00004055
Anders Carlssonacc79812008-11-16 07:17:21 +00004056 switch (E->getOpcode()) {
4057 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004058 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00004059 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004060 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00004061 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004062 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00004063 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004064 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00004065 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00004066 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004067 E);
John McCalle3027922010-08-25 11:45:40 +00004068 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004069 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00004070 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00004071 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00004072 || CR == APFloat::cmpLessThan
4073 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00004074 }
Anders Carlssonacc79812008-11-16 07:17:21 +00004075 }
Mike Stump11289f42009-09-09 15:08:12 +00004076
Eli Friedmana38da572009-04-28 19:17:36 +00004077 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00004078 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCall45d55e42010-05-07 21:00:08 +00004079 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004080 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
4081 return false;
Eli Friedman64004332009-03-23 04:38:34 +00004082
John McCall45d55e42010-05-07 21:00:08 +00004083 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004084 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
4085 return false;
Eli Friedman64004332009-03-23 04:38:34 +00004086
Richard Smith8b3497e2011-10-31 01:37:14 +00004087 // Reject differing bases from the normal codepath; we special-case
4088 // comparisons to null.
4089 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004090 if (E->getOpcode() == BO_Sub) {
4091 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004092 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4093 return false;
4094 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4095 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4096 if (!LHSExpr || !RHSExpr)
4097 return false;
4098 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4099 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4100 if (!LHSAddrExpr || !RHSAddrExpr)
4101 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00004102 // Make sure both labels come from the same function.
4103 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4104 RHSAddrExpr->getLabel()->getDeclContext())
4105 return false;
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004106 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4107 return true;
4108 }
Richard Smith83c68212011-10-31 05:11:32 +00004109 // Inequalities and subtractions between unrelated pointers have
4110 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00004111 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004112 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00004113 // A constant address may compare equal to the address of a symbol.
4114 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00004115 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00004116 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4117 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004118 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00004119 // It's implementation-defined whether distinct literals will have
Eli Friedman42fbd622011-10-31 22:54:30 +00004120 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smithe9e20dd32011-11-04 01:10:57 +00004121 // distinct. However, we do know that the address of a literal will be
4122 // non-null.
4123 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4124 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004125 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00004126 // We can't tell whether weak symbols will end up pointing to the same
4127 // object.
4128 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004129 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00004130 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00004131 // (Note that clang defaults to -fmerge-all-constants, which can
4132 // lead to inconsistent results for comparisons involving the address
4133 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00004134 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00004135 }
Eli Friedman64004332009-03-23 04:38:34 +00004136
Richard Smithf3e9e432011-11-07 09:22:26 +00004137 // FIXME: Implement the C++11 restrictions:
4138 // - Pointer subtractions must be on elements of the same array.
4139 // - Pointer comparisons must be between members with the same access.
4140
John McCalle3027922010-08-25 11:45:40 +00004141 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00004142 QualType Type = E->getLHS()->getType();
4143 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004144
Richard Smithd62306a2011-11-10 06:34:14 +00004145 CharUnits ElementSize;
4146 if (!HandleSizeof(Info, ElementType, ElementSize))
4147 return false;
Eli Friedman64004332009-03-23 04:38:34 +00004148
Richard Smithd62306a2011-11-10 06:34:14 +00004149 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dyck02990832010-01-15 12:37:54 +00004150 RHSValue.getLValueOffset();
4151 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00004152 }
Richard Smith8b3497e2011-10-31 01:37:14 +00004153
4154 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4155 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4156 switch (E->getOpcode()) {
4157 default: llvm_unreachable("missing comparison operator");
4158 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4159 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4160 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4161 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4162 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4163 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmana38da572009-04-28 19:17:36 +00004164 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004165 }
4166 }
Douglas Gregorb90df602010-06-16 00:17:44 +00004167 if (!LHSTy->isIntegralOrEnumerationType() ||
4168 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smith027bf112011-11-17 22:56:20 +00004169 // We can't continue from here for non-integral types.
4170 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004171 }
4172
Anders Carlsson9c181652008-07-08 14:35:21 +00004173 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00004174 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00004175 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004176 return false;
Eli Friedmanbd840592008-07-27 05:46:18 +00004177
Richard Smith11562c52011-10-28 17:51:58 +00004178 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004179 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004180 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00004181
4182 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00004183 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00004184 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4185 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00004186 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00004187 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00004188 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00004189 LHSVal.getLValueOffset() -= AdditionalOffset;
4190 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00004191 return true;
4192 }
4193
4194 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00004195 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00004196 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004197 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4198 LHSVal.getInt().getZExtValue());
4199 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00004200 return true;
4201 }
4202
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004203 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4204 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004205 if (!LHSVal.getLValueOffset().isZero() ||
4206 !RHSVal.getLValueOffset().isZero())
4207 return false;
4208 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4209 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4210 if (!LHSExpr || !RHSExpr)
4211 return false;
4212 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4213 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4214 if (!LHSAddrExpr || !RHSAddrExpr)
4215 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00004216 // Make sure both labels come from the same function.
4217 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4218 RHSAddrExpr->getLabel()->getDeclContext())
4219 return false;
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004220 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4221 return true;
4222 }
4223
Eli Friedman94c25c62009-03-24 01:14:50 +00004224 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00004225 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004226 return Error(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004227
Richard Smith11562c52011-10-28 17:51:58 +00004228 APSInt &LHS = LHSVal.getInt();
4229 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00004230
Anders Carlsson9c181652008-07-08 14:35:21 +00004231 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00004232 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004233 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004234 case BO_Mul: return Success(LHS * RHS, E);
4235 case BO_Add: return Success(LHS + RHS, E);
4236 case BO_Sub: return Success(LHS - RHS, E);
4237 case BO_And: return Success(LHS & RHS, E);
4238 case BO_Xor: return Success(LHS ^ RHS, E);
4239 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00004240 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00004241 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004242 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00004243 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00004244 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00004245 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004246 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00004247 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00004248 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00004249 // During constant-folding, a negative shift is an opposite shift.
4250 if (RHS.isSigned() && RHS.isNegative()) {
4251 RHS = -RHS;
4252 goto shift_right;
4253 }
4254
4255 shift_left:
4256 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00004257 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4258 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004259 }
John McCalle3027922010-08-25 11:45:40 +00004260 case BO_Shr: {
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_left;
4265 }
4266
4267 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00004268 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 }
Mike Stump11289f42009-09-09 15:08:12 +00004272
Richard Smith11562c52011-10-28 17:51:58 +00004273 case BO_LT: return Success(LHS < RHS, E);
4274 case BO_GT: return Success(LHS > RHS, E);
4275 case BO_LE: return Success(LHS <= RHS, E);
4276 case BO_GE: return Success(LHS >= RHS, E);
4277 case BO_EQ: return Success(LHS == RHS, E);
4278 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00004279 }
Anders Carlsson9c181652008-07-08 14:35:21 +00004280}
4281
Ken Dyck160146e2010-01-27 17:10:57 +00004282CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00004283 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4284 // the result is the size of the referenced type."
4285 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4286 // result shall be the alignment of the referenced type."
4287 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4288 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00004289
4290 // __alignof is defined to return the preferred alignment.
4291 return Info.Ctx.toCharUnitsFromBits(
4292 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00004293}
4294
Ken Dyck160146e2010-01-27 17:10:57 +00004295CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00004296 E = E->IgnoreParens();
4297
4298 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00004299 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00004300 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00004301 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4302 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00004303
Chris Lattner68061312009-01-24 21:53:27 +00004304 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00004305 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4306 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00004307
Chris Lattner24aeeab2009-01-24 21:09:06 +00004308 return GetAlignOfType(E->getType());
4309}
4310
4311
Peter Collingbournee190dee2011-03-11 19:24:49 +00004312/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4313/// a result as the expression's type.
4314bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4315 const UnaryExprOrTypeTraitExpr *E) {
4316 switch(E->getKind()) {
4317 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00004318 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00004319 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00004320 else
Ken Dyckdbc01912011-03-11 02:13:43 +00004321 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00004322 }
Eli Friedman64004332009-03-23 04:38:34 +00004323
Peter Collingbournee190dee2011-03-11 19:24:49 +00004324 case UETT_VecStep: {
4325 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00004326
Peter Collingbournee190dee2011-03-11 19:24:49 +00004327 if (Ty->isVectorType()) {
4328 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00004329
Peter Collingbournee190dee2011-03-11 19:24:49 +00004330 // The vec_step built-in functions that take a 3-component
4331 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4332 if (n == 3)
4333 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00004334
Peter Collingbournee190dee2011-03-11 19:24:49 +00004335 return Success(n, E);
4336 } else
4337 return Success(1, E);
4338 }
4339
4340 case UETT_SizeOf: {
4341 QualType SrcTy = E->getTypeOfArgument();
4342 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4343 // the result is the size of the referenced type."
4344 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4345 // result shall be the alignment of the referenced type."
4346 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4347 SrcTy = Ref->getPointeeType();
4348
Richard Smithd62306a2011-11-10 06:34:14 +00004349 CharUnits Sizeof;
4350 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00004351 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004352 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00004353 }
4354 }
4355
4356 llvm_unreachable("unknown expr/type trait");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004357 return Error(E);
Chris Lattnerf8d7f722008-07-11 21:24:13 +00004358}
4359
Peter Collingbournee9200682011-05-13 03:29:01 +00004360bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00004361 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00004362 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00004363 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004364 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00004365 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00004366 for (unsigned i = 0; i != n; ++i) {
4367 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4368 switch (ON.getKind()) {
4369 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00004370 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00004371 APSInt IdxResult;
4372 if (!EvaluateInteger(Idx, IdxResult, Info))
4373 return false;
4374 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4375 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004376 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004377 CurrentType = AT->getElementType();
4378 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4379 Result += IdxResult.getSExtValue() * ElementSize;
4380 break;
4381 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00004382
Douglas Gregor882211c2010-04-28 22:16:22 +00004383 case OffsetOfExpr::OffsetOfNode::Field: {
4384 FieldDecl *MemberDecl = ON.getField();
4385 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00004386 if (!RT)
4387 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004388 RecordDecl *RD = RT->getDecl();
4389 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00004390 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00004391 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00004392 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00004393 CurrentType = MemberDecl->getType().getNonReferenceType();
4394 break;
4395 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00004396
Douglas Gregor882211c2010-04-28 22:16:22 +00004397 case OffsetOfExpr::OffsetOfNode::Identifier:
4398 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004399 return Error(OOE);
4400
Douglas Gregord1702062010-04-29 00:18:15 +00004401 case OffsetOfExpr::OffsetOfNode::Base: {
4402 CXXBaseSpecifier *BaseSpec = ON.getBase();
4403 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004404 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004405
4406 // Find the layout of the class whose base we are looking into.
4407 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00004408 if (!RT)
4409 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004410 RecordDecl *RD = RT->getDecl();
4411 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4412
4413 // Find the base class itself.
4414 CurrentType = BaseSpec->getType();
4415 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4416 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004417 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004418
4419 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00004420 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00004421 break;
4422 }
Douglas Gregor882211c2010-04-28 22:16:22 +00004423 }
4424 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004425 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004426}
4427
Chris Lattnere13042c2008-07-11 19:10:17 +00004428bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004429 switch (E->getOpcode()) {
4430 default:
4431 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4432 // See C99 6.6p3.
4433 return Error(E);
4434 case UO_Extension:
4435 // FIXME: Should extension allow i-c-e extension expressions in its scope?
4436 // If so, we could clear the diagnostic ID.
4437 return Visit(E->getSubExpr());
4438 case UO_Plus:
4439 // The result is just the value.
4440 return Visit(E->getSubExpr());
4441 case UO_Minus: {
4442 if (!Visit(E->getSubExpr()))
4443 return false;
4444 if (!Result.isInt()) return Error(E);
4445 return Success(-Result.getInt(), E);
4446 }
4447 case UO_Not: {
4448 if (!Visit(E->getSubExpr()))
4449 return false;
4450 if (!Result.isInt()) return Error(E);
4451 return Success(~Result.getInt(), E);
4452 }
4453 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00004454 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00004455 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00004456 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004457 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004458 }
Anders Carlsson9c181652008-07-08 14:35:21 +00004459 }
Anders Carlsson9c181652008-07-08 14:35:21 +00004460}
Mike Stump11289f42009-09-09 15:08:12 +00004461
Chris Lattner477c4be2008-07-12 01:15:53 +00004462/// HandleCast - This is used to evaluate implicit or explicit casts where the
4463/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00004464bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4465 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00004466 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00004467 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00004468
Eli Friedmanc757de22011-03-25 00:43:55 +00004469 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00004470 case CK_BaseToDerived:
4471 case CK_DerivedToBase:
4472 case CK_UncheckedDerivedToBase:
4473 case CK_Dynamic:
4474 case CK_ToUnion:
4475 case CK_ArrayToPointerDecay:
4476 case CK_FunctionToPointerDecay:
4477 case CK_NullToPointer:
4478 case CK_NullToMemberPointer:
4479 case CK_BaseToDerivedMemberPointer:
4480 case CK_DerivedToBaseMemberPointer:
4481 case CK_ConstructorConversion:
4482 case CK_IntegralToPointer:
4483 case CK_ToVoid:
4484 case CK_VectorSplat:
4485 case CK_IntegralToFloating:
4486 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00004487 case CK_CPointerToObjCPointerCast:
4488 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00004489 case CK_AnyPointerToBlockPointerCast:
4490 case CK_ObjCObjectLValueCast:
4491 case CK_FloatingRealToComplex:
4492 case CK_FloatingComplexToReal:
4493 case CK_FloatingComplexCast:
4494 case CK_FloatingComplexToIntegralComplex:
4495 case CK_IntegralRealToComplex:
4496 case CK_IntegralComplexCast:
4497 case CK_IntegralComplexToFloatingComplex:
4498 llvm_unreachable("invalid cast kind for integral value");
4499
Eli Friedman9faf2f92011-03-25 19:07:11 +00004500 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00004501 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004502 case CK_LValueBitCast:
4503 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00004504 case CK_ARCProduceObject:
4505 case CK_ARCConsumeObject:
4506 case CK_ARCReclaimReturnedObject:
4507 case CK_ARCExtendBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004508 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004509
4510 case CK_LValueToRValue:
4511 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004512 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004513
4514 case CK_MemberPointerToBoolean:
4515 case CK_PointerToBoolean:
4516 case CK_IntegralToBoolean:
4517 case CK_FloatingToBoolean:
4518 case CK_FloatingComplexToBoolean:
4519 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004520 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00004521 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00004522 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004523 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004524 }
4525
Eli Friedmanc757de22011-03-25 00:43:55 +00004526 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00004527 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00004528 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00004529
Eli Friedman742421e2009-02-20 01:15:07 +00004530 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004531 // Allow casts of address-of-label differences if they are no-ops
4532 // or narrowing. (The narrowing case isn't actually guaranteed to
4533 // be constant-evaluatable except in some narrow cases which are hard
4534 // to detect here. We let it through on the assumption the user knows
4535 // what they are doing.)
4536 if (Result.isAddrLabelDiff())
4537 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00004538 // Only allow casts of lvalues if they are lossless.
4539 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
4540 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004541
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004542 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004543 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00004544 }
Mike Stump11289f42009-09-09 15:08:12 +00004545
Eli Friedmanc757de22011-03-25 00:43:55 +00004546 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004547 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4548
John McCall45d55e42010-05-07 21:00:08 +00004549 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00004550 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00004551 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00004552
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004553 if (LV.getLValueBase()) {
4554 // Only allow based lvalue casts if they are lossless.
4555 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004556 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004557
Richard Smithcf74da72011-11-16 07:18:12 +00004558 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004559 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004560 return true;
4561 }
4562
Ken Dyck02990832010-01-15 12:37:54 +00004563 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
4564 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004565 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004566 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004567
Eli Friedmanc757de22011-03-25 00:43:55 +00004568 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00004569 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00004570 if (!EvaluateComplex(SubExpr, C, Info))
4571 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00004572 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00004573 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00004574
Eli Friedmanc757de22011-03-25 00:43:55 +00004575 case CK_FloatingToIntegral: {
4576 APFloat F(0.0);
4577 if (!EvaluateFloat(SubExpr, F, Info))
4578 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00004579
Richard Smith357362d2011-12-13 06:39:58 +00004580 APSInt Value;
4581 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
4582 return false;
4583 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004584 }
4585 }
Mike Stump11289f42009-09-09 15:08:12 +00004586
Eli Friedmanc757de22011-03-25 00:43:55 +00004587 llvm_unreachable("unknown cast resulting in integral value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004588 return Error(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00004589}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004590
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004591bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4592 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00004593 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004594 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4595 return false;
4596 if (!LV.isComplexInt())
4597 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004598 return Success(LV.getComplexIntReal(), E);
4599 }
4600
4601 return Visit(E->getSubExpr());
4602}
4603
Eli Friedman4e7a2412009-02-27 04:45:43 +00004604bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004605 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00004606 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004607 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4608 return false;
4609 if (!LV.isComplexInt())
4610 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004611 return Success(LV.getComplexIntImag(), E);
4612 }
4613
Richard Smith4a678122011-10-24 18:44:57 +00004614 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00004615 return Success(0, E);
4616}
4617
Douglas Gregor820ba7b2011-01-04 17:33:58 +00004618bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4619 return Success(E->getPackLength(), E);
4620}
4621
Sebastian Redl5f0180d2010-09-10 20:55:47 +00004622bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4623 return Success(E->getValue(), E);
4624}
4625
Chris Lattner05706e882008-07-11 18:11:29 +00004626//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00004627// Float Evaluation
4628//===----------------------------------------------------------------------===//
4629
4630namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004631class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004632 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00004633 APFloat &Result;
4634public:
4635 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004636 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00004637
Richard Smith0b0a0b62011-10-29 20:57:55 +00004638 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004639 Result = V.getFloat();
4640 return true;
4641 }
Eli Friedman24c01542008-08-22 00:06:13 +00004642
Richard Smithfddd3842011-12-30 21:15:51 +00004643 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00004644 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4645 return true;
4646 }
4647
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004648 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00004649
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004650 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00004651 bool VisitBinaryOperator(const BinaryOperator *E);
4652 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004653 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00004654
John McCallb1fb0d32010-05-07 22:08:54 +00004655 bool VisitUnaryReal(const UnaryOperator *E);
4656 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00004657
Richard Smithfddd3842011-12-30 21:15:51 +00004658 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00004659};
4660} // end anonymous namespace
4661
4662static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004663 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004664 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00004665}
4666
Jay Foad39c79802011-01-12 09:06:06 +00004667static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00004668 QualType ResultTy,
4669 const Expr *Arg,
4670 bool SNaN,
4671 llvm::APFloat &Result) {
4672 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4673 if (!S) return false;
4674
4675 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4676
4677 llvm::APInt fill;
4678
4679 // Treat empty strings as if they were zero.
4680 if (S->getString().empty())
4681 fill = llvm::APInt(32, 0);
4682 else if (S->getString().getAsInteger(0, fill))
4683 return false;
4684
4685 if (SNaN)
4686 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
4687 else
4688 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
4689 return true;
4690}
4691
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004692bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004693 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004694 default:
4695 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4696
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004697 case Builtin::BI__builtin_huge_val:
4698 case Builtin::BI__builtin_huge_valf:
4699 case Builtin::BI__builtin_huge_vall:
4700 case Builtin::BI__builtin_inf:
4701 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00004702 case Builtin::BI__builtin_infl: {
4703 const llvm::fltSemantics &Sem =
4704 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00004705 Result = llvm::APFloat::getInf(Sem);
4706 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00004707 }
Mike Stump11289f42009-09-09 15:08:12 +00004708
John McCall16291492010-02-28 13:00:19 +00004709 case Builtin::BI__builtin_nans:
4710 case Builtin::BI__builtin_nansf:
4711 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004712 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4713 true, Result))
4714 return Error(E);
4715 return true;
John McCall16291492010-02-28 13:00:19 +00004716
Chris Lattner0b7282e2008-10-06 06:31:58 +00004717 case Builtin::BI__builtin_nan:
4718 case Builtin::BI__builtin_nanf:
4719 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00004720 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00004721 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004722 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4723 false, Result))
4724 return Error(E);
4725 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004726
4727 case Builtin::BI__builtin_fabs:
4728 case Builtin::BI__builtin_fabsf:
4729 case Builtin::BI__builtin_fabsl:
4730 if (!EvaluateFloat(E->getArg(0), Result, Info))
4731 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004732
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004733 if (Result.isNegative())
4734 Result.changeSign();
4735 return true;
4736
Mike Stump11289f42009-09-09 15:08:12 +00004737 case Builtin::BI__builtin_copysign:
4738 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004739 case Builtin::BI__builtin_copysignl: {
4740 APFloat RHS(0.);
4741 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4742 !EvaluateFloat(E->getArg(1), RHS, Info))
4743 return false;
4744 Result.copySign(RHS);
4745 return true;
4746 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004747 }
4748}
4749
John McCallb1fb0d32010-05-07 22:08:54 +00004750bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004751 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4752 ComplexValue CV;
4753 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4754 return false;
4755 Result = CV.FloatReal;
4756 return true;
4757 }
4758
4759 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00004760}
4761
4762bool FloatExprEvaluator::VisitUnaryImag(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.FloatImag;
4768 return true;
4769 }
4770
Richard Smith4a678122011-10-24 18:44:57 +00004771 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00004772 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4773 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00004774 return true;
4775}
4776
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004777bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004778 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004779 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004780 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00004781 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00004782 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00004783 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
4784 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004785 Result.changeSign();
4786 return true;
4787 }
4788}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004789
Eli Friedman24c01542008-08-22 00:06:13 +00004790bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004791 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
4792 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00004793
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004794 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00004795 if (!EvaluateFloat(E->getLHS(), Result, Info))
4796 return false;
4797 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4798 return false;
4799
4800 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004801 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004802 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00004803 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
4804 return true;
John McCalle3027922010-08-25 11:45:40 +00004805 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00004806 Result.add(RHS, APFloat::rmNearestTiesToEven);
4807 return true;
John McCalle3027922010-08-25 11:45:40 +00004808 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00004809 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
4810 return true;
John McCalle3027922010-08-25 11:45:40 +00004811 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00004812 Result.divide(RHS, APFloat::rmNearestTiesToEven);
4813 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00004814 }
4815}
4816
4817bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
4818 Result = E->getValue();
4819 return true;
4820}
4821
Peter Collingbournee9200682011-05-13 03:29:01 +00004822bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4823 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00004824
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004825 switch (E->getCastKind()) {
4826 default:
Richard Smith11562c52011-10-28 17:51:58 +00004827 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004828
4829 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004830 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00004831 return EvaluateInteger(SubExpr, IntResult, Info) &&
4832 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
4833 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00004834 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004835
4836 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004837 if (!Visit(SubExpr))
4838 return false;
Richard Smith357362d2011-12-13 06:39:58 +00004839 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
4840 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00004841 }
John McCalld7646252010-11-14 08:17:51 +00004842
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004843 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00004844 ComplexValue V;
4845 if (!EvaluateComplex(SubExpr, V, Info))
4846 return false;
4847 Result = V.getComplexFloatReal();
4848 return true;
4849 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004850 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004851
Richard Smithf57d8cb2011-12-09 22:58:01 +00004852 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004853}
4854
Eli Friedman24c01542008-08-22 00:06:13 +00004855//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004856// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00004857//===----------------------------------------------------------------------===//
4858
4859namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004860class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004861 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00004862 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00004863
Anders Carlsson537969c2008-11-16 20:27:53 +00004864public:
John McCall93d91dc2010-05-07 17:22:02 +00004865 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004866 : ExprEvaluatorBaseTy(info), Result(Result) {}
4867
Richard Smith0b0a0b62011-10-29 20:57:55 +00004868 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004869 Result.setFrom(V);
4870 return true;
4871 }
Mike Stump11289f42009-09-09 15:08:12 +00004872
Anders Carlsson537969c2008-11-16 20:27:53 +00004873 //===--------------------------------------------------------------------===//
4874 // Visitor Methods
4875 //===--------------------------------------------------------------------===//
4876
Peter Collingbournee9200682011-05-13 03:29:01 +00004877 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00004878
Peter Collingbournee9200682011-05-13 03:29:01 +00004879 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00004880
John McCall93d91dc2010-05-07 17:22:02 +00004881 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004882 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00004883 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00004884};
4885} // end anonymous namespace
4886
John McCall93d91dc2010-05-07 17:22:02 +00004887static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
4888 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004889 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004890 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00004891}
4892
Peter Collingbournee9200682011-05-13 03:29:01 +00004893bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
4894 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004895
4896 if (SubExpr->getType()->isRealFloatingType()) {
4897 Result.makeComplexFloat();
4898 APFloat &Imag = Result.FloatImag;
4899 if (!EvaluateFloat(SubExpr, Imag, Info))
4900 return false;
4901
4902 Result.FloatReal = APFloat(Imag.getSemantics());
4903 return true;
4904 } else {
4905 assert(SubExpr->getType()->isIntegerType() &&
4906 "Unexpected imaginary literal.");
4907
4908 Result.makeComplexInt();
4909 APSInt &Imag = Result.IntImag;
4910 if (!EvaluateInteger(SubExpr, Imag, Info))
4911 return false;
4912
4913 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
4914 return true;
4915 }
4916}
4917
Peter Collingbournee9200682011-05-13 03:29:01 +00004918bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004919
John McCallfcef3cf2010-12-14 17:51:41 +00004920 switch (E->getCastKind()) {
4921 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004922 case CK_BaseToDerived:
4923 case CK_DerivedToBase:
4924 case CK_UncheckedDerivedToBase:
4925 case CK_Dynamic:
4926 case CK_ToUnion:
4927 case CK_ArrayToPointerDecay:
4928 case CK_FunctionToPointerDecay:
4929 case CK_NullToPointer:
4930 case CK_NullToMemberPointer:
4931 case CK_BaseToDerivedMemberPointer:
4932 case CK_DerivedToBaseMemberPointer:
4933 case CK_MemberPointerToBoolean:
4934 case CK_ConstructorConversion:
4935 case CK_IntegralToPointer:
4936 case CK_PointerToIntegral:
4937 case CK_PointerToBoolean:
4938 case CK_ToVoid:
4939 case CK_VectorSplat:
4940 case CK_IntegralCast:
4941 case CK_IntegralToBoolean:
4942 case CK_IntegralToFloating:
4943 case CK_FloatingToIntegral:
4944 case CK_FloatingToBoolean:
4945 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00004946 case CK_CPointerToObjCPointerCast:
4947 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004948 case CK_AnyPointerToBlockPointerCast:
4949 case CK_ObjCObjectLValueCast:
4950 case CK_FloatingComplexToReal:
4951 case CK_FloatingComplexToBoolean:
4952 case CK_IntegralComplexToReal:
4953 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00004954 case CK_ARCProduceObject:
4955 case CK_ARCConsumeObject:
4956 case CK_ARCReclaimReturnedObject:
4957 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00004958 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00004959
John McCallfcef3cf2010-12-14 17:51:41 +00004960 case CK_LValueToRValue:
4961 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004962 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004963
4964 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004965 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004966 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004967 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004968
4969 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004970 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00004971 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004972 return false;
4973
John McCallfcef3cf2010-12-14 17:51:41 +00004974 Result.makeComplexFloat();
4975 Result.FloatImag = APFloat(Real.getSemantics());
4976 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004977 }
4978
John McCallfcef3cf2010-12-14 17:51:41 +00004979 case CK_FloatingComplexCast: {
4980 if (!Visit(E->getSubExpr()))
4981 return false;
4982
4983 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4984 QualType From
4985 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4986
Richard Smith357362d2011-12-13 06:39:58 +00004987 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
4988 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00004989 }
4990
4991 case CK_FloatingComplexToIntegralComplex: {
4992 if (!Visit(E->getSubExpr()))
4993 return false;
4994
4995 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4996 QualType From
4997 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4998 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00004999 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5000 To, Result.IntReal) &&
5001 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5002 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00005003 }
5004
5005 case CK_IntegralRealToComplex: {
5006 APSInt &Real = Result.IntReal;
5007 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5008 return false;
5009
5010 Result.makeComplexInt();
5011 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5012 return true;
5013 }
5014
5015 case CK_IntegralComplexCast: {
5016 if (!Visit(E->getSubExpr()))
5017 return false;
5018
5019 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5020 QualType From
5021 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5022
5023 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
5024 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
5025 return true;
5026 }
5027
5028 case CK_IntegralComplexToFloatingComplex: {
5029 if (!Visit(E->getSubExpr()))
5030 return false;
5031
5032 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5033 QualType From
5034 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5035 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00005036 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5037 To, Result.FloatReal) &&
5038 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5039 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00005040 }
5041 }
5042
5043 llvm_unreachable("unknown cast resulting in complex value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00005044 return Error(E);
Eli Friedmanc3e9df32010-08-16 23:27:44 +00005045}
5046
John McCall93d91dc2010-05-07 17:22:02 +00005047bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005048 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00005049 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5050
John McCall93d91dc2010-05-07 17:22:02 +00005051 if (!Visit(E->getLHS()))
5052 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005053
John McCall93d91dc2010-05-07 17:22:02 +00005054 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00005055 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00005056 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00005057
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005058 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5059 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00005060 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005061 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00005062 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00005063 if (Result.isComplexFloat()) {
5064 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5065 APFloat::rmNearestTiesToEven);
5066 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5067 APFloat::rmNearestTiesToEven);
5068 } else {
5069 Result.getComplexIntReal() += RHS.getComplexIntReal();
5070 Result.getComplexIntImag() += RHS.getComplexIntImag();
5071 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005072 break;
John McCalle3027922010-08-25 11:45:40 +00005073 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00005074 if (Result.isComplexFloat()) {
5075 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5076 APFloat::rmNearestTiesToEven);
5077 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5078 APFloat::rmNearestTiesToEven);
5079 } else {
5080 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5081 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5082 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005083 break;
John McCalle3027922010-08-25 11:45:40 +00005084 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005085 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00005086 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005087 APFloat &LHS_r = LHS.getComplexFloatReal();
5088 APFloat &LHS_i = LHS.getComplexFloatImag();
5089 APFloat &RHS_r = RHS.getComplexFloatReal();
5090 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00005091
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005092 APFloat Tmp = LHS_r;
5093 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5094 Result.getComplexFloatReal() = Tmp;
5095 Tmp = LHS_i;
5096 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5097 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5098
5099 Tmp = LHS_r;
5100 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5101 Result.getComplexFloatImag() = Tmp;
5102 Tmp = LHS_i;
5103 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5104 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5105 } else {
John McCall93d91dc2010-05-07 17:22:02 +00005106 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00005107 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005108 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5109 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00005110 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005111 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5112 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5113 }
5114 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005115 case BO_Div:
5116 if (Result.isComplexFloat()) {
5117 ComplexValue LHS = Result;
5118 APFloat &LHS_r = LHS.getComplexFloatReal();
5119 APFloat &LHS_i = LHS.getComplexFloatImag();
5120 APFloat &RHS_r = RHS.getComplexFloatReal();
5121 APFloat &RHS_i = RHS.getComplexFloatImag();
5122 APFloat &Res_r = Result.getComplexFloatReal();
5123 APFloat &Res_i = Result.getComplexFloatImag();
5124
5125 APFloat Den = RHS_r;
5126 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5127 APFloat Tmp = RHS_i;
5128 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5129 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5130
5131 Res_r = LHS_r;
5132 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5133 Tmp = LHS_i;
5134 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5135 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5136 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5137
5138 Res_i = LHS_i;
5139 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5140 Tmp = LHS_r;
5141 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5142 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5143 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5144 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005145 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5146 return Error(E, diag::note_expr_divide_by_zero);
5147
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005148 ComplexValue LHS = Result;
5149 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5150 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5151 Result.getComplexIntReal() =
5152 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5153 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5154 Result.getComplexIntImag() =
5155 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5156 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5157 }
5158 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00005159 }
5160
John McCall93d91dc2010-05-07 17:22:02 +00005161 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00005162}
5163
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005164bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5165 // Get the operand value into 'Result'.
5166 if (!Visit(E->getSubExpr()))
5167 return false;
5168
5169 switch (E->getOpcode()) {
5170 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00005171 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005172 case UO_Extension:
5173 return true;
5174 case UO_Plus:
5175 // The result is always just the subexpr.
5176 return true;
5177 case UO_Minus:
5178 if (Result.isComplexFloat()) {
5179 Result.getComplexFloatReal().changeSign();
5180 Result.getComplexFloatImag().changeSign();
5181 }
5182 else {
5183 Result.getComplexIntReal() = -Result.getComplexIntReal();
5184 Result.getComplexIntImag() = -Result.getComplexIntImag();
5185 }
5186 return true;
5187 case UO_Not:
5188 if (Result.isComplexFloat())
5189 Result.getComplexFloatImag().changeSign();
5190 else
5191 Result.getComplexIntImag() = -Result.getComplexIntImag();
5192 return true;
5193 }
5194}
5195
Anders Carlsson537969c2008-11-16 20:27:53 +00005196//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00005197// Void expression evaluation, primarily for a cast to void on the LHS of a
5198// comma operator
5199//===----------------------------------------------------------------------===//
5200
5201namespace {
5202class VoidExprEvaluator
5203 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5204public:
5205 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5206
5207 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00005208
5209 bool VisitCastExpr(const CastExpr *E) {
5210 switch (E->getCastKind()) {
5211 default:
5212 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5213 case CK_ToVoid:
5214 VisitIgnoredValue(E->getSubExpr());
5215 return true;
5216 }
5217 }
5218};
5219} // end anonymous namespace
5220
5221static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5222 assert(E->isRValue() && E->getType()->isVoidType());
5223 return VoidExprEvaluator(Info).Visit(E);
5224}
5225
5226//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00005227// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00005228//===----------------------------------------------------------------------===//
5229
Richard Smith0b0a0b62011-10-29 20:57:55 +00005230static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005231 // In C, function designators are not lvalues, but we evaluate them as if they
5232 // are.
5233 if (E->isGLValue() || E->getType()->isFunctionType()) {
5234 LValue LV;
5235 if (!EvaluateLValue(E, LV, Info))
5236 return false;
5237 LV.moveInto(Result);
5238 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00005239 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005240 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005241 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00005242 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005243 return false;
John McCall45d55e42010-05-07 21:00:08 +00005244 } else if (E->getType()->hasPointerRepresentation()) {
5245 LValue LV;
5246 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005247 return false;
Richard Smith725810a2011-10-16 21:26:27 +00005248 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00005249 } else if (E->getType()->isRealFloatingType()) {
5250 llvm::APFloat F(0.0);
5251 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005252 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005253 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00005254 } else if (E->getType()->isAnyComplexType()) {
5255 ComplexValue C;
5256 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005257 return false;
Richard Smith725810a2011-10-16 21:26:27 +00005258 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00005259 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00005260 MemberPtr P;
5261 if (!EvaluateMemberPointer(E, P, Info))
5262 return false;
5263 P.moveInto(Result);
5264 return true;
Richard Smithfddd3842011-12-30 21:15:51 +00005265 } else if (E->getType()->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005266 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00005267 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00005268 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00005269 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005270 Result = Info.CurrentCall->Temporaries[E];
Richard Smithfddd3842011-12-30 21:15:51 +00005271 } else if (E->getType()->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005272 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00005273 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00005274 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5275 return false;
5276 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00005277 } else if (E->getType()->isVoidType()) {
Richard Smith357362d2011-12-13 06:39:58 +00005278 if (Info.getLangOpts().CPlusPlus0x)
5279 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5280 << E->getType();
5281 else
5282 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith42d3af92011-12-07 00:43:50 +00005283 if (!EvaluateVoid(E, Info))
5284 return false;
Richard Smith357362d2011-12-13 06:39:58 +00005285 } else if (Info.getLangOpts().CPlusPlus0x) {
5286 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5287 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005288 } else {
Richard Smith92b1ce02011-12-12 09:28:41 +00005289 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00005290 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005291 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005292
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00005293 return true;
5294}
5295
Richard Smithed5165f2011-11-04 05:33:44 +00005296/// EvaluateConstantExpression - Evaluate an expression as a constant expression
5297/// in-place in an APValue. In some cases, the in-place evaluation is essential,
5298/// since later initializers for an object can indirectly refer to subobjects
5299/// which were initialized earlier.
5300static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smith357362d2011-12-13 06:39:58 +00005301 const LValue &This, const Expr *E,
5302 CheckConstantExpressionKind CCEK) {
Richard Smithfddd3842011-12-30 21:15:51 +00005303 if (!CheckLiteralType(Info, E))
5304 return false;
5305
5306 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00005307 // Evaluate arrays and record types in-place, so that later initializers can
5308 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00005309 if (E->getType()->isArrayType())
5310 return EvaluateArray(E, This, Result, Info);
5311 else if (E->getType()->isRecordType())
5312 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00005313 }
5314
5315 // For any other type, in-place evaluation is unimportant.
5316 CCValue CoreConstResult;
5317 return Evaluate(CoreConstResult, Info, E) &&
Richard Smith357362d2011-12-13 06:39:58 +00005318 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smithed5165f2011-11-04 05:33:44 +00005319}
5320
Richard Smithf57d8cb2011-12-09 22:58:01 +00005321/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5322/// lvalue-to-rvalue cast if it is an lvalue.
5323static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00005324 if (!CheckLiteralType(Info, E))
5325 return false;
5326
Richard Smithf57d8cb2011-12-09 22:58:01 +00005327 CCValue Value;
5328 if (!::Evaluate(Value, Info, E))
5329 return false;
5330
5331 if (E->isGLValue()) {
5332 LValue LV;
5333 LV.setFrom(Value);
5334 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
5335 return false;
5336 }
5337
5338 // Check this core constant expression is a constant expression, and if so,
5339 // convert it to one.
5340 return CheckConstantExpression(Info, E, Value, Result);
5341}
Richard Smith11562c52011-10-28 17:51:58 +00005342
Richard Smith7b553f12011-10-29 00:50:52 +00005343/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00005344/// any crazy technique (that has nothing to do with language standards) that
5345/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00005346/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
5347/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00005348bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith036e2bd2011-12-10 01:10:13 +00005349 // Fast-path evaluations of integer literals, since we sometimes see files
5350 // containing vast quantities of these.
5351 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
5352 Result.Val = APValue(APSInt(L->getValue(),
5353 L->getType()->isUnsignedIntegerType()));
5354 return true;
5355 }
5356
Richard Smith5686e752011-11-10 03:30:42 +00005357 // FIXME: Evaluating initializers for large arrays can cause performance
5358 // problems, and we don't use such values yet. Once we have a more efficient
5359 // array representation, this should be reinstated, and used by CodeGen.
Richard Smith027bf112011-11-17 22:56:20 +00005360 // The same problem affects large records.
5361 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5362 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith5686e752011-11-10 03:30:42 +00005363 return false;
5364
Richard Smithd62306a2011-11-10 06:34:14 +00005365 // FIXME: If this is the initializer for an lvalue, pass that in.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005366 EvalInfo Info(Ctx, Result);
5367 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00005368}
5369
Jay Foad39c79802011-01-12 09:06:06 +00005370bool Expr::EvaluateAsBooleanCondition(bool &Result,
5371 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00005372 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00005373 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00005374 HandleConversionToBool(CCValue(const_cast<ASTContext&>(Ctx),
5375 Scratch.Val, CCValue::GlobalValue()),
Richard Smith0b0a0b62011-10-29 20:57:55 +00005376 Result);
John McCall1be1c632010-01-05 23:42:56 +00005377}
5378
Richard Smith5fab0c92011-12-28 19:48:30 +00005379bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
5380 SideEffectsKind AllowSideEffects) const {
5381 if (!getType()->isIntegralOrEnumerationType())
5382 return false;
5383
Richard Smith11562c52011-10-28 17:51:58 +00005384 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00005385 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
5386 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00005387 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005388
Richard Smith11562c52011-10-28 17:51:58 +00005389 Result = ExprResult.Val.getInt();
5390 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00005391}
5392
Jay Foad39c79802011-01-12 09:06:06 +00005393bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00005394 EvalInfo Info(Ctx, Result);
5395
John McCall45d55e42010-05-07 21:00:08 +00005396 LValue LV;
Richard Smith80815602011-11-07 05:07:52 +00005397 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smith357362d2011-12-13 06:39:58 +00005398 CheckLValueConstantExpression(Info, this, LV, Result.Val,
5399 CCEK_Constant);
Eli Friedman7d45c482009-09-13 10:17:44 +00005400}
5401
Richard Smithd0b4dd62011-12-19 06:19:21 +00005402bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
5403 const VarDecl *VD,
5404 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
5405 Expr::EvalStatus EStatus;
5406 EStatus.Diag = &Notes;
5407
5408 EvalInfo InitInfo(Ctx, EStatus);
5409 InitInfo.setEvaluatingDecl(VD, Value);
5410
Richard Smithfddd3842011-12-30 21:15:51 +00005411 if (!CheckLiteralType(InitInfo, this))
5412 return false;
5413
Richard Smithd0b4dd62011-12-19 06:19:21 +00005414 LValue LVal;
5415 LVal.set(VD);
5416
Richard Smithfddd3842011-12-30 21:15:51 +00005417 // C++11 [basic.start.init]p2:
5418 // Variables with static storage duration or thread storage duration shall be
5419 // zero-initialized before any other initialization takes place.
5420 // This behavior is not present in C.
5421 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
5422 !VD->getType()->isReferenceType()) {
5423 ImplicitValueInitExpr VIE(VD->getType());
5424 if (!EvaluateConstantExpression(Value, InitInfo, LVal, &VIE))
5425 return false;
5426 }
5427
Richard Smithd0b4dd62011-12-19 06:19:21 +00005428 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
5429 !EStatus.HasSideEffects;
5430}
5431
Richard Smith7b553f12011-10-29 00:50:52 +00005432/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
5433/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00005434bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00005435 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00005436 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00005437}
Anders Carlsson59689ed2008-11-22 21:04:56 +00005438
Jay Foad39c79802011-01-12 09:06:06 +00005439bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00005440 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005441}
5442
Richard Smithcaf33902011-10-10 18:28:20 +00005443APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005444 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005445 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00005446 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00005447 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005448 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00005449
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005450 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00005451}
John McCall864e3962010-05-07 05:32:02 +00005452
Abramo Bagnaraf8199452010-05-14 17:07:14 +00005453 bool Expr::EvalResult::isGlobalLValue() const {
5454 assert(Val.isLValue());
5455 return IsGlobalLValue(Val.getLValueBase());
5456 }
5457
5458
John McCall864e3962010-05-07 05:32:02 +00005459/// isIntegerConstantExpr - this recursive routine will test if an expression is
5460/// an integer constant expression.
5461
5462/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
5463/// comma, etc
5464///
5465/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
5466/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
5467/// cast+dereference.
5468
5469// CheckICE - This function does the fundamental ICE checking: the returned
5470// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
5471// Note that to reduce code duplication, this helper does no evaluation
5472// itself; the caller checks whether the expression is evaluatable, and
5473// in the rare cases where CheckICE actually cares about the evaluated
5474// value, it calls into Evalute.
5475//
5476// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00005477// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00005478// 1: This expression is not an ICE, but if it isn't evaluated, it's
5479// a legal subexpression for an ICE. This return value is used to handle
5480// the comma operator in C99 mode.
5481// 2: This expression is not an ICE, and is not a legal subexpression for one.
5482
Dan Gohman28ade552010-07-26 21:25:24 +00005483namespace {
5484
John McCall864e3962010-05-07 05:32:02 +00005485struct ICEDiag {
5486 unsigned Val;
5487 SourceLocation Loc;
5488
5489 public:
5490 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
5491 ICEDiag() : Val(0) {}
5492};
5493
Dan Gohman28ade552010-07-26 21:25:24 +00005494}
5495
5496static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00005497
5498static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
5499 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005500 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00005501 !EVResult.Val.isInt()) {
5502 return ICEDiag(2, E->getLocStart());
5503 }
5504 return NoDiag();
5505}
5506
5507static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
5508 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00005509 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00005510 return ICEDiag(2, E->getLocStart());
5511 }
5512
5513 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00005514#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00005515#define STMT(Node, Base) case Expr::Node##Class:
5516#define EXPR(Node, Base)
5517#include "clang/AST/StmtNodes.inc"
5518 case Expr::PredefinedExprClass:
5519 case Expr::FloatingLiteralClass:
5520 case Expr::ImaginaryLiteralClass:
5521 case Expr::StringLiteralClass:
5522 case Expr::ArraySubscriptExprClass:
5523 case Expr::MemberExprClass:
5524 case Expr::CompoundAssignOperatorClass:
5525 case Expr::CompoundLiteralExprClass:
5526 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00005527 case Expr::DesignatedInitExprClass:
5528 case Expr::ImplicitValueInitExprClass:
5529 case Expr::ParenListExprClass:
5530 case Expr::VAArgExprClass:
5531 case Expr::AddrLabelExprClass:
5532 case Expr::StmtExprClass:
5533 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00005534 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00005535 case Expr::CXXDynamicCastExprClass:
5536 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00005537 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00005538 case Expr::CXXNullPtrLiteralExprClass:
5539 case Expr::CXXThisExprClass:
5540 case Expr::CXXThrowExprClass:
5541 case Expr::CXXNewExprClass:
5542 case Expr::CXXDeleteExprClass:
5543 case Expr::CXXPseudoDestructorExprClass:
5544 case Expr::UnresolvedLookupExprClass:
5545 case Expr::DependentScopeDeclRefExprClass:
5546 case Expr::CXXConstructExprClass:
5547 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00005548 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00005549 case Expr::CXXTemporaryObjectExprClass:
5550 case Expr::CXXUnresolvedConstructExprClass:
5551 case Expr::CXXDependentScopeMemberExprClass:
5552 case Expr::UnresolvedMemberExprClass:
5553 case Expr::ObjCStringLiteralClass:
5554 case Expr::ObjCEncodeExprClass:
5555 case Expr::ObjCMessageExprClass:
5556 case Expr::ObjCSelectorExprClass:
5557 case Expr::ObjCProtocolExprClass:
5558 case Expr::ObjCIvarRefExprClass:
5559 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00005560 case Expr::ObjCIsaExprClass:
5561 case Expr::ShuffleVectorExprClass:
5562 case Expr::BlockExprClass:
5563 case Expr::BlockDeclRefExprClass:
5564 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00005565 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00005566 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00005567 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00005568 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00005569 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00005570 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00005571 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00005572 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00005573 case Expr::InitListExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00005574 return ICEDiag(2, E->getLocStart());
5575
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005576 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00005577 case Expr::GNUNullExprClass:
5578 // GCC considers the GNU __null value to be an integral constant expression.
5579 return NoDiag();
5580
John McCall7c454bb2011-07-15 05:09:51 +00005581 case Expr::SubstNonTypeTemplateParmExprClass:
5582 return
5583 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
5584
John McCall864e3962010-05-07 05:32:02 +00005585 case Expr::ParenExprClass:
5586 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00005587 case Expr::GenericSelectionExprClass:
5588 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005589 case Expr::IntegerLiteralClass:
5590 case Expr::CharacterLiteralClass:
5591 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00005592 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00005593 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005594 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00005595 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00005596 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00005597 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00005598 return NoDiag();
5599 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00005600 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00005601 // C99 6.6/3 allows function calls within unevaluated subexpressions of
5602 // constant expressions, but they can never be ICEs because an ICE cannot
5603 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00005604 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005605 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00005606 return CheckEvalInICE(E, Ctx);
5607 return ICEDiag(2, E->getLocStart());
5608 }
5609 case Expr::DeclRefExprClass:
5610 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
5611 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00005612 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00005613 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
5614
5615 // Parameter variables are never constants. Without this check,
5616 // getAnyInitializer() can find a default argument, which leads
5617 // to chaos.
5618 if (isa<ParmVarDecl>(D))
5619 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5620
5621 // C++ 7.1.5.1p2
5622 // A variable of non-volatile const-qualified integral or enumeration
5623 // type initialized by an ICE can be used in ICEs.
5624 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00005625 if (!Dcl->getType()->isIntegralOrEnumerationType())
5626 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5627
Richard Smithd0b4dd62011-12-19 06:19:21 +00005628 const VarDecl *VD;
5629 // Look for a declaration of this variable that has an initializer, and
5630 // check whether it is an ICE.
5631 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
5632 return NoDiag();
5633 else
5634 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00005635 }
5636 }
5637 return ICEDiag(2, E->getLocStart());
5638 case Expr::UnaryOperatorClass: {
5639 const UnaryOperator *Exp = cast<UnaryOperator>(E);
5640 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00005641 case UO_PostInc:
5642 case UO_PostDec:
5643 case UO_PreInc:
5644 case UO_PreDec:
5645 case UO_AddrOf:
5646 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00005647 // C99 6.6/3 allows increment and decrement within unevaluated
5648 // subexpressions of constant expressions, but they can never be ICEs
5649 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00005650 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00005651 case UO_Extension:
5652 case UO_LNot:
5653 case UO_Plus:
5654 case UO_Minus:
5655 case UO_Not:
5656 case UO_Real:
5657 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00005658 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005659 }
5660
5661 // OffsetOf falls through here.
5662 }
5663 case Expr::OffsetOfExprClass: {
5664 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00005665 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00005666 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00005667 // compliance: we should warn earlier for offsetof expressions with
5668 // array subscripts that aren't ICEs, and if the array subscripts
5669 // are ICEs, the value of the offsetof must be an integer constant.
5670 return CheckEvalInICE(E, Ctx);
5671 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00005672 case Expr::UnaryExprOrTypeTraitExprClass: {
5673 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
5674 if ((Exp->getKind() == UETT_SizeOf) &&
5675 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00005676 return ICEDiag(2, E->getLocStart());
5677 return NoDiag();
5678 }
5679 case Expr::BinaryOperatorClass: {
5680 const BinaryOperator *Exp = cast<BinaryOperator>(E);
5681 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00005682 case BO_PtrMemD:
5683 case BO_PtrMemI:
5684 case BO_Assign:
5685 case BO_MulAssign:
5686 case BO_DivAssign:
5687 case BO_RemAssign:
5688 case BO_AddAssign:
5689 case BO_SubAssign:
5690 case BO_ShlAssign:
5691 case BO_ShrAssign:
5692 case BO_AndAssign:
5693 case BO_XorAssign:
5694 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00005695 // C99 6.6/3 allows assignments within unevaluated subexpressions of
5696 // constant expressions, but they can never be ICEs because an ICE cannot
5697 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00005698 return ICEDiag(2, E->getLocStart());
5699
John McCalle3027922010-08-25 11:45:40 +00005700 case BO_Mul:
5701 case BO_Div:
5702 case BO_Rem:
5703 case BO_Add:
5704 case BO_Sub:
5705 case BO_Shl:
5706 case BO_Shr:
5707 case BO_LT:
5708 case BO_GT:
5709 case BO_LE:
5710 case BO_GE:
5711 case BO_EQ:
5712 case BO_NE:
5713 case BO_And:
5714 case BO_Xor:
5715 case BO_Or:
5716 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00005717 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5718 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00005719 if (Exp->getOpcode() == BO_Div ||
5720 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00005721 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00005722 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00005723 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00005724 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00005725 if (REval == 0)
5726 return ICEDiag(1, E->getLocStart());
5727 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00005728 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00005729 if (LEval.isMinSignedValue())
5730 return ICEDiag(1, E->getLocStart());
5731 }
5732 }
5733 }
John McCalle3027922010-08-25 11:45:40 +00005734 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00005735 if (Ctx.getLangOptions().C99) {
5736 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
5737 // if it isn't evaluated.
5738 if (LHSResult.Val == 0 && RHSResult.Val == 0)
5739 return ICEDiag(1, E->getLocStart());
5740 } else {
5741 // In both C89 and C++, commas in ICEs are illegal.
5742 return ICEDiag(2, E->getLocStart());
5743 }
5744 }
5745 if (LHSResult.Val >= RHSResult.Val)
5746 return LHSResult;
5747 return RHSResult;
5748 }
John McCalle3027922010-08-25 11:45:40 +00005749 case BO_LAnd:
5750 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00005751 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5752 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
5753 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
5754 // Rare case where the RHS has a comma "side-effect"; we need
5755 // to actually check the condition to see whether the side
5756 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00005757 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00005758 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00005759 return RHSResult;
5760 return NoDiag();
5761 }
5762
5763 if (LHSResult.Val >= RHSResult.Val)
5764 return LHSResult;
5765 return RHSResult;
5766 }
5767 }
5768 }
5769 case Expr::ImplicitCastExprClass:
5770 case Expr::CStyleCastExprClass:
5771 case Expr::CXXFunctionalCastExprClass:
5772 case Expr::CXXStaticCastExprClass:
5773 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00005774 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005775 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00005776 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00005777 if (isa<ExplicitCastExpr>(E)) {
5778 if (const FloatingLiteral *FL
5779 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
5780 unsigned DestWidth = Ctx.getIntWidth(E->getType());
5781 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
5782 APSInt IgnoredVal(DestWidth, !DestSigned);
5783 bool Ignored;
5784 // If the value does not fit in the destination type, the behavior is
5785 // undefined, so we are not required to treat it as a constant
5786 // expression.
5787 if (FL->getValue().convertToInteger(IgnoredVal,
5788 llvm::APFloat::rmTowardZero,
5789 &Ignored) & APFloat::opInvalidOp)
5790 return ICEDiag(2, E->getLocStart());
5791 return NoDiag();
5792 }
5793 }
Eli Friedman76d4e432011-09-29 21:49:34 +00005794 switch (cast<CastExpr>(E)->getCastKind()) {
5795 case CK_LValueToRValue:
5796 case CK_NoOp:
5797 case CK_IntegralToBoolean:
5798 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00005799 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00005800 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00005801 return ICEDiag(2, E->getLocStart());
5802 }
John McCall864e3962010-05-07 05:32:02 +00005803 }
John McCallc07a0c72011-02-17 10:25:35 +00005804 case Expr::BinaryConditionalOperatorClass: {
5805 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
5806 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
5807 if (CommonResult.Val == 2) return CommonResult;
5808 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
5809 if (FalseResult.Val == 2) return FalseResult;
5810 if (CommonResult.Val == 1) return CommonResult;
5811 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00005812 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00005813 return FalseResult;
5814 }
John McCall864e3962010-05-07 05:32:02 +00005815 case Expr::ConditionalOperatorClass: {
5816 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
5817 // If the condition (ignoring parens) is a __builtin_constant_p call,
5818 // then only the true side is actually considered in an integer constant
5819 // expression, and it is fully evaluated. This is an important GNU
5820 // extension. See GCC PR38377 for discussion.
5821 if (const CallExpr *CallCE
5822 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00005823 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
5824 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00005825 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005826 if (CondResult.Val == 2)
5827 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005828
Richard Smithf57d8cb2011-12-09 22:58:01 +00005829 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
5830 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005831
John McCall864e3962010-05-07 05:32:02 +00005832 if (TrueResult.Val == 2)
5833 return TrueResult;
5834 if (FalseResult.Val == 2)
5835 return FalseResult;
5836 if (CondResult.Val == 1)
5837 return CondResult;
5838 if (TrueResult.Val == 0 && FalseResult.Val == 0)
5839 return NoDiag();
5840 // Rare case where the diagnostics depend on which side is evaluated
5841 // Note that if we get here, CondResult is 0, and at least one of
5842 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00005843 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00005844 return FalseResult;
5845 }
5846 return TrueResult;
5847 }
5848 case Expr::CXXDefaultArgExprClass:
5849 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
5850 case Expr::ChooseExprClass: {
5851 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
5852 }
5853 }
5854
5855 // Silence a GCC warning
5856 return ICEDiag(2, E->getLocStart());
5857}
5858
Richard Smithf57d8cb2011-12-09 22:58:01 +00005859/// Evaluate an expression as a C++11 integral constant expression.
5860static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
5861 const Expr *E,
5862 llvm::APSInt *Value,
5863 SourceLocation *Loc) {
5864 if (!E->getType()->isIntegralOrEnumerationType()) {
5865 if (Loc) *Loc = E->getExprLoc();
5866 return false;
5867 }
5868
5869 Expr::EvalResult Result;
Richard Smith92b1ce02011-12-12 09:28:41 +00005870 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
5871 Result.Diag = &Diags;
5872 EvalInfo Info(Ctx, Result);
5873
5874 bool IsICE = EvaluateAsRValue(Info, E, Result.Val);
5875 if (!Diags.empty()) {
5876 IsICE = false;
5877 if (Loc) *Loc = Diags[0].first;
5878 } else if (!IsICE && Loc) {
5879 *Loc = E->getExprLoc();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005880 }
Richard Smith92b1ce02011-12-12 09:28:41 +00005881
5882 if (!IsICE)
5883 return false;
5884
5885 assert(Result.Val.isInt() && "pointer cast to int is not an ICE");
5886 if (Value) *Value = Result.Val.getInt();
5887 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005888}
5889
Richard Smith92b1ce02011-12-12 09:28:41 +00005890bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005891 if (Ctx.getLangOptions().CPlusPlus0x)
5892 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
5893
John McCall864e3962010-05-07 05:32:02 +00005894 ICEDiag d = CheckICE(this, Ctx);
5895 if (d.Val != 0) {
5896 if (Loc) *Loc = d.Loc;
5897 return false;
5898 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005899 return true;
5900}
5901
5902bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
5903 SourceLocation *Loc, bool isEvaluated) const {
5904 if (Ctx.getLangOptions().CPlusPlus0x)
5905 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
5906
5907 if (!isIntegerConstantExpr(Ctx, Loc))
5908 return false;
5909 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00005910 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00005911 return true;
5912}