blob: 1ad0bc5474b5d1e1105a6c406652d4c941cf1363 [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-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 Dyck199c3d62010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner500d3292009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump4572bab2009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlssonc44eec62008-07-03 04:20:39 +000027using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000030
Chris Lattner87eae5e2008-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 McCallf4cf1a12010-05-07 17:22:02 +000045namespace {
Richard Smith180f4792011-11-10 06:34:14 +000046 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000047 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000048 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000049
Richard Smith1bf9a9e2011-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 Smith180f4792011-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 Smithb4e85ed2012-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 Smith9a17a682011-11-07 05:07:52 +000087 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smithb4e85ed2012-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 Smith9a17a682011-11-07 05:07:52 +000099 // Path[I] describes a base class.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000100 ArraySize = 0;
101 }
Richard Smith9a17a682011-11-07 05:07:52 +0000102 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000103 return MostDerivedLength;
Richard Smith9a17a682011-11-07 05:07:52 +0000104 }
105
Richard Smithb4e85ed2012-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 Smith0a3bdb62011-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 Smithb4e85ed2012-01-06 16:39:00 +0000118 /// Is this a pointer one past the end of an object?
119 bool IsOnePastTheEnd : 1;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000120
Richard Smithb4e85ed2012-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 Smith0a3bdb62011-11-04 02:25:55 +0000131
Richard Smith9a17a682011-11-07 05:07:52 +0000132 typedef APValue::LValuePathEntry PathEntry;
133
Richard Smith0a3bdb62011-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 Smithb4e85ed2012-01-06 16:39:00 +0000137 SubobjectDesignator() : Invalid(true) {}
Richard Smith0a3bdb62011-11-04 02:25:55 +0000138
Richard Smithb4e85ed2012-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 Smith9a17a682011-11-07 05:07:52 +0000146 if (!Invalid) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000147 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-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 Smithb4e85ed2012-01-06 16:39:00 +0000151 MostDerivedPathLength =
152 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
153 V.getLValuePath(), MostDerivedArraySize,
154 MostDerivedType);
Richard Smith9a17a682011-11-07 05:07:52 +0000155 }
156 }
157
Richard Smith0a3bdb62011-11-04 02:25:55 +0000158 void setInvalid() {
159 Invalid = true;
160 Entries.clear();
161 }
Richard Smithb4e85ed2012-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 Smith0a3bdb62011-11-04 02:25:55 +0000185 PathEntry Entry;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000186 Entry.ArrayIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000187 Entries.push_back(Entry);
Richard Smithb4e85ed2012-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 Smith0a3bdb62011-11-04 02:25:55 +0000193 }
194 /// Update this designator to refer to the given base or member of this
195 /// object.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000196 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000197 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000198 APValue::BaseOrMemberType Value(D, Virtual);
199 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000200 Entries.push_back(Entry);
Richard Smithb4e85ed2012-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 Smith0a3bdb62011-11-04 02:25:55 +0000208 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000209 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000210 /// Add N to the address of this subobject.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000211 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000212 if (Invalid) return;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000213 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith9a17a682011-11-07 05:07:52 +0000214 Entries.back().ArrayIndex += N;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000215 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
216 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
217 setInvalid();
218 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000219 return;
220 }
Richard Smithb4e85ed2012-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 Smith0a3bdb62011-11-04 02:25:55 +0000230 setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000231 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000232 }
233 };
234
Richard Smith47a1eed2011-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 Smithe24f5fc2011-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 Smith47a1eed2011-10-29 20:57:55 +0000241 class CCValue : public APValue {
242 typedef llvm::APSInt APSInt;
243 typedef llvm::APFloat APFloat;
Richard Smith177dce72011-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 Smith0a3bdb62011-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 Smith47a1eed2011-10-29 20:57:55 +0000250 public:
Richard Smith177dce72011-11-01 16:57:24 +0000251 struct GlobalValue {};
252
Richard Smith47a1eed2011-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 Smith177dce72011-11-01 16:57:24 +0000259 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000260 CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F,
Richard Smith0a3bdb62011-11-04 02:25:55 +0000261 const SubobjectDesignator &D) :
Richard Smith9a17a682011-11-07 05:07:52 +0000262 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smithb4e85ed2012-01-06 16:39:00 +0000263 CCValue(ASTContext &Ctx, const APValue &V, GlobalValue) :
264 APValue(V), CallFrame(0), Designator(Ctx, V) {}
Richard Smithe24f5fc2011-11-17 22:56:20 +0000265 CCValue(const ValueDecl *D, bool IsDerivedMember,
266 ArrayRef<const CXXRecordDecl*> Path) :
267 APValue(D, IsDerivedMember, Path) {}
Eli Friedman65639282012-01-04 23:13:47 +0000268 CCValue(const AddrLabelExpr* LHSExpr, const AddrLabelExpr* RHSExpr) :
269 APValue(LHSExpr, RHSExpr) {}
Richard Smith47a1eed2011-10-29 20:57:55 +0000270
Richard Smith177dce72011-11-01 16:57:24 +0000271 CallStackFrame *getLValueFrame() const {
Richard Smith47a1eed2011-10-29 20:57:55 +0000272 assert(getKind() == LValue);
Richard Smith177dce72011-11-01 16:57:24 +0000273 return CallFrame;
Richard Smith47a1eed2011-10-29 20:57:55 +0000274 }
Richard Smith0a3bdb62011-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 Smith47a1eed2011-10-29 20:57:55 +0000282 };
283
Richard Smithd0dccea2011-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 Smithbd552ef2011-10-31 05:52:43 +0000289 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000290
Richard Smith08d6e032011-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 Smith180f4792011-11-10 06:34:14 +0000297 /// This - The binding for the this pointer in this call, if any.
298 const LValue *This;
299
Richard Smithd0dccea2011-10-28 22:34:42 +0000300 /// ParmBindings - Parameter bindings for this function call, indexed by
301 /// parameters' function scope indices.
Richard Smith47a1eed2011-10-29 20:57:55 +0000302 const CCValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000303
Richard Smithbd552ef2011-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 Smith08d6e032011-12-16 19:06:07 +0000309 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
310 const FunctionDecl *Callee, const LValue *This,
Richard Smith180f4792011-11-10 06:34:14 +0000311 const CCValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000312 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000313 };
314
Richard Smithdd1f29b2011-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 Smithbd552ef2011-10-31 05:52:43 +0000331 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000332 ASTContext &Ctx;
Richard Smithbd552ef2011-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 Smithbd552ef2011-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 Smith180f4792011-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 Smithc1c5f272011-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 Smithbd552ef2011-10-31 05:52:43 +0000364
365 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000366 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith08d6e032011-12-16 19:06:07 +0000367 CallStackDepth(0), BottomFrame(*this, SourceLocation(), 0, 0, 0),
368 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000369
Richard Smithbd552ef2011-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 Smith180f4792011-11-10 06:34:14 +0000376 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
377 EvaluatingDecl = VD;
378 EvaluatingDeclValue = &Value;
379 }
380
Richard Smithc18c4232011-11-21 19:36:32 +0000381 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
382
Richard Smithc1c5f272011-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 Smithc18c4232011-11-21 19:36:32 +0000389 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000390
Richard Smithc1c5f272011-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 Smith08d6e032011-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 Smithc1c5f272011-12-13 06:39:58 +0000402 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000403 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000404 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
405 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000406 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-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 Smithdd1f29b2011-12-12 09:28:41 +0000410 if (EvalStatus.Diag) {
Richard Smith08d6e032011-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 Smithc1c5f272011-12-13 06:39:58 +0000416 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000417 EvalStatus.Diag->clear();
Richard Smith08d6e032011-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 Smithdd1f29b2011-12-12 09:28:41 +0000422 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000423 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-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 Smith7098cbd2011-12-21 05:04:46 +0000429 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
430 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000431 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000432 // Don't override a previous diagnostic.
433 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
434 return OptionalDiagnostic();
Richard Smithc1c5f272011-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 Smithf48fdb02011-12-09 22:58:01 +0000443 }
Richard Smith099e7f62011-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 Smithbd552ef2011-10-31 05:52:43 +0000452 };
Richard Smith08d6e032011-12-16 19:06:07 +0000453}
Richard Smithbd552ef2011-10-31 05:52:43 +0000454
Richard Smithb4e85ed2012-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 Smith08d6e032011-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 Smithb4e85ed2012-01-06 16:39:00 +0000517 Arg.getLValueDesignator().IsOnePastTheEnd);
Richard Smith08d6e032011-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 Smithbd552ef2011-10-31 05:52:43 +0000523 }
524
Richard Smith08d6e032011-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 Smithbd552ef2011-10-31 05:52:43 +0000535 }
536
Richard Smith08d6e032011-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 McCallf4cf1a12010-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 Smith47a1eed2011-10-29 20:57:55 +0000579 void moveInto(CCValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000580 if (isComplexFloat())
Richard Smith47a1eed2011-10-29 20:57:55 +0000581 v = CCValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000582 else
Richard Smith47a1eed2011-10-29 20:57:55 +0000583 v = CCValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000584 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000585 void setFrom(const CCValue &v) {
John McCall56ca35d2011-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 McCallf4cf1a12010-05-07 17:22:02 +0000597 };
John McCallefdb83e2010-05-07 21:00:08 +0000598
599 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000600 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000601 CharUnits Offset;
Richard Smith177dce72011-11-01 16:57:24 +0000602 CallStackFrame *Frame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000603 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000604
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000605 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000606 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000607 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith177dce72011-11-01 16:57:24 +0000608 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000609 SubobjectDesignator &getLValueDesignator() { return Designator; }
610 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000611
Richard Smith47a1eed2011-10-29 20:57:55 +0000612 void moveInto(CCValue &V) const {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000613 V = CCValue(Base, Offset, Frame, Designator);
John McCallefdb83e2010-05-07 21:00:08 +0000614 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000615 void setFrom(const CCValue &V) {
616 assert(V.isLValue());
617 Base = V.getLValueBase();
618 Offset = V.getLValueOffset();
Richard Smith177dce72011-11-01 16:57:24 +0000619 Frame = V.getLValueFrame();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000620 Designator = V.getLValueDesignator();
621 }
622
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000623 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
624 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000625 Offset = CharUnits::Zero();
626 Frame = F;
Richard Smithb4e85ed2012-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 McCall56ca35d2011-02-17 10:25:35 +0000665 }
John McCallefdb83e2010-05-07 21:00:08 +0000666 };
Richard Smithe24f5fc2011-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 Smithc1c5f272011-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 McCallf4cf1a12010-05-07 17:22:02 +0000763}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000764
Richard Smith47a1eed2011-10-29 20:57:55 +0000765static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith69c2c502011-11-04 05:33:44 +0000766static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +0000767 const LValue &This, const Expr *E,
768 CheckConstantExpressionKind CCEK
769 = CCEK_Constant);
John McCallefdb83e2010-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 Smithe24f5fc2011-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 Lattner87eae5e2008-07-11 22:52:41 +0000775static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith47a1eed2011-10-29 20:57:55 +0000776static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000777 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000778static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000779static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000780
781//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000782// Misc utilities
783//===----------------------------------------------------------------------===//
784
Richard Smith180f4792011-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 Smith1bf9a9e2011-11-12 22:28:03 +0000792static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-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 Smith1bf9a9e2011-11-12 22:28:03 +0000798 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000799
Richard Smith1bf9a9e2011-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 Smith180f4792011-11-10 06:34:14 +0000809 switch (E->getStmtClass()) {
810 default:
811 return false;
Richard Smith180f4792011-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 Smith47d21452011-12-27 12:18:28 +0000819 case Expr::CXXTypeidExprClass:
Richard Smith180f4792011-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 McCall42c8f872010-05-10 23:27:23 +0000831}
832
Richard Smith9a17a682011-11-07 05:07:52 +0000833/// Check that this reference or pointer core constant expression is a valid
Richard Smithb4e85ed2012-01-06 16:39:00 +0000834/// value for an address or reference constant expression. Type T should be
Richard Smith61e61622012-01-12 06:08:57 +0000835/// either LValue or CCValue. Return true if we can fold this expression,
836/// whether or not it's a constant expression.
Richard Smith9a17a682011-11-07 05:07:52 +0000837template<typename T>
Richard Smithf48fdb02011-12-09 22:58:01 +0000838static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000839 const T &LVal, APValue &Value,
840 CheckConstantExpressionKind CCEK) {
841 APValue::LValueBase Base = LVal.getLValueBase();
842 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
843
844 if (!IsGlobalLValue(Base)) {
845 if (Info.getLangOpts().CPlusPlus0x) {
846 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
847 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
848 << E->isGLValue() << !Designator.Entries.empty()
849 << !!VD << CCEK << VD;
850 if (VD)
851 Info.Note(VD->getLocation(), diag::note_declared_at);
852 else
853 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
854 diag::note_constexpr_temporary_here);
855 } else {
Richard Smith7098cbd2011-12-21 05:04:46 +0000856 Info.Diag(E->getExprLoc());
Richard Smithc1c5f272011-12-13 06:39:58 +0000857 }
Richard Smith61e61622012-01-12 06:08:57 +0000858 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +0000859 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000860 }
Richard Smith9a17a682011-11-07 05:07:52 +0000861
Richard Smithb4e85ed2012-01-06 16:39:00 +0000862 bool IsReferenceType = E->isGLValue();
863
864 if (Designator.Invalid) {
Richard Smith61e61622012-01-12 06:08:57 +0000865 // This is not a core constant expression. An appropriate diagnostic will
866 // have already been produced.
Richard Smith9a17a682011-11-07 05:07:52 +0000867 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
868 APValue::NoLValuePath());
869 return true;
870 }
871
Richard Smithb4e85ed2012-01-06 16:39:00 +0000872 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
873 Designator.Entries, Designator.IsOnePastTheEnd);
874
875 // Allow address constant expressions to be past-the-end pointers. This is
876 // an extension: the standard requires them to point to an object.
877 if (!IsReferenceType)
878 return true;
879
880 // A reference constant expression must refer to an object.
881 if (!Base) {
882 // FIXME: diagnostic
883 Info.CCEDiag(E->getExprLoc());
Richard Smith61e61622012-01-12 06:08:57 +0000884 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000885 }
886
Richard Smithc1c5f272011-12-13 06:39:58 +0000887 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +0000888 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +0000889 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
890 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
891 << !Designator.Entries.empty() << !!VD << VD;
892 if (VD)
893 Info.Note(VD->getLocation(), diag::note_declared_at);
894 else
895 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
896 diag::note_constexpr_temporary_here);
Richard Smithc1c5f272011-12-13 06:39:58 +0000897 }
898
Richard Smith9a17a682011-11-07 05:07:52 +0000899 return true;
900}
901
Richard Smith51201882011-12-30 21:15:51 +0000902/// Check that this core constant expression is of literal type, and if not,
903/// produce an appropriate diagnostic.
904static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
905 if (!E->isRValue() || E->getType()->isLiteralType())
906 return true;
907
908 // Prvalue constant expressions must be of literal types.
909 if (Info.getLangOpts().CPlusPlus0x)
910 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
911 << E->getType();
912 else
913 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
914 return false;
915}
916
Richard Smith47a1eed2011-10-29 20:57:55 +0000917/// Check that this core constant expression value is a valid value for a
Richard Smith69c2c502011-11-04 05:33:44 +0000918/// constant expression, and if it is, produce the corresponding constant value.
Richard Smith51201882011-12-30 21:15:51 +0000919/// If not, report an appropriate diagnostic. Does not check that the expression
920/// is of literal type.
Richard Smithf48fdb02011-12-09 22:58:01 +0000921static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000922 const CCValue &CCValue, APValue &Value,
923 CheckConstantExpressionKind CCEK
924 = CCEK_Constant) {
Richard Smith9a17a682011-11-07 05:07:52 +0000925 if (!CCValue.isLValue()) {
926 Value = CCValue;
927 return true;
928 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000929 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith47a1eed2011-10-29 20:57:55 +0000930}
931
Richard Smith9e36b532011-10-31 05:11:32 +0000932const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000933 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +0000934}
935
936static bool IsLiteralLValue(const LValue &Value) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000937 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith9e36b532011-10-31 05:11:32 +0000938}
939
Richard Smith65ac5982011-11-01 21:06:14 +0000940static bool IsWeakLValue(const LValue &Value) {
941 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +0000942 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +0000943}
944
Richard Smithe24f5fc2011-11-17 22:56:20 +0000945static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +0000946 // A null base expression indicates a null pointer. These are always
947 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000948 if (!Value.getLValueBase()) {
949 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +0000950 return true;
951 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000952
John McCall42c8f872010-05-10 23:27:23 +0000953 // Require the base expression to be a global l-value.
Richard Smith47a1eed2011-10-29 20:57:55 +0000954 // FIXME: C++11 requires such conversions. Remove this check.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000955 if (!IsGlobalLValue(Value.getLValueBase())) return false;
John McCall42c8f872010-05-10 23:27:23 +0000956
Richard Smithe24f5fc2011-11-17 22:56:20 +0000957 // We have a non-null base. These are generally known to be true, but if it's
958 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +0000959 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +0000960 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +0000961 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +0000962}
963
Richard Smith47a1eed2011-10-29 20:57:55 +0000964static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +0000965 switch (Val.getKind()) {
966 case APValue::Uninitialized:
967 return false;
968 case APValue::Int:
969 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +0000970 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000971 case APValue::Float:
972 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +0000973 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000974 case APValue::ComplexInt:
975 Result = Val.getComplexIntReal().getBoolValue() ||
976 Val.getComplexIntImag().getBoolValue();
977 return true;
978 case APValue::ComplexFloat:
979 Result = !Val.getComplexFloatReal().isZero() ||
980 !Val.getComplexFloatImag().isZero();
981 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +0000982 case APValue::LValue:
983 return EvalPointerValueAsBool(Val, Result);
984 case APValue::MemberPointer:
985 Result = Val.getMemberPointerDecl();
986 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000987 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +0000988 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +0000989 case APValue::Struct:
990 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +0000991 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +0000992 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000993 }
994
Richard Smithc49bd112011-10-28 17:51:58 +0000995 llvm_unreachable("unknown APValue kind");
996}
997
998static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
999 EvalInfo &Info) {
1000 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith47a1eed2011-10-29 20:57:55 +00001001 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +00001002 if (!Evaluate(Val, Info, E))
1003 return false;
1004 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001005}
1006
Richard Smithc1c5f272011-12-13 06:39:58 +00001007template<typename T>
1008static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1009 const T &SrcValue, QualType DestType) {
1010 llvm::SmallVector<char, 32> Buffer;
1011 SrcValue.toString(Buffer);
1012 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
1013 << StringRef(Buffer.data(), Buffer.size()) << DestType;
1014 return false;
1015}
1016
1017static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1018 QualType SrcType, const APFloat &Value,
1019 QualType DestType, APSInt &Result) {
1020 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001021 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001022 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001023
Richard Smithc1c5f272011-12-13 06:39:58 +00001024 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001025 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001026 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1027 & APFloat::opInvalidOp)
1028 return HandleOverflow(Info, E, Value, DestType);
1029 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001030}
1031
Richard Smithc1c5f272011-12-13 06:39:58 +00001032static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1033 QualType SrcType, QualType DestType,
1034 APFloat &Result) {
1035 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001036 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001037 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1038 APFloat::rmNearestTiesToEven, &ignored)
1039 & APFloat::opOverflow)
1040 return HandleOverflow(Info, E, Value, DestType);
1041 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001042}
1043
Mike Stump1eb44332009-09-09 15:08:12 +00001044static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +00001045 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001046 unsigned DestWidth = Ctx.getIntWidth(DestType);
1047 APSInt Result = Value;
1048 // Figure out if this is a truncate, extend or noop cast.
1049 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001050 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001051 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001052 return Result;
1053}
1054
Richard Smithc1c5f272011-12-13 06:39:58 +00001055static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1056 QualType SrcType, const APSInt &Value,
1057 QualType DestType, APFloat &Result) {
1058 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1059 if (Result.convertFromAPInt(Value, Value.isSigned(),
1060 APFloat::rmNearestTiesToEven)
1061 & APFloat::opOverflow)
1062 return HandleOverflow(Info, E, Value, DestType);
1063 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001064}
1065
Eli Friedmane6a24e82011-12-22 03:51:45 +00001066static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1067 llvm::APInt &Res) {
1068 CCValue SVal;
1069 if (!Evaluate(SVal, Info, E))
1070 return false;
1071 if (SVal.isInt()) {
1072 Res = SVal.getInt();
1073 return true;
1074 }
1075 if (SVal.isFloat()) {
1076 Res = SVal.getFloat().bitcastToAPInt();
1077 return true;
1078 }
1079 if (SVal.isVector()) {
1080 QualType VecTy = E->getType();
1081 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1082 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1083 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1084 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1085 Res = llvm::APInt::getNullValue(VecSize);
1086 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1087 APValue &Elt = SVal.getVectorElt(i);
1088 llvm::APInt EltAsInt;
1089 if (Elt.isInt()) {
1090 EltAsInt = Elt.getInt();
1091 } else if (Elt.isFloat()) {
1092 EltAsInt = Elt.getFloat().bitcastToAPInt();
1093 } else {
1094 // Don't try to handle vectors of anything other than int or float
1095 // (not sure if it's possible to hit this case).
1096 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1097 return false;
1098 }
1099 unsigned BaseEltSize = EltAsInt.getBitWidth();
1100 if (BigEndian)
1101 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1102 else
1103 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1104 }
1105 return true;
1106 }
1107 // Give up if the input isn't an int, float, or vector. For example, we
1108 // reject "(v4i16)(intptr_t)&a".
1109 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1110 return false;
1111}
1112
Richard Smithb4e85ed2012-01-06 16:39:00 +00001113/// Cast an lvalue referring to a base subobject to a derived class, by
1114/// truncating the lvalue's path to the given length.
1115static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1116 const RecordDecl *TruncatedType,
1117 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001118 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001119
1120 // Check we actually point to a derived class object.
1121 if (TruncatedElements == D.Entries.size())
1122 return true;
1123 assert(TruncatedElements >= D.MostDerivedPathLength &&
1124 "not casting to a derived class");
1125 if (!Result.checkSubobject(Info, E, CSK_Derived))
1126 return false;
1127
1128 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001129 const RecordDecl *RD = TruncatedType;
1130 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +00001131 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1132 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001133 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001134 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001135 else
Richard Smith180f4792011-11-10 06:34:14 +00001136 Result.Offset -= Layout.getBaseClassOffset(Base);
1137 RD = Base;
1138 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001139 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001140 return true;
1141}
1142
Richard Smithb4e85ed2012-01-06 16:39:00 +00001143static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001144 const CXXRecordDecl *Derived,
1145 const CXXRecordDecl *Base,
1146 const ASTRecordLayout *RL = 0) {
1147 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1148 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001149 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
Richard Smith180f4792011-11-10 06:34:14 +00001150}
1151
Richard Smithb4e85ed2012-01-06 16:39:00 +00001152static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001153 const CXXRecordDecl *DerivedDecl,
1154 const CXXBaseSpecifier *Base) {
1155 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1156
1157 if (!Base->isVirtual()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001158 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001159 return true;
1160 }
1161
Richard Smithb4e85ed2012-01-06 16:39:00 +00001162 SubobjectDesignator &D = Obj.Designator;
1163 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001164 return false;
1165
Richard Smithb4e85ed2012-01-06 16:39:00 +00001166 // Extract most-derived object and corresponding type.
1167 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1168 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1169 return false;
1170
1171 // Find the virtual base class.
Richard Smith180f4792011-11-10 06:34:14 +00001172 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1173 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001174 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001175 return true;
1176}
1177
1178/// Update LVal to refer to the given field, which must be a member of the type
1179/// currently described by LVal.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001180static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001181 const FieldDecl *FD,
1182 const ASTRecordLayout *RL = 0) {
1183 if (!RL)
1184 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1185
1186 unsigned I = FD->getFieldIndex();
1187 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001188 LVal.addDecl(Info, E, FD);
Richard Smith180f4792011-11-10 06:34:14 +00001189}
1190
1191/// Get the size of the given type in char units.
1192static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1193 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1194 // extension.
1195 if (Type->isVoidType() || Type->isFunctionType()) {
1196 Size = CharUnits::One();
1197 return true;
1198 }
1199
1200 if (!Type->isConstantSizeType()) {
1201 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001202 // FIXME: Diagnostic.
Richard Smith180f4792011-11-10 06:34:14 +00001203 return false;
1204 }
1205
1206 Size = Info.Ctx.getTypeSizeInChars(Type);
1207 return true;
1208}
1209
1210/// Update a pointer value to model pointer arithmetic.
1211/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001212/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001213/// \param LVal - The pointer value to be updated.
1214/// \param EltTy - The pointee type represented by LVal.
1215/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001216static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1217 LValue &LVal, QualType EltTy,
1218 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001219 CharUnits SizeOfPointee;
1220 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1221 return false;
1222
1223 // Compute the new offset in the appropriate width.
1224 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001225 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001226 return true;
1227}
1228
Richard Smith03f96112011-10-24 17:54:18 +00001229/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001230static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1231 const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +00001232 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001233 // If this is a parameter to an active constexpr function call, perform
1234 // argument substitution.
1235 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00001236 if (!Frame || !Frame->Arguments) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001237 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001238 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001239 }
Richard Smith177dce72011-11-01 16:57:24 +00001240 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1241 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001242 }
Richard Smith03f96112011-10-24 17:54:18 +00001243
Richard Smith099e7f62011-12-19 06:19:21 +00001244 // Dig out the initializer, and use the declaration which it's attached to.
1245 const Expr *Init = VD->getAnyInitializer(VD);
1246 if (!Init || Init->isValueDependent()) {
1247 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1248 return false;
1249 }
1250
Richard Smith180f4792011-11-10 06:34:14 +00001251 // If we're currently evaluating the initializer of this declaration, use that
1252 // in-flight value.
1253 if (Info.EvaluatingDecl == VD) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001254 Result = CCValue(Info.Ctx, *Info.EvaluatingDeclValue,
1255 CCValue::GlobalValue());
Richard Smith180f4792011-11-10 06:34:14 +00001256 return !Result.isUninit();
1257 }
1258
Richard Smith65ac5982011-11-01 21:06:14 +00001259 // Never evaluate the initializer of a weak variable. We can't be sure that
1260 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001261 if (VD->isWeak()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001262 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001263 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001264 }
Richard Smith65ac5982011-11-01 21:06:14 +00001265
Richard Smith099e7f62011-12-19 06:19:21 +00001266 // Check that we can fold the initializer. In C++, we will have already done
1267 // this in the cases where it matters for conformance.
1268 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1269 if (!VD->evaluateValue(Notes)) {
1270 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1271 Notes.size() + 1) << VD;
1272 Info.Note(VD->getLocation(), diag::note_declared_at);
1273 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001274 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001275 } else if (!VD->checkInitIsICE()) {
1276 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1277 Notes.size() + 1) << VD;
1278 Info.Note(VD->getLocation(), diag::note_declared_at);
1279 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001280 }
Richard Smith03f96112011-10-24 17:54:18 +00001281
Richard Smithb4e85ed2012-01-06 16:39:00 +00001282 Result = CCValue(Info.Ctx, *VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +00001283 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001284}
1285
Richard Smithc49bd112011-10-28 17:51:58 +00001286static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001287 Qualifiers Quals = T.getQualifiers();
1288 return Quals.hasConst() && !Quals.hasVolatile();
1289}
1290
Richard Smith59efe262011-11-11 04:05:33 +00001291/// Get the base index of the given base class within an APValue representing
1292/// the given derived class.
1293static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1294 const CXXRecordDecl *Base) {
1295 Base = Base->getCanonicalDecl();
1296 unsigned Index = 0;
1297 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1298 E = Derived->bases_end(); I != E; ++I, ++Index) {
1299 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1300 return Index;
1301 }
1302
1303 llvm_unreachable("base class missing from derived class's bases list");
1304}
1305
Richard Smithcc5d4f62011-11-07 09:22:26 +00001306/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001307static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1308 CCValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001309 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001310 if (Sub.Invalid)
1311 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001312 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001313 if (Sub.isOnePastTheEnd()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001314 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001315 (unsigned)diag::note_constexpr_read_past_end :
1316 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001317 return false;
1318 }
Richard Smithf64699e2011-11-11 08:28:03 +00001319 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001320 return true;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001321
1322 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1323 const APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001324 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001325 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001326 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001327 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001328 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001329 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001330 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001331 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001332 // Note, it should not be possible to form a pointer with a valid
1333 // designator which points more than one past the end of the array.
1334 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001335 (unsigned)diag::note_constexpr_read_past_end :
1336 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001337 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001338 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001339 if (O->getArrayInitializedElts() > Index)
1340 O = &O->getArrayInitializedElt(Index);
1341 else
1342 O = &O->getArrayFiller();
1343 ObjType = CAT->getElementType();
Richard Smith180f4792011-11-10 06:34:14 +00001344 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1345 // Next subobject is a class, struct or union field.
1346 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1347 if (RD->isUnion()) {
1348 const FieldDecl *UnionField = O->getUnionField();
1349 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001350 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001351 Info.Diag(E->getExprLoc(),
1352 diag::note_constexpr_read_inactive_union_member)
1353 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001354 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001355 }
Richard Smith180f4792011-11-10 06:34:14 +00001356 O = &O->getUnionValue();
1357 } else
1358 O = &O->getStructField(Field->getFieldIndex());
1359 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001360
1361 if (ObjType.isVolatileQualified()) {
1362 if (Info.getLangOpts().CPlusPlus) {
1363 // FIXME: Include a description of the path to the volatile subobject.
1364 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1365 << 2 << Field;
1366 Info.Note(Field->getLocation(), diag::note_declared_at);
1367 } else {
1368 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1369 }
1370 return false;
1371 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001372 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001373 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001374 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1375 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1376 O = &O->getStructBase(getBaseIndex(Derived, Base));
1377 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001378 }
Richard Smith180f4792011-11-10 06:34:14 +00001379
Richard Smithf48fdb02011-12-09 22:58:01 +00001380 if (O->isUninit()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001381 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001382 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001383 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001384 }
1385
Richard Smithb4e85ed2012-01-06 16:39:00 +00001386 Obj = CCValue(Info.Ctx, *O, CCValue::GlobalValue());
Richard Smithcc5d4f62011-11-07 09:22:26 +00001387 return true;
1388}
1389
Richard Smith180f4792011-11-10 06:34:14 +00001390/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1391/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1392/// for looking up the glvalue referred to by an entity of reference type.
1393///
1394/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001395/// \param Conv - The expression for which we are performing the conversion.
1396/// Used for diagnostics.
Richard Smith180f4792011-11-10 06:34:14 +00001397/// \param Type - The type we expect this conversion to produce.
1398/// \param LVal - The glvalue on which we are attempting to perform this action.
1399/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001400static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1401 QualType Type,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001402 const LValue &LVal, CCValue &RVal) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001403 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1404 if (!Info.getLangOpts().CPlusPlus)
1405 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1406
Richard Smithb4e85ed2012-01-06 16:39:00 +00001407 if (LVal.Designator.Invalid)
1408 // A diagnostic will have already been produced.
1409 return false;
1410
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001411 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001412 CallStackFrame *Frame = LVal.Frame;
Richard Smith7098cbd2011-12-21 05:04:46 +00001413 SourceLocation Loc = Conv->getExprLoc();
Richard Smithc49bd112011-10-28 17:51:58 +00001414
Richard Smithf48fdb02011-12-09 22:58:01 +00001415 if (!LVal.Base) {
1416 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith7098cbd2011-12-21 05:04:46 +00001417 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1418 return false;
1419 }
1420
1421 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1422 // is not a constant expression (even if the object is non-volatile). We also
1423 // apply this rule to C++98, in order to conform to the expected 'volatile'
1424 // semantics.
1425 if (Type.isVolatileQualified()) {
1426 if (Info.getLangOpts().CPlusPlus)
1427 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1428 else
1429 Info.Diag(Loc);
Richard Smithc49bd112011-10-28 17:51:58 +00001430 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001431 }
Richard Smithc49bd112011-10-28 17:51:58 +00001432
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001433 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001434 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1435 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001436 // expressions are constant expressions too. Inside constexpr functions,
1437 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001438 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001439 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf48fdb02011-12-09 22:58:01 +00001440 if (!VD || VD->isInvalidDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001441 Info.Diag(Loc);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001442 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001443 }
1444
Richard Smith7098cbd2011-12-21 05:04:46 +00001445 // DR1313: If the object is volatile-qualified but the glvalue was not,
1446 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001447 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001448 if (VT.isVolatileQualified()) {
1449 if (Info.getLangOpts().CPlusPlus) {
1450 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1451 Info.Note(VD->getLocation(), diag::note_declared_at);
1452 } else {
1453 Info.Diag(Loc);
Richard Smithf48fdb02011-12-09 22:58:01 +00001454 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001455 return false;
1456 }
1457
1458 if (!isa<ParmVarDecl>(VD)) {
1459 if (VD->isConstexpr()) {
1460 // OK, we can read this variable.
1461 } else if (VT->isIntegralOrEnumerationType()) {
1462 if (!VT.isConstQualified()) {
1463 if (Info.getLangOpts().CPlusPlus) {
1464 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1465 Info.Note(VD->getLocation(), diag::note_declared_at);
1466 } else {
1467 Info.Diag(Loc);
1468 }
1469 return false;
1470 }
1471 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1472 // We support folding of const floating-point types, in order to make
1473 // static const data members of such types (supported as an extension)
1474 // more useful.
1475 if (Info.getLangOpts().CPlusPlus0x) {
1476 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1477 Info.Note(VD->getLocation(), diag::note_declared_at);
1478 } else {
1479 Info.CCEDiag(Loc);
1480 }
1481 } else {
1482 // FIXME: Allow folding of values of any literal type in all languages.
1483 if (Info.getLangOpts().CPlusPlus0x) {
1484 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1485 Info.Note(VD->getLocation(), diag::note_declared_at);
1486 } else {
1487 Info.Diag(Loc);
1488 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001489 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001490 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001491 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001492
Richard Smithf48fdb02011-12-09 22:58:01 +00001493 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001494 return false;
1495
Richard Smith47a1eed2011-10-29 20:57:55 +00001496 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001497 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001498
1499 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1500 // conversion. This happens when the declaration and the lvalue should be
1501 // considered synonymous, for instance when initializing an array of char
1502 // from a string literal. Continue as if the initializer lvalue was the
1503 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001504 assert(RVal.getLValueOffset().isZero() &&
1505 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001506 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001507 Frame = RVal.getLValueFrame();
Richard Smithc49bd112011-10-28 17:51:58 +00001508 }
1509
Richard Smith7098cbd2011-12-21 05:04:46 +00001510 // Volatile temporary objects cannot be read in constant expressions.
1511 if (Base->getType().isVolatileQualified()) {
1512 if (Info.getLangOpts().CPlusPlus) {
1513 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1514 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1515 } else {
1516 Info.Diag(Loc);
1517 }
1518 return false;
1519 }
1520
Richard Smith0a3bdb62011-11-04 02:25:55 +00001521 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1522 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1523 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf48fdb02011-12-09 22:58:01 +00001524 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001525 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001526 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001527 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001528
1529 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith9a17a682011-11-07 05:07:52 +00001530 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smith7098cbd2011-12-21 05:04:46 +00001531 const ConstantArrayType *CAT =
1532 Info.Ctx.getAsConstantArrayType(S->getType());
1533 if (Index >= CAT->getSize().getZExtValue()) {
1534 // Note, it should not be possible to form a pointer which points more
1535 // than one past the end of the array without producing a prior const expr
1536 // diagnostic.
1537 Info.Diag(Loc, diag::note_constexpr_read_past_end);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001538 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001539 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001540 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1541 Type->isUnsignedIntegerType());
1542 if (Index < S->getLength())
1543 Value = S->getCodeUnit(Index);
1544 RVal = CCValue(Value);
1545 return true;
1546 }
1547
Richard Smithcc5d4f62011-11-07 09:22:26 +00001548 if (Frame) {
1549 // If this is a temporary expression with a nontrivial initializer, grab the
1550 // value from the relevant stack frame.
1551 RVal = Frame->Temporaries[Base];
1552 } else if (const CompoundLiteralExpr *CLE
1553 = dyn_cast<CompoundLiteralExpr>(Base)) {
1554 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1555 // initializer until now for such expressions. Such an expression can't be
1556 // an ICE in C, so this only matters for fold.
1557 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1558 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1559 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001560 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001561 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001562 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001563 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001564
Richard Smithf48fdb02011-12-09 22:58:01 +00001565 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1566 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001567}
1568
Richard Smith59efe262011-11-11 04:05:33 +00001569/// Build an lvalue for the object argument of a member function call.
1570static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1571 LValue &This) {
1572 if (Object->getType()->isPointerType())
1573 return EvaluatePointer(Object, This, Info);
1574
1575 if (Object->isGLValue())
1576 return EvaluateLValue(Object, This, Info);
1577
Richard Smithe24f5fc2011-11-17 22:56:20 +00001578 if (Object->getType()->isLiteralType())
1579 return EvaluateTemporary(Object, This, Info);
1580
1581 return false;
1582}
1583
1584/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1585/// lvalue referring to the result.
1586///
1587/// \param Info - Information about the ongoing evaluation.
1588/// \param BO - The member pointer access operation.
1589/// \param LV - Filled in with a reference to the resulting object.
1590/// \param IncludeMember - Specifies whether the member itself is included in
1591/// the resulting LValue subobject designator. This is not possible when
1592/// creating a bound member function.
1593/// \return The field or method declaration to which the member pointer refers,
1594/// or 0 if evaluation fails.
1595static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1596 const BinaryOperator *BO,
1597 LValue &LV,
1598 bool IncludeMember = true) {
1599 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1600
1601 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV))
1602 return 0;
1603
1604 MemberPtr MemPtr;
1605 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1606 return 0;
1607
1608 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1609 // member value, the behavior is undefined.
1610 if (!MemPtr.getDecl())
1611 return 0;
1612
1613 if (MemPtr.isDerivedMember()) {
1614 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001615 // The end of the derived-to-base path for the base object must match the
1616 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001617 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001618 LV.Designator.Entries.size())
1619 return 0;
1620 unsigned PathLengthToMember =
1621 LV.Designator.Entries.size() - MemPtr.Path.size();
1622 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1623 const CXXRecordDecl *LVDecl = getAsBaseClass(
1624 LV.Designator.Entries[PathLengthToMember + I]);
1625 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1626 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1627 return 0;
1628 }
1629
1630 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001631 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1632 PathLengthToMember))
1633 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001634 } else if (!MemPtr.Path.empty()) {
1635 // Extend the LValue path with the member pointer's path.
1636 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1637 MemPtr.Path.size() + IncludeMember);
1638
1639 // Walk down to the appropriate base class.
1640 QualType LVType = BO->getLHS()->getType();
1641 if (const PointerType *PT = LVType->getAs<PointerType>())
1642 LVType = PT->getPointeeType();
1643 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1644 assert(RD && "member pointer access on non-class-type expression");
1645 // The first class in the path is that of the lvalue.
1646 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1647 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smithb4e85ed2012-01-06 16:39:00 +00001648 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001649 RD = Base;
1650 }
1651 // Finally cast to the class containing the member.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001652 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smithe24f5fc2011-11-17 22:56:20 +00001653 }
1654
1655 // Add the member. Note that we cannot build bound member functions here.
1656 if (IncludeMember) {
1657 // FIXME: Deal with IndirectFieldDecls.
1658 const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl());
1659 if (!FD) return 0;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001660 HandleLValueMember(Info, BO, LV, FD);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001661 }
1662
1663 return MemPtr.getDecl();
1664}
1665
1666/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1667/// the provided lvalue, which currently refers to the base object.
1668static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1669 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001670 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001671 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001672 return false;
1673
Richard Smithb4e85ed2012-01-06 16:39:00 +00001674 QualType TargetQT = E->getType();
1675 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1676 TargetQT = PT->getPointeeType();
1677
1678 // Check this cast lands within the final derived-to-base subobject path.
1679 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
1680 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1681 << D.MostDerivedType << TargetQT;
1682 return false;
1683 }
1684
Richard Smithe24f5fc2011-11-17 22:56:20 +00001685 // Check the type of the final cast. We don't need to check the path,
1686 // since a cast can only be formed if the path is unique.
1687 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001688 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1689 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001690 if (NewEntriesSize == D.MostDerivedPathLength)
1691 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
1692 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00001693 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001694 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
1695 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1696 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001697 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001698 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001699
1700 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001701 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00001702}
1703
Mike Stumpc4c90452009-10-27 22:09:17 +00001704namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00001705enum EvalStmtResult {
1706 /// Evaluation failed.
1707 ESR_Failed,
1708 /// Hit a 'return' statement.
1709 ESR_Returned,
1710 /// Evaluation succeeded.
1711 ESR_Succeeded
1712};
1713}
1714
1715// Evaluate a statement.
Richard Smithc1c5f272011-12-13 06:39:58 +00001716static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00001717 const Stmt *S) {
1718 switch (S->getStmtClass()) {
1719 default:
1720 return ESR_Failed;
1721
1722 case Stmt::NullStmtClass:
1723 case Stmt::DeclStmtClass:
1724 return ESR_Succeeded;
1725
Richard Smithc1c5f272011-12-13 06:39:58 +00001726 case Stmt::ReturnStmtClass: {
1727 CCValue CCResult;
1728 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1729 if (!Evaluate(CCResult, Info, RetExpr) ||
1730 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1731 CCEK_ReturnValue))
1732 return ESR_Failed;
1733 return ESR_Returned;
1734 }
Richard Smithd0dccea2011-10-28 22:34:42 +00001735
1736 case Stmt::CompoundStmtClass: {
1737 const CompoundStmt *CS = cast<CompoundStmt>(S);
1738 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1739 BE = CS->body_end(); BI != BE; ++BI) {
1740 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1741 if (ESR != ESR_Succeeded)
1742 return ESR;
1743 }
1744 return ESR_Succeeded;
1745 }
1746 }
1747}
1748
Richard Smith61802452011-12-22 02:22:31 +00001749/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
1750/// default constructor. If so, we'll fold it whether or not it's marked as
1751/// constexpr. If it is marked as constexpr, we will never implicitly define it,
1752/// so we need special handling.
1753static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00001754 const CXXConstructorDecl *CD,
1755 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00001756 if (!CD->isTrivial() || !CD->isDefaultConstructor())
1757 return false;
1758
1759 if (!CD->isConstexpr()) {
1760 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith51201882011-12-30 21:15:51 +00001761 // Value-initialization does not call a trivial default constructor, so
1762 // such a call is a core constant expression whether or not the
1763 // constructor is constexpr.
1764 if (!IsValueInitialization) {
1765 // FIXME: If DiagDecl is an implicitly-declared special member function,
1766 // we should be much more explicit about why it's not constexpr.
1767 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
1768 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
1769 Info.Note(CD->getLocation(), diag::note_declared_at);
1770 }
Richard Smith61802452011-12-22 02:22:31 +00001771 } else {
1772 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
1773 }
1774 }
1775 return true;
1776}
1777
Richard Smithc1c5f272011-12-13 06:39:58 +00001778/// CheckConstexprFunction - Check that a function can be called in a constant
1779/// expression.
1780static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1781 const FunctionDecl *Declaration,
1782 const FunctionDecl *Definition) {
1783 // Can we evaluate this function call?
1784 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1785 return true;
1786
1787 if (Info.getLangOpts().CPlusPlus0x) {
1788 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00001789 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1790 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00001791 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1792 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1793 << DiagDecl;
1794 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1795 } else {
1796 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1797 }
1798 return false;
1799}
1800
Richard Smith180f4792011-11-10 06:34:14 +00001801namespace {
Richard Smithcd99b072011-11-11 05:48:57 +00001802typedef SmallVector<CCValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00001803}
1804
1805/// EvaluateArgs - Evaluate the arguments to a function call.
1806static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1807 EvalInfo &Info) {
1808 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1809 I != E; ++I)
1810 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1811 return false;
1812 return true;
1813}
1814
Richard Smithd0dccea2011-10-28 22:34:42 +00001815/// Evaluate a function call.
Richard Smith08d6e032011-12-16 19:06:07 +00001816static bool HandleFunctionCall(const Expr *CallExpr, const FunctionDecl *Callee,
1817 const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00001818 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smithc1c5f272011-12-13 06:39:58 +00001819 EvalInfo &Info, APValue &Result) {
1820 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smithd0dccea2011-10-28 22:34:42 +00001821 return false;
1822
Richard Smith180f4792011-11-10 06:34:14 +00001823 ArgVector ArgValues(Args.size());
1824 if (!EvaluateArgs(Args, ArgValues, Info))
1825 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00001826
Richard Smith08d6e032011-12-16 19:06:07 +00001827 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Callee, This,
1828 ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00001829 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1830}
1831
Richard Smith180f4792011-11-10 06:34:14 +00001832/// Evaluate a constructor call.
Richard Smithf48fdb02011-12-09 22:58:01 +00001833static bool HandleConstructorCall(const Expr *CallExpr, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00001834 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00001835 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00001836 EvalInfo &Info, APValue &Result) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001837 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smith180f4792011-11-10 06:34:14 +00001838 return false;
1839
1840 ArgVector ArgValues(Args.size());
1841 if (!EvaluateArgs(Args, ArgValues, Info))
1842 return false;
1843
Richard Smith08d6e032011-12-16 19:06:07 +00001844 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Definition,
1845 &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00001846
1847 // If it's a delegating constructor, just delegate.
1848 if (Definition->isDelegatingConstructor()) {
1849 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1850 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1851 }
1852
Richard Smith610a60c2012-01-10 04:32:03 +00001853 // For a trivial copy or move constructor, perform an APValue copy. This is
1854 // essential for unions, where the operations performed by the constructor
1855 // cannot be represented by ctor-initializers.
Richard Smith180f4792011-11-10 06:34:14 +00001856 const CXXRecordDecl *RD = Definition->getParent();
Richard Smith610a60c2012-01-10 04:32:03 +00001857 if (Definition->isDefaulted() &&
1858 ((Definition->isCopyConstructor() && RD->hasTrivialCopyConstructor()) ||
1859 (Definition->isMoveConstructor() && RD->hasTrivialMoveConstructor()))) {
1860 LValue RHS;
1861 RHS.setFrom(ArgValues[0]);
1862 CCValue Value;
1863 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
1864 RHS, Value) &&
1865 CheckConstantExpression(Info, CallExpr, Value, Result);
1866 }
1867
1868 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00001869 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00001870 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1871 std::distance(RD->field_begin(), RD->field_end()));
1872
1873 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1874
1875 unsigned BasesSeen = 0;
1876#ifndef NDEBUG
1877 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1878#endif
1879 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1880 E = Definition->init_end(); I != E; ++I) {
1881 if ((*I)->isBaseInitializer()) {
1882 QualType BaseType((*I)->getBaseClass(), 0);
1883#ifndef NDEBUG
1884 // Non-virtual base classes are initialized in the order in the class
1885 // definition. We cannot have a virtual base class for a literal type.
1886 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1887 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1888 "base class initializers not in expected order");
1889 ++BaseIt;
1890#endif
1891 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001892 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smith180f4792011-11-10 06:34:14 +00001893 BaseType->getAsCXXRecordDecl(), &Layout);
1894 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1895 Subobject, (*I)->getInit()))
1896 return false;
1897 } else if (FieldDecl *FD = (*I)->getMember()) {
1898 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001899 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00001900 if (RD->isUnion()) {
1901 Result = APValue(FD);
Richard Smithc1c5f272011-12-13 06:39:58 +00001902 if (!EvaluateConstantExpression(Result.getUnionValue(), Info, Subobject,
1903 (*I)->getInit(), CCEK_MemberInit))
Richard Smith180f4792011-11-10 06:34:14 +00001904 return false;
1905 } else if (!EvaluateConstantExpression(
1906 Result.getStructField(FD->getFieldIndex()),
Richard Smithc1c5f272011-12-13 06:39:58 +00001907 Info, Subobject, (*I)->getInit(), CCEK_MemberInit))
Richard Smith180f4792011-11-10 06:34:14 +00001908 return false;
1909 } else {
1910 // FIXME: handle indirect field initializers
Richard Smithdd1f29b2011-12-12 09:28:41 +00001911 Info.Diag((*I)->getInit()->getExprLoc(),
Richard Smithf48fdb02011-12-09 22:58:01 +00001912 diag::note_invalid_subexpr_in_const_expr);
Richard Smith180f4792011-11-10 06:34:14 +00001913 return false;
1914 }
1915 }
1916
1917 return true;
1918}
1919
Richard Smithd0dccea2011-10-28 22:34:42 +00001920namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001921class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001922 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00001923 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00001924public:
1925
Richard Smith1e12c592011-10-16 21:26:27 +00001926 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00001927
1928 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001929 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00001930 return true;
1931 }
1932
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001933 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1934 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00001935 return Visit(E->getResultExpr());
1936 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001937 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001938 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00001939 return true;
1940 return false;
1941 }
John McCallf85e1932011-06-15 23:02:42 +00001942 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001943 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00001944 return true;
1945 return false;
1946 }
1947 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001948 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00001949 return true;
1950 return false;
1951 }
1952
Mike Stumpc4c90452009-10-27 22:09:17 +00001953 // We don't want to evaluate BlockExprs multiple times, as they generate
1954 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001955 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1956 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1957 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00001958 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001959 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1960 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1961 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1962 bool VisitStringLiteral(const StringLiteral *E) { return false; }
1963 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1964 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001965 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001966 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00001967 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001968 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00001969 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001970 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
1971 bool VisitBinAssign(const BinaryOperator *E) { return true; }
1972 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
1973 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00001974 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001975 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
1976 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
1977 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
1978 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
1979 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001980 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00001981 return true;
Mike Stump980ca222009-10-29 20:48:09 +00001982 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00001983 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001984 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00001985
1986 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001987 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00001988 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
1989 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001990 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00001991 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00001992 return false;
1993 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00001994
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001995 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00001996};
1997
John McCall56ca35d2011-02-17 10:25:35 +00001998class OpaqueValueEvaluation {
1999 EvalInfo &info;
2000 OpaqueValueExpr *opaqueValue;
2001
2002public:
2003 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2004 Expr *value)
2005 : info(info), opaqueValue(opaqueValue) {
2006
2007 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002008 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002009 this->opaqueValue = 0;
2010 return;
2011 }
John McCall56ca35d2011-02-17 10:25:35 +00002012 }
2013
2014 bool hasError() const { return opaqueValue == 0; }
2015
2016 ~OpaqueValueEvaluation() {
Richard Smith1e12c592011-10-16 21:26:27 +00002017 // FIXME: This will not work for recursive constexpr functions using opaque
2018 // values. Restore the former value.
John McCall56ca35d2011-02-17 10:25:35 +00002019 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2020 }
2021};
2022
Mike Stumpc4c90452009-10-27 22:09:17 +00002023} // end anonymous namespace
2024
Eli Friedman4efaa272008-11-12 09:44:48 +00002025//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002026// Generic Evaluation
2027//===----------------------------------------------------------------------===//
2028namespace {
2029
Richard Smithf48fdb02011-12-09 22:58:01 +00002030// FIXME: RetTy is always bool. Remove it.
2031template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002032class ExprEvaluatorBase
2033 : public ConstStmtVisitor<Derived, RetTy> {
2034private:
Richard Smith47a1eed2011-10-29 20:57:55 +00002035 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002036 return static_cast<Derived*>(this)->Success(V, E);
2037 }
Richard Smith51201882011-12-30 21:15:51 +00002038 RetTy DerivedZeroInitialization(const Expr *E) {
2039 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002040 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002041
2042protected:
2043 EvalInfo &Info;
2044 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2045 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2046
Richard Smithdd1f29b2011-12-12 09:28:41 +00002047 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd5093422011-12-12 09:41:58 +00002048 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002049 }
2050
2051 /// Report an evaluation error. This should only be called when an error is
2052 /// first discovered. When propagating an error, just return false.
2053 bool Error(const Expr *E, diag::kind D) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00002054 Info.Diag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002055 return false;
2056 }
2057 bool Error(const Expr *E) {
2058 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2059 }
2060
Richard Smith51201882011-12-30 21:15:51 +00002061 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00002062
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002063public:
2064 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2065
2066 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002067 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002068 }
2069 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002070 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002071 }
2072
2073 RetTy VisitParenExpr(const ParenExpr *E)
2074 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2075 RetTy VisitUnaryExtension(const UnaryOperator *E)
2076 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2077 RetTy VisitUnaryPlus(const UnaryOperator *E)
2078 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2079 RetTy VisitChooseExpr(const ChooseExpr *E)
2080 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2081 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2082 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002083 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2084 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002085 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2086 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002087 // We cannot create any objects for which cleanups are required, so there is
2088 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2089 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2090 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002091
Richard Smithc216a012011-12-12 12:46:16 +00002092 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2093 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2094 return static_cast<Derived*>(this)->VisitCastExpr(E);
2095 }
2096 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2097 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2098 return static_cast<Derived*>(this)->VisitCastExpr(E);
2099 }
2100
Richard Smithe24f5fc2011-11-17 22:56:20 +00002101 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2102 switch (E->getOpcode()) {
2103 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002104 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002105
2106 case BO_Comma:
2107 VisitIgnoredValue(E->getLHS());
2108 return StmtVisitorTy::Visit(E->getRHS());
2109
2110 case BO_PtrMemD:
2111 case BO_PtrMemI: {
2112 LValue Obj;
2113 if (!HandleMemberPointerAccess(Info, E, Obj))
2114 return false;
2115 CCValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002116 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002117 return false;
2118 return DerivedSuccess(Result, E);
2119 }
2120 }
2121 }
2122
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002123 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2124 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2125 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002126 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002127
2128 bool cond;
Richard Smithc49bd112011-10-28 17:51:58 +00002129 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002130 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002131
2132 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
2133 }
2134
2135 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
2136 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00002137 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002138 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002139
Richard Smithc49bd112011-10-28 17:51:58 +00002140 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002141 return StmtVisitorTy::Visit(EvalExpr);
2142 }
2143
2144 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002145 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002146 if (!Value) {
2147 const Expr *Source = E->getSourceExpr();
2148 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002149 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002150 if (Source == E) { // sanity checking.
2151 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002152 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002153 }
2154 return StmtVisitorTy::Visit(Source);
2155 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002156 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002157 }
Richard Smithf10d9172011-10-11 21:43:33 +00002158
Richard Smithd0dccea2011-10-28 22:34:42 +00002159 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002160 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002161 QualType CalleeType = Callee->getType();
2162
Richard Smithd0dccea2011-10-28 22:34:42 +00002163 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002164 LValue *This = 0, ThisVal;
2165 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith6c957872011-11-10 09:31:24 +00002166
Richard Smith59efe262011-11-11 04:05:33 +00002167 // Extract function decl and 'this' pointer from the callee.
2168 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002169 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002170 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2171 // Explicit bound member calls, such as x.f() or p->g();
2172 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002173 return false;
2174 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002175 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002176 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2177 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002178 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2179 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002180 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002181 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002182 return Error(Callee);
2183
2184 FD = dyn_cast<FunctionDecl>(Member);
2185 if (!FD)
2186 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002187 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002188 LValue Call;
2189 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002190 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002191
Richard Smithb4e85ed2012-01-06 16:39:00 +00002192 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002193 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002194 FD = dyn_cast_or_null<FunctionDecl>(
2195 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002196 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002197 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002198
2199 // Overloaded operator calls to member functions are represented as normal
2200 // calls with '*this' as the first argument.
2201 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2202 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002203 // FIXME: When selecting an implicit conversion for an overloaded
2204 // operator delete, we sometimes try to evaluate calls to conversion
2205 // operators without a 'this' parameter!
2206 if (Args.empty())
2207 return Error(E);
2208
Richard Smith59efe262011-11-11 04:05:33 +00002209 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2210 return false;
2211 This = &ThisVal;
2212 Args = Args.slice(1);
2213 }
2214
2215 // Don't call function pointers which have been cast to some other type.
2216 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002217 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002218 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002219 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002220
Richard Smithc1c5f272011-12-13 06:39:58 +00002221 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002222 Stmt *Body = FD->getBody(Definition);
Richard Smith69c2c502011-11-04 05:33:44 +00002223 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002224
Richard Smithc1c5f272011-12-13 06:39:58 +00002225 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith08d6e032011-12-16 19:06:07 +00002226 !HandleFunctionCall(E, Definition, This, Args, Body, Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002227 return false;
2228
Richard Smithb4e85ed2012-01-06 16:39:00 +00002229 return DerivedSuccess(CCValue(Info.Ctx, Result, CCValue::GlobalValue()), E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002230 }
2231
Richard Smithc49bd112011-10-28 17:51:58 +00002232 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2233 return StmtVisitorTy::Visit(E->getInitializer());
2234 }
Richard Smithf10d9172011-10-11 21:43:33 +00002235 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002236 if (E->getNumInits() == 0)
2237 return DerivedZeroInitialization(E);
2238 if (E->getNumInits() == 1)
2239 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002240 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002241 }
2242 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002243 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002244 }
2245 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002246 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002247 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002248 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002249 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002250 }
Richard Smithf10d9172011-10-11 21:43:33 +00002251
Richard Smith180f4792011-11-10 06:34:14 +00002252 /// A member expression where the object is a prvalue is itself a prvalue.
2253 RetTy VisitMemberExpr(const MemberExpr *E) {
2254 assert(!E->isArrow() && "missing call to bound member function?");
2255
2256 CCValue Val;
2257 if (!Evaluate(Val, Info, E->getBase()))
2258 return false;
2259
2260 QualType BaseTy = E->getBase()->getType();
2261
2262 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002263 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002264 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2265 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2266 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2267
Richard Smithb4e85ed2012-01-06 16:39:00 +00002268 SubobjectDesignator Designator(BaseTy);
2269 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002270
Richard Smithf48fdb02011-12-09 22:58:01 +00002271 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002272 DerivedSuccess(Val, E);
2273 }
2274
Richard Smithc49bd112011-10-28 17:51:58 +00002275 RetTy VisitCastExpr(const CastExpr *E) {
2276 switch (E->getCastKind()) {
2277 default:
2278 break;
2279
David Chisnall7a7ee302012-01-16 17:27:18 +00002280 case CK_AtomicToNonAtomic:
2281 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002282 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002283 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002284 return StmtVisitorTy::Visit(E->getSubExpr());
2285
2286 case CK_LValueToRValue: {
2287 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002288 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2289 return false;
2290 CCValue RVal;
2291 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2292 return false;
2293 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002294 }
2295 }
2296
Richard Smithf48fdb02011-12-09 22:58:01 +00002297 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002298 }
2299
Richard Smith8327fad2011-10-24 18:44:57 +00002300 /// Visit a value which is evaluated, but whose value is ignored.
2301 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002302 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002303 if (!Evaluate(Scratch, Info, E))
2304 Info.EvalStatus.HasSideEffects = true;
2305 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002306};
2307
2308}
2309
2310//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002311// Common base class for lvalue and temporary evaluation.
2312//===----------------------------------------------------------------------===//
2313namespace {
2314template<class Derived>
2315class LValueExprEvaluatorBase
2316 : public ExprEvaluatorBase<Derived, bool> {
2317protected:
2318 LValue &Result;
2319 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2320 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2321
2322 bool Success(APValue::LValueBase B) {
2323 Result.set(B);
2324 return true;
2325 }
2326
2327public:
2328 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2329 ExprEvaluatorBaseTy(Info), Result(Result) {}
2330
2331 bool Success(const CCValue &V, const Expr *E) {
2332 Result.setFrom(V);
2333 return true;
2334 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002335
Richard Smithe24f5fc2011-11-17 22:56:20 +00002336 bool VisitMemberExpr(const MemberExpr *E) {
2337 // Handle non-static data members.
2338 QualType BaseTy;
2339 if (E->isArrow()) {
2340 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2341 return false;
2342 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002343 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002344 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002345 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2346 return false;
2347 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002348 } else {
2349 if (!this->Visit(E->getBase()))
2350 return false;
2351 BaseTy = E->getBase()->getType();
2352 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002353
2354 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2355 // FIXME: Handle IndirectFieldDecls
Richard Smithf48fdb02011-12-09 22:58:01 +00002356 if (!FD) return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002357 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2358 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2359 (void)BaseTy;
2360
Richard Smithb4e85ed2012-01-06 16:39:00 +00002361 HandleLValueMember(this->Info, E, Result, FD);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002362
2363 if (FD->getType()->isReferenceType()) {
2364 CCValue RefValue;
Richard Smithf48fdb02011-12-09 22:58:01 +00002365 if (!HandleLValueToRValueConversion(this->Info, E, FD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002366 RefValue))
2367 return false;
2368 return Success(RefValue, E);
2369 }
2370 return true;
2371 }
2372
2373 bool VisitBinaryOperator(const BinaryOperator *E) {
2374 switch (E->getOpcode()) {
2375 default:
2376 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2377
2378 case BO_PtrMemD:
2379 case BO_PtrMemI:
2380 return HandleMemberPointerAccess(this->Info, E, Result);
2381 }
2382 }
2383
2384 bool VisitCastExpr(const CastExpr *E) {
2385 switch (E->getCastKind()) {
2386 default:
2387 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2388
2389 case CK_DerivedToBase:
2390 case CK_UncheckedDerivedToBase: {
2391 if (!this->Visit(E->getSubExpr()))
2392 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002393
2394 // Now figure out the necessary offset to add to the base LV to get from
2395 // the derived class to the base class.
2396 QualType Type = E->getSubExpr()->getType();
2397
2398 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2399 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002400 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002401 *PathI))
2402 return false;
2403 Type = (*PathI)->getType();
2404 }
2405
2406 return true;
2407 }
2408 }
2409 }
2410};
2411}
2412
2413//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002414// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002415//
2416// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2417// function designators (in C), decl references to void objects (in C), and
2418// temporaries (if building with -Wno-address-of-temporary).
2419//
2420// LValue evaluation produces values comprising a base expression of one of the
2421// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002422// - Declarations
2423// * VarDecl
2424// * FunctionDecl
2425// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002426// * CompoundLiteralExpr in C
2427// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002428// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002429// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002430// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002431// * ObjCEncodeExpr
2432// * AddrLabelExpr
2433// * BlockExpr
2434// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002435// - Locals and temporaries
2436// * Any Expr, with a Frame indicating the function in which the temporary was
2437// evaluated.
2438// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002439//===----------------------------------------------------------------------===//
2440namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002441class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002442 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002443public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002444 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2445 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002446
Richard Smithc49bd112011-10-28 17:51:58 +00002447 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2448
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002449 bool VisitDeclRefExpr(const DeclRefExpr *E);
2450 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002451 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002452 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2453 bool VisitMemberExpr(const MemberExpr *E);
2454 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2455 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002456 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002457 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2458 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002459
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002460 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002461 switch (E->getCastKind()) {
2462 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002463 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002464
Eli Friedmandb924222011-10-11 00:13:24 +00002465 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002466 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002467 if (!Visit(E->getSubExpr()))
2468 return false;
2469 Result.Designator.setInvalid();
2470 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002471
Richard Smithe24f5fc2011-11-17 22:56:20 +00002472 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002473 if (!Visit(E->getSubExpr()))
2474 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002475 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002476 }
2477 }
Sebastian Redlcea8d962011-09-24 17:48:14 +00002478
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002479 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002480
Eli Friedman4efaa272008-11-12 09:44:48 +00002481};
2482} // end anonymous namespace
2483
Richard Smithc49bd112011-10-28 17:51:58 +00002484/// Evaluate an expression as an lvalue. This can be legitimately called on
2485/// expressions which are not glvalues, in a few cases:
2486/// * function designators in C,
2487/// * "extern void" objects,
2488/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002489static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002490 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2491 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2492 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002493 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002494}
2495
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002496bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002497 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2498 return Success(FD);
2499 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002500 return VisitVarDecl(E, VD);
2501 return Error(E);
2502}
Richard Smith436c8892011-10-24 23:14:33 +00002503
Richard Smithc49bd112011-10-28 17:51:58 +00002504bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002505 if (!VD->getType()->isReferenceType()) {
2506 if (isa<ParmVarDecl>(VD)) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002507 Result.set(VD, Info.CurrentCall);
Richard Smith177dce72011-11-01 16:57:24 +00002508 return true;
2509 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002510 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002511 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002512
Richard Smith47a1eed2011-10-29 20:57:55 +00002513 CCValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002514 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2515 return false;
2516 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002517}
2518
Richard Smithbd552ef2011-10-31 05:52:43 +00002519bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2520 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002521 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002522 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002523 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2524
2525 Result.set(E, Info.CurrentCall);
2526 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2527 Result, E->GetTemporaryExpr());
2528 }
2529
2530 // Materialization of an lvalue temporary occurs when we need to force a copy
2531 // (for instance, if it's a bitfield).
2532 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2533 if (!Visit(E->GetTemporaryExpr()))
2534 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002535 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002536 Info.CurrentCall->Temporaries[E]))
2537 return false;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002538 Result.set(E, Info.CurrentCall);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002539 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002540}
2541
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002542bool
2543LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002544 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2545 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2546 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002547 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002548}
2549
Richard Smith47d21452011-12-27 12:18:28 +00002550bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2551 if (E->isTypeOperand())
2552 return Success(E);
2553 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2554 if (RD && RD->isPolymorphic()) {
2555 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2556 << E->getExprOperand()->getType()
2557 << E->getExprOperand()->getSourceRange();
2558 return false;
2559 }
2560 return Success(E);
2561}
2562
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002563bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002564 // Handle static data members.
2565 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2566 VisitIgnoredValue(E->getBase());
2567 return VisitVarDecl(E, VD);
2568 }
2569
Richard Smithd0dccea2011-10-28 22:34:42 +00002570 // Handle static member functions.
2571 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2572 if (MD->isStatic()) {
2573 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002574 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002575 }
2576 }
2577
Richard Smith180f4792011-11-10 06:34:14 +00002578 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002579 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002580}
2581
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002582bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002583 // FIXME: Deal with vectors as array subscript bases.
2584 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002585 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002586
Anders Carlsson3068d112008-11-16 19:01:22 +00002587 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002588 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002589
Anders Carlsson3068d112008-11-16 19:01:22 +00002590 APSInt Index;
2591 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002592 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002593 int64_t IndexValue
2594 = Index.isSigned() ? Index.getSExtValue()
2595 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00002596
Richard Smithb4e85ed2012-01-06 16:39:00 +00002597 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00002598}
Eli Friedman4efaa272008-11-12 09:44:48 +00002599
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002600bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002601 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00002602}
2603
Eli Friedman4efaa272008-11-12 09:44:48 +00002604//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002605// Pointer Evaluation
2606//===----------------------------------------------------------------------===//
2607
Anders Carlssonc754aa62008-07-08 05:13:58 +00002608namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002609class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002610 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00002611 LValue &Result;
2612
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002613 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002614 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00002615 return true;
2616 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002617public:
Mike Stump1eb44332009-09-09 15:08:12 +00002618
John McCallefdb83e2010-05-07 21:00:08 +00002619 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002620 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002621
Richard Smith47a1eed2011-10-29 20:57:55 +00002622 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002623 Result.setFrom(V);
2624 return true;
2625 }
Richard Smith51201882011-12-30 21:15:51 +00002626 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00002627 return Success((Expr*)0);
2628 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002629
John McCallefdb83e2010-05-07 21:00:08 +00002630 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002631 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00002632 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002633 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00002634 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002635 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00002636 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002637 bool VisitCallExpr(const CallExpr *E);
2638 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00002639 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00002640 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00002641 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00002642 }
Richard Smith180f4792011-11-10 06:34:14 +00002643 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2644 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00002645 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002646 Result = *Info.CurrentCall->This;
2647 return true;
2648 }
John McCall56ca35d2011-02-17 10:25:35 +00002649
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002650 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00002651};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002652} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00002653
John McCallefdb83e2010-05-07 21:00:08 +00002654static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002655 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002656 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002657}
2658
John McCallefdb83e2010-05-07 21:00:08 +00002659bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002660 if (E->getOpcode() != BO_Add &&
2661 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00002662 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002663
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002664 const Expr *PExp = E->getLHS();
2665 const Expr *IExp = E->getRHS();
2666 if (IExp->getType()->isPointerType())
2667 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002668
John McCallefdb83e2010-05-07 21:00:08 +00002669 if (!EvaluatePointer(PExp, Result, Info))
2670 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002671
John McCallefdb83e2010-05-07 21:00:08 +00002672 llvm::APSInt Offset;
2673 if (!EvaluateInteger(IExp, Offset, Info))
2674 return false;
2675 int64_t AdditionalOffset
2676 = Offset.isSigned() ? Offset.getSExtValue()
2677 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00002678 if (E->getOpcode() == BO_Sub)
2679 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002680
Richard Smith180f4792011-11-10 06:34:14 +00002681 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00002682 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
2683 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002684}
Eli Friedman4efaa272008-11-12 09:44:48 +00002685
John McCallefdb83e2010-05-07 21:00:08 +00002686bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2687 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002688}
Mike Stump1eb44332009-09-09 15:08:12 +00002689
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002690bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2691 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002692
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002693 switch (E->getCastKind()) {
2694 default:
2695 break;
2696
John McCall2de56d12010-08-25 11:45:40 +00002697 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002698 case CK_CPointerToObjCPointerCast:
2699 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00002700 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00002701 if (!Visit(SubExpr))
2702 return false;
Richard Smithc216a012011-12-12 12:46:16 +00002703 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2704 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2705 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002706 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00002707 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002708 if (SubExpr->getType()->isVoidPointerType())
2709 CCEDiag(E, diag::note_constexpr_invalid_cast)
2710 << 3 << SubExpr->getType();
2711 else
2712 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2713 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002714 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002715
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002716 case CK_DerivedToBase:
2717 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00002718 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002719 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002720 if (!Result.Base && Result.Offset.isZero())
2721 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002722
Richard Smith180f4792011-11-10 06:34:14 +00002723 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002724 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00002725 QualType Type =
2726 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002727
Richard Smith180f4792011-11-10 06:34:14 +00002728 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002729 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002730 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2731 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002732 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002733 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002734 }
2735
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002736 return true;
2737 }
2738
Richard Smithe24f5fc2011-11-17 22:56:20 +00002739 case CK_BaseToDerived:
2740 if (!Visit(E->getSubExpr()))
2741 return false;
2742 if (!Result.Base && Result.Offset.isZero())
2743 return true;
2744 return HandleBaseToDerivedCast(Info, E, Result);
2745
Richard Smith47a1eed2011-10-29 20:57:55 +00002746 case CK_NullToPointer:
Richard Smith51201882011-12-30 21:15:51 +00002747 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00002748
John McCall2de56d12010-08-25 11:45:40 +00002749 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00002750 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2751
Richard Smith47a1eed2011-10-29 20:57:55 +00002752 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00002753 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002754 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00002755
John McCallefdb83e2010-05-07 21:00:08 +00002756 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002757 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2758 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002759 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00002760 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith177dce72011-11-01 16:57:24 +00002761 Result.Frame = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002762 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00002763 return true;
2764 } else {
2765 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00002766 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00002767 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002768 }
2769 }
John McCall2de56d12010-08-25 11:45:40 +00002770 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002771 if (SubExpr->isGLValue()) {
2772 if (!EvaluateLValue(SubExpr, Result, Info))
2773 return false;
2774 } else {
2775 Result.set(SubExpr, Info.CurrentCall);
2776 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2777 Info, Result, SubExpr))
2778 return false;
2779 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002780 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002781 if (const ConstantArrayType *CAT
2782 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
2783 Result.addArray(Info, E, CAT);
2784 else
2785 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00002786 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00002787
John McCall2de56d12010-08-25 11:45:40 +00002788 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00002789 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002790 }
2791
Richard Smithc49bd112011-10-28 17:51:58 +00002792 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002793}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002794
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002795bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00002796 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00002797 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00002798
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002799 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002800}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002801
2802//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002803// Member Pointer Evaluation
2804//===----------------------------------------------------------------------===//
2805
2806namespace {
2807class MemberPointerExprEvaluator
2808 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2809 MemberPtr &Result;
2810
2811 bool Success(const ValueDecl *D) {
2812 Result = MemberPtr(D);
2813 return true;
2814 }
2815public:
2816
2817 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2818 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2819
2820 bool Success(const CCValue &V, const Expr *E) {
2821 Result.setFrom(V);
2822 return true;
2823 }
Richard Smith51201882011-12-30 21:15:51 +00002824 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002825 return Success((const ValueDecl*)0);
2826 }
2827
2828 bool VisitCastExpr(const CastExpr *E);
2829 bool VisitUnaryAddrOf(const UnaryOperator *E);
2830};
2831} // end anonymous namespace
2832
2833static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2834 EvalInfo &Info) {
2835 assert(E->isRValue() && E->getType()->isMemberPointerType());
2836 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2837}
2838
2839bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2840 switch (E->getCastKind()) {
2841 default:
2842 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2843
2844 case CK_NullToMemberPointer:
Richard Smith51201882011-12-30 21:15:51 +00002845 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002846
2847 case CK_BaseToDerivedMemberPointer: {
2848 if (!Visit(E->getSubExpr()))
2849 return false;
2850 if (E->path_empty())
2851 return true;
2852 // Base-to-derived member pointer casts store the path in derived-to-base
2853 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2854 // the wrong end of the derived->base arc, so stagger the path by one class.
2855 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2856 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2857 PathI != PathE; ++PathI) {
2858 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2859 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2860 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00002861 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002862 }
2863 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2864 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002865 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002866 return true;
2867 }
2868
2869 case CK_DerivedToBaseMemberPointer:
2870 if (!Visit(E->getSubExpr()))
2871 return false;
2872 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2873 PathE = E->path_end(); PathI != PathE; ++PathI) {
2874 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2875 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2876 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00002877 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002878 }
2879 return true;
2880 }
2881}
2882
2883bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2884 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
2885 // member can be formed.
2886 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
2887}
2888
2889//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00002890// Record Evaluation
2891//===----------------------------------------------------------------------===//
2892
2893namespace {
2894 class RecordExprEvaluator
2895 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
2896 const LValue &This;
2897 APValue &Result;
2898 public:
2899
2900 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
2901 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
2902
2903 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002904 return CheckConstantExpression(Info, E, V, Result);
Richard Smith180f4792011-11-10 06:34:14 +00002905 }
Richard Smith51201882011-12-30 21:15:51 +00002906 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00002907
Richard Smith59efe262011-11-11 04:05:33 +00002908 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00002909 bool VisitInitListExpr(const InitListExpr *E);
2910 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
2911 };
2912}
2913
Richard Smith51201882011-12-30 21:15:51 +00002914/// Perform zero-initialization on an object of non-union class type.
2915/// C++11 [dcl.init]p5:
2916/// To zero-initialize an object or reference of type T means:
2917/// [...]
2918/// -- if T is a (possibly cv-qualified) non-union class type,
2919/// each non-static data member and each base-class subobject is
2920/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00002921static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
2922 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00002923 const LValue &This, APValue &Result) {
2924 assert(!RD->isUnion() && "Expected non-union class type");
2925 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
2926 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
2927 std::distance(RD->field_begin(), RD->field_end()));
2928
2929 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2930
2931 if (CD) {
2932 unsigned Index = 0;
2933 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00002934 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00002935 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
2936 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002937 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
2938 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00002939 Result.getStructBase(Index)))
2940 return false;
2941 }
2942 }
2943
Richard Smithb4e85ed2012-01-06 16:39:00 +00002944 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
2945 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00002946 // -- if T is a reference type, no initialization is performed.
2947 if ((*I)->getType()->isReferenceType())
2948 continue;
2949
2950 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002951 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smith51201882011-12-30 21:15:51 +00002952
2953 ImplicitValueInitExpr VIE((*I)->getType());
2954 if (!EvaluateConstantExpression(
2955 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
2956 return false;
2957 }
2958
2959 return true;
2960}
2961
2962bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
2963 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2964 if (RD->isUnion()) {
2965 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
2966 // object's first non-static named data member is zero-initialized
2967 RecordDecl::field_iterator I = RD->field_begin();
2968 if (I == RD->field_end()) {
2969 Result = APValue((const FieldDecl*)0);
2970 return true;
2971 }
2972
2973 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002974 HandleLValueMember(Info, E, Subobject, *I);
Richard Smith51201882011-12-30 21:15:51 +00002975 Result = APValue(*I);
2976 ImplicitValueInitExpr VIE((*I)->getType());
2977 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2978 Subobject, &VIE);
2979 }
2980
Richard Smithb4e85ed2012-01-06 16:39:00 +00002981 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00002982}
2983
Richard Smith59efe262011-11-11 04:05:33 +00002984bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
2985 switch (E->getCastKind()) {
2986 default:
2987 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2988
2989 case CK_ConstructorConversion:
2990 return Visit(E->getSubExpr());
2991
2992 case CK_DerivedToBase:
2993 case CK_UncheckedDerivedToBase: {
2994 CCValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00002995 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00002996 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002997 if (!DerivedObject.isStruct())
2998 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00002999
3000 // Derived-to-base rvalue conversion: just slice off the derived part.
3001 APValue *Value = &DerivedObject;
3002 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3003 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3004 PathE = E->path_end(); PathI != PathE; ++PathI) {
3005 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3006 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3007 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3008 RD = Base;
3009 }
3010 Result = *Value;
3011 return true;
3012 }
3013 }
3014}
3015
Richard Smith180f4792011-11-10 06:34:14 +00003016bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3017 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3018 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3019
3020 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003021 const FieldDecl *Field = E->getInitializedFieldInUnion();
3022 Result = APValue(Field);
3023 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003024 return true;
Richard Smithec789162012-01-12 18:54:33 +00003025
3026 // If the initializer list for a union does not contain any elements, the
3027 // first element of the union is value-initialized.
3028 ImplicitValueInitExpr VIE(Field->getType());
3029 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3030
Richard Smith180f4792011-11-10 06:34:14 +00003031 LValue Subobject = This;
Richard Smithec789162012-01-12 18:54:33 +00003032 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00003033 return EvaluateConstantExpression(Result.getUnionValue(), Info,
Richard Smithec789162012-01-12 18:54:33 +00003034 Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003035 }
3036
3037 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3038 "initializer list for class with base classes");
3039 Result = APValue(APValue::UninitStruct(), 0,
3040 std::distance(RD->field_begin(), RD->field_end()));
3041 unsigned ElementNo = 0;
3042 for (RecordDecl::field_iterator Field = RD->field_begin(),
3043 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3044 // Anonymous bit-fields are not considered members of the class for
3045 // purposes of aggregate initialization.
3046 if (Field->isUnnamedBitfield())
3047 continue;
3048
3049 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003050
3051 if (ElementNo < E->getNumInits()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003052 HandleLValueMember(Info, E->getInit(ElementNo), Subobject, *Field,
3053 &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00003054 if (!EvaluateConstantExpression(
3055 Result.getStructField((*Field)->getFieldIndex()),
3056 Info, Subobject, E->getInit(ElementNo++)))
3057 return false;
3058 } else {
3059 // Perform an implicit value-initialization for members beyond the end of
3060 // the initializer list.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003061 HandleLValueMember(Info, E, Subobject, *Field, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00003062 ImplicitValueInitExpr VIE(Field->getType());
3063 if (!EvaluateConstantExpression(
3064 Result.getStructField((*Field)->getFieldIndex()),
3065 Info, Subobject, &VIE))
3066 return false;
3067 }
3068 }
3069
3070 return true;
3071}
3072
3073bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3074 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith51201882011-12-30 21:15:51 +00003075 bool ZeroInit = E->requiresZeroInitialization();
3076 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003077 // If we've already performed zero-initialization, we're already done.
3078 if (!Result.isUninit())
3079 return true;
3080
Richard Smith51201882011-12-30 21:15:51 +00003081 if (ZeroInit)
3082 return ZeroInitialization(E);
3083
Richard Smith61802452011-12-22 02:22:31 +00003084 const CXXRecordDecl *RD = FD->getParent();
3085 if (RD->isUnion())
3086 Result = APValue((FieldDecl*)0);
3087 else
3088 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3089 std::distance(RD->field_begin(), RD->field_end()));
3090 return true;
3091 }
3092
Richard Smith180f4792011-11-10 06:34:14 +00003093 const FunctionDecl *Definition = 0;
3094 FD->getBody(Definition);
3095
Richard Smithc1c5f272011-12-13 06:39:58 +00003096 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3097 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003098
Richard Smith610a60c2012-01-10 04:32:03 +00003099 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003100 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003101 if (const MaterializeTemporaryExpr *ME
3102 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3103 return Visit(ME->GetTemporaryExpr());
3104
Richard Smith51201882011-12-30 21:15:51 +00003105 if (ZeroInit && !ZeroInitialization(E))
3106 return false;
3107
Richard Smith180f4792011-11-10 06:34:14 +00003108 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf48fdb02011-12-09 22:58:01 +00003109 return HandleConstructorCall(E, This, Args,
3110 cast<CXXConstructorDecl>(Definition), Info,
3111 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003112}
3113
3114static bool EvaluateRecord(const Expr *E, const LValue &This,
3115 APValue &Result, EvalInfo &Info) {
3116 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003117 "can't evaluate expression as a record rvalue");
3118 return RecordExprEvaluator(Info, This, Result).Visit(E);
3119}
3120
3121//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003122// Temporary Evaluation
3123//
3124// Temporaries are represented in the AST as rvalues, but generally behave like
3125// lvalues. The full-object of which the temporary is a subobject is implicitly
3126// materialized so that a reference can bind to it.
3127//===----------------------------------------------------------------------===//
3128namespace {
3129class TemporaryExprEvaluator
3130 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3131public:
3132 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3133 LValueExprEvaluatorBaseTy(Info, Result) {}
3134
3135 /// Visit an expression which constructs the value of this temporary.
3136 bool VisitConstructExpr(const Expr *E) {
3137 Result.set(E, Info.CurrentCall);
3138 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
3139 Result, E);
3140 }
3141
3142 bool VisitCastExpr(const CastExpr *E) {
3143 switch (E->getCastKind()) {
3144 default:
3145 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3146
3147 case CK_ConstructorConversion:
3148 return VisitConstructExpr(E->getSubExpr());
3149 }
3150 }
3151 bool VisitInitListExpr(const InitListExpr *E) {
3152 return VisitConstructExpr(E);
3153 }
3154 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3155 return VisitConstructExpr(E);
3156 }
3157 bool VisitCallExpr(const CallExpr *E) {
3158 return VisitConstructExpr(E);
3159 }
3160};
3161} // end anonymous namespace
3162
3163/// Evaluate an expression of record type as a temporary.
3164static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003165 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003166 return TemporaryExprEvaluator(Info, Result).Visit(E);
3167}
3168
3169//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003170// Vector Evaluation
3171//===----------------------------------------------------------------------===//
3172
3173namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003174 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003175 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3176 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003177 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003178
Richard Smith07fc6572011-10-22 21:10:00 +00003179 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3180 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003181
Richard Smith07fc6572011-10-22 21:10:00 +00003182 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3183 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3184 // FIXME: remove this APValue copy.
3185 Result = APValue(V.data(), V.size());
3186 return true;
3187 }
Richard Smith69c2c502011-11-04 05:33:44 +00003188 bool Success(const CCValue &V, const Expr *E) {
3189 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003190 Result = V;
3191 return true;
3192 }
Richard Smith51201882011-12-30 21:15:51 +00003193 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003194
Richard Smith07fc6572011-10-22 21:10:00 +00003195 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003196 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003197 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003198 bool VisitInitListExpr(const InitListExpr *E);
3199 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003200 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003201 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003202 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003203 };
3204} // end anonymous namespace
3205
3206static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003207 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003208 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003209}
3210
Richard Smith07fc6572011-10-22 21:10:00 +00003211bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3212 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003213 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003214
Richard Smithd62ca372011-12-06 22:44:34 +00003215 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003216 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003217
Eli Friedman46a52322011-03-25 00:43:55 +00003218 switch (E->getCastKind()) {
3219 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003220 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003221 if (SETy->isIntegerType()) {
3222 APSInt IntResult;
3223 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003224 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003225 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003226 } else if (SETy->isRealFloatingType()) {
3227 APFloat F(0.0);
3228 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003229 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003230 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003231 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003232 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003233 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003234
3235 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003236 SmallVector<APValue, 4> Elts(NElts, Val);
3237 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003238 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003239 case CK_BitCast: {
3240 // Evaluate the operand into an APInt we can extract from.
3241 llvm::APInt SValInt;
3242 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3243 return false;
3244 // Extract the elements
3245 QualType EltTy = VTy->getElementType();
3246 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3247 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3248 SmallVector<APValue, 4> Elts;
3249 if (EltTy->isRealFloatingType()) {
3250 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3251 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3252 unsigned FloatEltSize = EltSize;
3253 if (&Sem == &APFloat::x87DoubleExtended)
3254 FloatEltSize = 80;
3255 for (unsigned i = 0; i < NElts; i++) {
3256 llvm::APInt Elt;
3257 if (BigEndian)
3258 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3259 else
3260 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3261 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3262 }
3263 } else if (EltTy->isIntegerType()) {
3264 for (unsigned i = 0; i < NElts; i++) {
3265 llvm::APInt Elt;
3266 if (BigEndian)
3267 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3268 else
3269 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3270 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3271 }
3272 } else {
3273 return Error(E);
3274 }
3275 return Success(Elts, E);
3276 }
Eli Friedman46a52322011-03-25 00:43:55 +00003277 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003278 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003279 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003280}
3281
Richard Smith07fc6572011-10-22 21:10:00 +00003282bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003283VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003284 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003285 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003286 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003287
Nate Begeman59b5da62009-01-18 03:20:47 +00003288 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003289 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003290
Eli Friedman3edd5a92012-01-03 23:24:20 +00003291 // The number of initializers can be less than the number of
3292 // vector elements. For OpenCL, this can be due to nested vector
3293 // initialization. For GCC compatibility, missing trailing elements
3294 // should be initialized with zeroes.
3295 unsigned CountInits = 0, CountElts = 0;
3296 while (CountElts < NumElements) {
3297 // Handle nested vector initialization.
3298 if (CountInits < NumInits
3299 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3300 APValue v;
3301 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3302 return Error(E);
3303 unsigned vlen = v.getVectorLength();
3304 for (unsigned j = 0; j < vlen; j++)
3305 Elements.push_back(v.getVectorElt(j));
3306 CountElts += vlen;
3307 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003308 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003309 if (CountInits < NumInits) {
3310 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3311 return Error(E);
3312 } else // trailing integer zero.
3313 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3314 Elements.push_back(APValue(sInt));
3315 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003316 } else {
3317 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003318 if (CountInits < NumInits) {
3319 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3320 return Error(E);
3321 } else // trailing float zero.
3322 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3323 Elements.push_back(APValue(f));
3324 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003325 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003326 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003327 }
Richard Smith07fc6572011-10-22 21:10:00 +00003328 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003329}
3330
Richard Smith07fc6572011-10-22 21:10:00 +00003331bool
Richard Smith51201882011-12-30 21:15:51 +00003332VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003333 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003334 QualType EltTy = VT->getElementType();
3335 APValue ZeroElement;
3336 if (EltTy->isIntegerType())
3337 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3338 else
3339 ZeroElement =
3340 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3341
Chris Lattner5f9e2722011-07-23 10:55:15 +00003342 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003343 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003344}
3345
Richard Smith07fc6572011-10-22 21:10:00 +00003346bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003347 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003348 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003349}
3350
Nate Begeman59b5da62009-01-18 03:20:47 +00003351//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003352// Array Evaluation
3353//===----------------------------------------------------------------------===//
3354
3355namespace {
3356 class ArrayExprEvaluator
3357 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003358 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003359 APValue &Result;
3360 public:
3361
Richard Smith180f4792011-11-10 06:34:14 +00003362 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3363 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003364
3365 bool Success(const APValue &V, const Expr *E) {
3366 assert(V.isArray() && "Expected array type");
3367 Result = V;
3368 return true;
3369 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003370
Richard Smith51201882011-12-30 21:15:51 +00003371 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003372 const ConstantArrayType *CAT =
3373 Info.Ctx.getAsConstantArrayType(E->getType());
3374 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003375 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003376
3377 Result = APValue(APValue::UninitArray(), 0,
3378 CAT->getSize().getZExtValue());
3379 if (!Result.hasArrayFiller()) return true;
3380
Richard Smith51201882011-12-30 21:15:51 +00003381 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003382 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003383 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003384 ImplicitValueInitExpr VIE(CAT->getElementType());
3385 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3386 Subobject, &VIE);
3387 }
3388
Richard Smithcc5d4f62011-11-07 09:22:26 +00003389 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003390 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003391 };
3392} // end anonymous namespace
3393
Richard Smith180f4792011-11-10 06:34:14 +00003394static bool EvaluateArray(const Expr *E, const LValue &This,
3395 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003396 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003397 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003398}
3399
3400bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3401 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3402 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003403 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003404
Richard Smith974c5f92011-12-22 01:07:19 +00003405 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3406 // an appropriately-typed string literal enclosed in braces.
Richard Smithec789162012-01-12 18:54:33 +00003407 if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
Richard Smith974c5f92011-12-22 01:07:19 +00003408 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3409 LValue LV;
3410 if (!EvaluateLValue(E->getInit(0), LV, Info))
3411 return false;
3412 uint64_t NumElements = CAT->getSize().getZExtValue();
3413 Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3414
3415 // Copy the string literal into the array. FIXME: Do this better.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003416 LV.addArray(Info, E, CAT);
Richard Smith974c5f92011-12-22 01:07:19 +00003417 for (uint64_t I = 0; I < NumElements; ++I) {
3418 CCValue Char;
3419 if (!HandleLValueToRValueConversion(Info, E->getInit(0),
3420 CAT->getElementType(), LV, Char))
3421 return false;
3422 if (!CheckConstantExpression(Info, E->getInit(0), Char,
3423 Result.getArrayInitializedElt(I)))
3424 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003425 if (!HandleLValueArrayAdjustment(Info, E->getInit(0), LV,
3426 CAT->getElementType(), 1))
Richard Smith974c5f92011-12-22 01:07:19 +00003427 return false;
3428 }
3429 return true;
3430 }
3431
Richard Smithcc5d4f62011-11-07 09:22:26 +00003432 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3433 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003434 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003435 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003436 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003437 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003438 I != End; ++I, ++Index) {
3439 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
3440 Info, Subobject, cast<Expr>(*I)))
Richard Smithcc5d4f62011-11-07 09:22:26 +00003441 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003442 if (!HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3443 CAT->getElementType(), 1))
Richard Smith180f4792011-11-10 06:34:14 +00003444 return false;
3445 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003446
3447 if (!Result.hasArrayFiller()) return true;
3448 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003449 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3450 // but sometimes does:
3451 // struct S { constexpr S() : p(&p) {} void *p; };
3452 // S s[10] = {};
Richard Smithcc5d4f62011-11-07 09:22:26 +00003453 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smith180f4792011-11-10 06:34:14 +00003454 Subobject, E->getArrayFiller());
Richard Smithcc5d4f62011-11-07 09:22:26 +00003455}
3456
Richard Smithe24f5fc2011-11-17 22:56:20 +00003457bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3458 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3459 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003460 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003461
Richard Smithec789162012-01-12 18:54:33 +00003462 bool HadZeroInit = !Result.isUninit();
3463 if (!HadZeroInit)
3464 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003465 if (!Result.hasArrayFiller())
3466 return true;
3467
3468 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003469
Richard Smith51201882011-12-30 21:15:51 +00003470 bool ZeroInit = E->requiresZeroInitialization();
3471 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003472 if (HadZeroInit)
3473 return true;
3474
Richard Smith51201882011-12-30 21:15:51 +00003475 if (ZeroInit) {
3476 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003477 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003478 ImplicitValueInitExpr VIE(CAT->getElementType());
3479 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3480 Subobject, &VIE);
3481 }
3482
Richard Smith61802452011-12-22 02:22:31 +00003483 const CXXRecordDecl *RD = FD->getParent();
3484 if (RD->isUnion())
3485 Result.getArrayFiller() = APValue((FieldDecl*)0);
3486 else
3487 Result.getArrayFiller() =
3488 APValue(APValue::UninitStruct(), RD->getNumBases(),
3489 std::distance(RD->field_begin(), RD->field_end()));
3490 return true;
3491 }
3492
Richard Smithe24f5fc2011-11-17 22:56:20 +00003493 const FunctionDecl *Definition = 0;
3494 FD->getBody(Definition);
3495
Richard Smithc1c5f272011-12-13 06:39:58 +00003496 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3497 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003498
3499 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3500 // but sometimes does:
3501 // struct S { constexpr S() : p(&p) {} void *p; };
3502 // S s[10];
3503 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003504 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003505
Richard Smithec789162012-01-12 18:54:33 +00003506 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003507 ImplicitValueInitExpr VIE(CAT->getElementType());
3508 if (!EvaluateConstantExpression(Result.getArrayFiller(), Info, Subobject,
3509 &VIE))
3510 return false;
3511 }
3512
Richard Smithe24f5fc2011-11-17 22:56:20 +00003513 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf48fdb02011-12-09 22:58:01 +00003514 return HandleConstructorCall(E, Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003515 cast<CXXConstructorDecl>(Definition),
3516 Info, Result.getArrayFiller());
3517}
3518
Richard Smithcc5d4f62011-11-07 09:22:26 +00003519//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003520// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003521//
3522// As a GNU extension, we support casting pointers to sufficiently-wide integer
3523// types and back in constant folding. Integer values are thus represented
3524// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003525//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003526
3527namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003528class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003529 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00003530 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003531public:
Richard Smith47a1eed2011-10-29 20:57:55 +00003532 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003533 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003534
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003535 bool Success(const llvm::APSInt &SI, const Expr *E) {
3536 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003537 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003538 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003539 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003540 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003541 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003542 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003543 return true;
3544 }
3545
Daniel Dunbar131eb432009-02-19 09:06:44 +00003546 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003547 assert(E->getType()->isIntegralOrEnumerationType() &&
3548 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003549 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003550 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003551 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003552 Result.getInt().setIsUnsigned(
3553 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003554 return true;
3555 }
3556
3557 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003558 assert(E->getType()->isIntegralOrEnumerationType() &&
3559 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003560 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003561 return true;
3562 }
3563
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003564 bool Success(CharUnits Size, const Expr *E) {
3565 return Success(Size.getQuantity(), E);
3566 }
3567
Richard Smith47a1eed2011-10-29 20:57:55 +00003568 bool Success(const CCValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00003569 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00003570 Result = V;
3571 return true;
3572 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003573 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003574 }
Mike Stump1eb44332009-09-09 15:08:12 +00003575
Richard Smith51201882011-12-30 21:15:51 +00003576 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00003577
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003578 //===--------------------------------------------------------------------===//
3579 // Visitor Methods
3580 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003581
Chris Lattner4c4867e2008-07-12 00:38:25 +00003582 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003583 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003584 }
3585 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003586 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003587 }
Eli Friedman04309752009-11-24 05:28:59 +00003588
3589 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3590 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003591 if (CheckReferencedDecl(E, E->getDecl()))
3592 return true;
3593
3594 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003595 }
3596 bool VisitMemberExpr(const MemberExpr *E) {
3597 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00003598 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00003599 return true;
3600 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003601
3602 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003603 }
3604
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003605 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003606 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003607 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003608 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00003609
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003610 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003611 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00003612
Anders Carlsson3068d112008-11-16 19:01:22 +00003613 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003614 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00003615 }
Mike Stump1eb44332009-09-09 15:08:12 +00003616
Richard Smithf10d9172011-10-11 21:43:33 +00003617 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00003618 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00003619 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00003620 }
3621
Sebastian Redl64b45f72009-01-05 20:52:13 +00003622 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003623 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003624 }
3625
Francois Pichet6ad6f282010-12-07 00:08:36 +00003626 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3627 return Success(E->getValue(), E);
3628 }
3629
John Wiegley21ff2e52011-04-28 00:16:57 +00003630 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3631 return Success(E->getValue(), E);
3632 }
3633
John Wiegley55262202011-04-25 06:54:41 +00003634 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3635 return Success(E->getValue(), E);
3636 }
3637
Eli Friedman722c7172009-02-28 03:59:05 +00003638 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003639 bool VisitUnaryImag(const UnaryOperator *E);
3640
Sebastian Redl295995c2010-09-10 20:55:47 +00003641 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00003642 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00003643
Chris Lattnerfcee0012008-07-11 21:24:13 +00003644private:
Ken Dyck8b752f12010-01-27 17:10:57 +00003645 CharUnits GetAlignOfExpr(const Expr *E);
3646 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003647 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003648 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003649 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003650};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003651} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003652
Richard Smithc49bd112011-10-28 17:51:58 +00003653/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3654/// produce either the integer value or a pointer.
3655///
3656/// GCC has a heinous extension which folds casts between pointer types and
3657/// pointer-sized integral types. We support this by allowing the evaluation of
3658/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3659/// Some simple arithmetic on such values is supported (they are treated much
3660/// like char*).
Richard Smithf48fdb02011-12-09 22:58:01 +00003661static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00003662 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003663 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003664 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003665}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003666
Richard Smithf48fdb02011-12-09 22:58:01 +00003667static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003668 CCValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00003669 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003670 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003671 if (!Val.isInt()) {
3672 // FIXME: It would be better to produce the diagnostic for casting
3673 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00003674 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00003675 return false;
3676 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003677 Result = Val.getInt();
3678 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00003679}
Anders Carlsson650c92f2008-07-08 15:34:11 +00003680
Richard Smithf48fdb02011-12-09 22:58:01 +00003681/// Check whether the given declaration can be directly converted to an integral
3682/// rvalue. If not, no diagnostic is produced; there are other things we can
3683/// try.
Eli Friedman04309752009-11-24 05:28:59 +00003684bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00003685 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003686 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003687 // Check for signedness/width mismatches between E type and ECD value.
3688 bool SameSign = (ECD->getInitVal().isSigned()
3689 == E->getType()->isSignedIntegerOrEnumerationType());
3690 bool SameWidth = (ECD->getInitVal().getBitWidth()
3691 == Info.Ctx.getIntWidth(E->getType()));
3692 if (SameSign && SameWidth)
3693 return Success(ECD->getInitVal(), E);
3694 else {
3695 // Get rid of mismatch (otherwise Success assertions will fail)
3696 // by computing a new value matching the type of E.
3697 llvm::APSInt Val = ECD->getInitVal();
3698 if (!SameSign)
3699 Val.setIsSigned(!ECD->getInitVal().isSigned());
3700 if (!SameWidth)
3701 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3702 return Success(Val, E);
3703 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003704 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003705 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00003706}
3707
Chris Lattnera4d55d82008-10-06 06:40:35 +00003708/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3709/// as GCC.
3710static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3711 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003712 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00003713 enum gcc_type_class {
3714 no_type_class = -1,
3715 void_type_class, integer_type_class, char_type_class,
3716 enumeral_type_class, boolean_type_class,
3717 pointer_type_class, reference_type_class, offset_type_class,
3718 real_type_class, complex_type_class,
3719 function_type_class, method_type_class,
3720 record_type_class, union_type_class,
3721 array_type_class, string_type_class,
3722 lang_type_class
3723 };
Mike Stump1eb44332009-09-09 15:08:12 +00003724
3725 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00003726 // ideal, however it is what gcc does.
3727 if (E->getNumArgs() == 0)
3728 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00003729
Chris Lattnera4d55d82008-10-06 06:40:35 +00003730 QualType ArgTy = E->getArg(0)->getType();
3731 if (ArgTy->isVoidType())
3732 return void_type_class;
3733 else if (ArgTy->isEnumeralType())
3734 return enumeral_type_class;
3735 else if (ArgTy->isBooleanType())
3736 return boolean_type_class;
3737 else if (ArgTy->isCharType())
3738 return string_type_class; // gcc doesn't appear to use char_type_class
3739 else if (ArgTy->isIntegerType())
3740 return integer_type_class;
3741 else if (ArgTy->isPointerType())
3742 return pointer_type_class;
3743 else if (ArgTy->isReferenceType())
3744 return reference_type_class;
3745 else if (ArgTy->isRealType())
3746 return real_type_class;
3747 else if (ArgTy->isComplexType())
3748 return complex_type_class;
3749 else if (ArgTy->isFunctionType())
3750 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00003751 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00003752 return record_type_class;
3753 else if (ArgTy->isUnionType())
3754 return union_type_class;
3755 else if (ArgTy->isArrayType())
3756 return array_type_class;
3757 else if (ArgTy->isUnionType())
3758 return union_type_class;
3759 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00003760 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00003761 return -1;
3762}
3763
Richard Smith80d4b552011-12-28 19:48:30 +00003764/// EvaluateBuiltinConstantPForLValue - Determine the result of
3765/// __builtin_constant_p when applied to the given lvalue.
3766///
3767/// An lvalue is only "constant" if it is a pointer or reference to the first
3768/// character of a string literal.
3769template<typename LValue>
3770static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
3771 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
3772 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3773}
3774
3775/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
3776/// GCC as we can manage.
3777static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
3778 QualType ArgType = Arg->getType();
3779
3780 // __builtin_constant_p always has one operand. The rules which gcc follows
3781 // are not precisely documented, but are as follows:
3782 //
3783 // - If the operand is of integral, floating, complex or enumeration type,
3784 // and can be folded to a known value of that type, it returns 1.
3785 // - If the operand and can be folded to a pointer to the first character
3786 // of a string literal (or such a pointer cast to an integral type), it
3787 // returns 1.
3788 //
3789 // Otherwise, it returns 0.
3790 //
3791 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3792 // its support for this does not currently work.
3793 if (ArgType->isIntegralOrEnumerationType()) {
3794 Expr::EvalResult Result;
3795 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
3796 return false;
3797
3798 APValue &V = Result.Val;
3799 if (V.getKind() == APValue::Int)
3800 return true;
3801
3802 return EvaluateBuiltinConstantPForLValue(V);
3803 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3804 return Arg->isEvaluatable(Ctx);
3805 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3806 LValue LV;
3807 Expr::EvalStatus Status;
3808 EvalInfo Info(Ctx, Status);
3809 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
3810 : EvaluatePointer(Arg, LV, Info)) &&
3811 !Status.HasSideEffects)
3812 return EvaluateBuiltinConstantPForLValue(LV);
3813 }
3814
3815 // Anything else isn't considered to be sufficiently constant.
3816 return false;
3817}
3818
John McCall42c8f872010-05-10 23:27:23 +00003819/// Retrieves the "underlying object type" of the given expression,
3820/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003821QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3822 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3823 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00003824 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003825 } else if (const Expr *E = B.get<const Expr*>()) {
3826 if (isa<CompoundLiteralExpr>(E))
3827 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00003828 }
3829
3830 return QualType();
3831}
3832
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003833bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00003834 // TODO: Perhaps we should let LLVM lower this?
3835 LValue Base;
3836 if (!EvaluatePointer(E->getArg(0), Base, Info))
3837 return false;
3838
3839 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003840 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00003841
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003842 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00003843 if (T.isNull() ||
3844 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00003845 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00003846 T->isVariablyModifiedType() ||
3847 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00003848 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00003849
3850 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3851 CharUnits Offset = Base.getLValueOffset();
3852
3853 if (!Offset.isNegative() && Offset <= Size)
3854 Size -= Offset;
3855 else
3856 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003857 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00003858}
3859
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003860bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003861 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00003862 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003863 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003864
3865 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00003866 if (TryEvaluateBuiltinObjectSize(E))
3867 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00003868
Eric Christopherb2aaf512010-01-19 22:58:35 +00003869 // If evaluating the argument has side-effects we can't determine
3870 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00003871 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003872 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00003873 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003874 return Success(0, E);
3875 }
Mike Stumpc4c90452009-10-27 22:09:17 +00003876
Richard Smithf48fdb02011-12-09 22:58:01 +00003877 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003878 }
3879
Chris Lattner019f4e82008-10-06 05:28:25 +00003880 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003881 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00003882
Richard Smith80d4b552011-12-28 19:48:30 +00003883 case Builtin::BI__builtin_constant_p:
3884 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00003885
Chris Lattner21fb98e2009-09-23 06:06:36 +00003886 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003887 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003888 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00003889 return Success(Operand, E);
3890 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00003891
3892 case Builtin::BI__builtin_expect:
3893 return Visit(E->getArg(0));
Douglas Gregor5726d402010-09-10 06:27:15 +00003894
3895 case Builtin::BIstrlen:
3896 case Builtin::BI__builtin_strlen:
3897 // As an extension, we support strlen() and __builtin_strlen() as constant
3898 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003899 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00003900 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
3901 // The string literal may have embedded null characters. Find the first
3902 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003903 StringRef Str = S->getString();
3904 StringRef::size_type Pos = Str.find(0);
3905 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00003906 Str = Str.substr(0, Pos);
3907
3908 return Success(Str.size(), E);
3909 }
3910
Richard Smithf48fdb02011-12-09 22:58:01 +00003911 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00003912
3913 case Builtin::BI__atomic_is_lock_free: {
3914 APSInt SizeVal;
3915 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
3916 return false;
3917
3918 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
3919 // of two less than the maximum inline atomic width, we know it is
3920 // lock-free. If the size isn't a power of two, or greater than the
3921 // maximum alignment where we promote atomics, we know it is not lock-free
3922 // (at least not in the sense of atomic_is_lock_free). Otherwise,
3923 // the answer can only be determined at runtime; for example, 16-byte
3924 // atomics have lock-free implementations on some, but not all,
3925 // x86-64 processors.
3926
3927 // Check power-of-two.
3928 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
3929 if (!Size.isPowerOfTwo())
3930#if 0
3931 // FIXME: Suppress this folding until the ABI for the promotion width
3932 // settles.
3933 return Success(0, E);
3934#else
Richard Smithf48fdb02011-12-09 22:58:01 +00003935 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00003936#endif
3937
3938#if 0
3939 // Check against promotion width.
3940 // FIXME: Suppress this folding until the ABI for the promotion width
3941 // settles.
3942 unsigned PromoteWidthBits =
3943 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
3944 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
3945 return Success(0, E);
3946#endif
3947
3948 // Check against inlining width.
3949 unsigned InlineWidthBits =
3950 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
3951 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
3952 return Success(1, E);
3953
Richard Smithf48fdb02011-12-09 22:58:01 +00003954 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00003955 }
Chris Lattner019f4e82008-10-06 05:28:25 +00003956 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00003957}
Anders Carlsson650c92f2008-07-08 15:34:11 +00003958
Richard Smith625b8072011-10-31 01:37:14 +00003959static bool HasSameBase(const LValue &A, const LValue &B) {
3960 if (!A.getLValueBase())
3961 return !B.getLValueBase();
3962 if (!B.getLValueBase())
3963 return false;
3964
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003965 if (A.getLValueBase().getOpaqueValue() !=
3966 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00003967 const Decl *ADecl = GetLValueBaseDecl(A);
3968 if (!ADecl)
3969 return false;
3970 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00003971 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00003972 return false;
3973 }
3974
3975 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith177dce72011-11-01 16:57:24 +00003976 A.getLValueFrame() == B.getLValueFrame();
Richard Smith625b8072011-10-31 01:37:14 +00003977}
3978
Chris Lattnerb542afe2008-07-11 19:10:17 +00003979bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00003980 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00003981 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00003982
John McCall2de56d12010-08-25 11:45:40 +00003983 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00003984 VisitIgnoredValue(E->getLHS());
3985 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00003986 }
3987
3988 if (E->isLogicalOp()) {
3989 // These need to be handled specially because the operands aren't
3990 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00003991 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00003992
Richard Smithc49bd112011-10-28 17:51:58 +00003993 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00003994 // We were able to evaluate the LHS, see if we can get away with not
3995 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00003996 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003997 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003998
Richard Smithc49bd112011-10-28 17:51:58 +00003999 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00004000 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004001 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004002 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00004003 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004004 }
4005 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00004006 // FIXME: If both evaluations fail, we should produce the diagnostic from
4007 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
4008 // less clear how to diagnose this.
Richard Smithc49bd112011-10-28 17:51:58 +00004009 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004010 // We can't evaluate the LHS; however, sometimes the result
4011 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf48fdb02011-12-09 22:58:01 +00004012 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004013 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004014 // must have had side effects.
Richard Smith1e12c592011-10-16 21:26:27 +00004015 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004016
4017 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004018 }
4019 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00004020 }
Eli Friedmana6afa762008-11-13 06:09:17 +00004021
Eli Friedmana6afa762008-11-13 06:09:17 +00004022 return false;
4023 }
4024
Anders Carlsson286f85e2008-11-16 07:17:21 +00004025 QualType LHSTy = E->getLHS()->getType();
4026 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004027
4028 if (LHSTy->isAnyComplexType()) {
4029 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004030 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004031
4032 if (!EvaluateComplex(E->getLHS(), LHS, Info))
4033 return false;
4034
4035 if (!EvaluateComplex(E->getRHS(), RHS, Info))
4036 return false;
4037
4038 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004039 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004040 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004041 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004042 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4043
John McCall2de56d12010-08-25 11:45:40 +00004044 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004045 return Success((CR_r == APFloat::cmpEqual &&
4046 CR_i == APFloat::cmpEqual), E);
4047 else {
John McCall2de56d12010-08-25 11:45:40 +00004048 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004049 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004050 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004051 CR_r == APFloat::cmpLessThan ||
4052 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004053 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004054 CR_i == APFloat::cmpLessThan ||
4055 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004056 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004057 } else {
John McCall2de56d12010-08-25 11:45:40 +00004058 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004059 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4060 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4061 else {
John McCall2de56d12010-08-25 11:45:40 +00004062 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004063 "Invalid compex comparison.");
4064 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4065 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4066 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004067 }
4068 }
Mike Stump1eb44332009-09-09 15:08:12 +00004069
Anders Carlsson286f85e2008-11-16 07:17:21 +00004070 if (LHSTy->isRealFloatingType() &&
4071 RHSTy->isRealFloatingType()) {
4072 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004073
Anders Carlsson286f85e2008-11-16 07:17:21 +00004074 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4075 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004076
Anders Carlsson286f85e2008-11-16 07:17:21 +00004077 if (!EvaluateFloat(E->getLHS(), LHS, Info))
4078 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004079
Anders Carlsson286f85e2008-11-16 07:17:21 +00004080 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004081
Anders Carlsson286f85e2008-11-16 07:17:21 +00004082 switch (E->getOpcode()) {
4083 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004084 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004085 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004086 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004087 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004088 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004089 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004090 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004091 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004092 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004093 E);
John McCall2de56d12010-08-25 11:45:40 +00004094 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004095 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004096 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004097 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004098 || CR == APFloat::cmpLessThan
4099 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004100 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004101 }
Mike Stump1eb44332009-09-09 15:08:12 +00004102
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004103 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004104 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00004105 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00004106 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
4107 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004108
John McCallefdb83e2010-05-07 21:00:08 +00004109 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00004110 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
4111 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004112
Richard Smith625b8072011-10-31 01:37:14 +00004113 // Reject differing bases from the normal codepath; we special-case
4114 // comparisons to null.
4115 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004116 if (E->getOpcode() == BO_Sub) {
4117 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004118 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4119 return false;
4120 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4121 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4122 if (!LHSExpr || !RHSExpr)
4123 return false;
4124 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4125 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4126 if (!LHSAddrExpr || !RHSAddrExpr)
4127 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004128 // Make sure both labels come from the same function.
4129 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4130 RHSAddrExpr->getLabel()->getDeclContext())
4131 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004132 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4133 return true;
4134 }
Richard Smith9e36b532011-10-31 05:11:32 +00004135 // Inequalities and subtractions between unrelated pointers have
4136 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004137 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004138 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004139 // A constant address may compare equal to the address of a symbol.
4140 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004141 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004142 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4143 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004144 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004145 // It's implementation-defined whether distinct literals will have
Eli Friedmanc45061b2011-10-31 22:54:30 +00004146 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smith74f46342011-11-04 01:10:57 +00004147 // distinct. However, we do know that the address of a literal will be
4148 // non-null.
4149 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4150 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004151 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004152 // We can't tell whether weak symbols will end up pointing to the same
4153 // object.
4154 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004155 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004156 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004157 // (Note that clang defaults to -fmerge-all-constants, which can
4158 // lead to inconsistent results for comparisons involving the address
4159 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004160 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004161 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004162
Richard Smithcc5d4f62011-11-07 09:22:26 +00004163 // FIXME: Implement the C++11 restrictions:
4164 // - Pointer subtractions must be on elements of the same array.
4165 // - Pointer comparisons must be between members with the same access.
4166
John McCall2de56d12010-08-25 11:45:40 +00004167 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00004168 QualType Type = E->getLHS()->getType();
4169 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004170
Richard Smith180f4792011-11-10 06:34:14 +00004171 CharUnits ElementSize;
4172 if (!HandleSizeof(Info, ElementType, ElementSize))
4173 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004174
Richard Smith180f4792011-11-10 06:34:14 +00004175 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dycka7305832010-01-15 12:37:54 +00004176 RHSValue.getLValueOffset();
4177 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004178 }
Richard Smith625b8072011-10-31 01:37:14 +00004179
4180 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4181 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4182 switch (E->getOpcode()) {
4183 default: llvm_unreachable("missing comparison operator");
4184 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4185 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4186 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4187 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4188 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4189 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004190 }
Anders Carlsson3068d112008-11-16 19:01:22 +00004191 }
4192 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004193 if (!LHSTy->isIntegralOrEnumerationType() ||
4194 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004195 // We can't continue from here for non-integral types.
4196 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004197 }
4198
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004199 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00004200 CCValue LHSVal;
Richard Smithc49bd112011-10-28 17:51:58 +00004201 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00004202 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00004203
Richard Smithc49bd112011-10-28 17:51:58 +00004204 if (!Visit(E->getRHS()))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004205 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00004206 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004207
4208 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00004209 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00004210 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4211 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00004212 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00004213 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004214 else
Richard Smith47a1eed2011-10-29 20:57:55 +00004215 LHSVal.getLValueOffset() -= AdditionalOffset;
4216 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004217 return true;
4218 }
4219
4220 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00004221 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00004222 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004223 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4224 LHSVal.getInt().getZExtValue());
4225 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00004226 return true;
4227 }
4228
Eli Friedman65639282012-01-04 23:13:47 +00004229 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4230 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedman65639282012-01-04 23:13:47 +00004231 if (!LHSVal.getLValueOffset().isZero() ||
4232 !RHSVal.getLValueOffset().isZero())
4233 return false;
4234 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4235 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4236 if (!LHSExpr || !RHSExpr)
4237 return false;
4238 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4239 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4240 if (!LHSAddrExpr || !RHSAddrExpr)
4241 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004242 // Make sure both labels come from the same function.
4243 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4244 RHSAddrExpr->getLabel()->getDeclContext())
4245 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004246 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4247 return true;
4248 }
4249
Eli Friedman42edd0d2009-03-24 01:14:50 +00004250 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00004251 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00004252 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004253
Richard Smithc49bd112011-10-28 17:51:58 +00004254 APSInt &LHS = LHSVal.getInt();
4255 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00004256
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004257 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00004258 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004259 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004260 case BO_Mul: return Success(LHS * RHS, E);
4261 case BO_Add: return Success(LHS + RHS, E);
4262 case BO_Sub: return Success(LHS - RHS, E);
4263 case BO_And: return Success(LHS & RHS, E);
4264 case BO_Xor: return Success(LHS ^ RHS, E);
4265 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004266 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00004267 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004268 return Error(E, diag::note_expr_divide_by_zero);
Richard Smithc49bd112011-10-28 17:51:58 +00004269 return Success(LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004270 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00004271 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004272 return Error(E, diag::note_expr_divide_by_zero);
Richard Smithc49bd112011-10-28 17:51:58 +00004273 return Success(LHS % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004274 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00004275 // During constant-folding, a negative shift is an opposite shift.
4276 if (RHS.isSigned() && RHS.isNegative()) {
4277 RHS = -RHS;
4278 goto shift_right;
4279 }
4280
4281 shift_left:
4282 unsigned SA
Richard Smithc49bd112011-10-28 17:51:58 +00004283 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4284 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004285 }
John McCall2de56d12010-08-25 11:45:40 +00004286 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00004287 // During constant-folding, a negative shift is an opposite shift.
4288 if (RHS.isSigned() && RHS.isNegative()) {
4289 RHS = -RHS;
4290 goto shift_left;
4291 }
4292
4293 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00004294 unsigned SA =
Richard Smithc49bd112011-10-28 17:51:58 +00004295 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4296 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004297 }
Mike Stump1eb44332009-09-09 15:08:12 +00004298
Richard Smithc49bd112011-10-28 17:51:58 +00004299 case BO_LT: return Success(LHS < RHS, E);
4300 case BO_GT: return Success(LHS > RHS, E);
4301 case BO_LE: return Success(LHS <= RHS, E);
4302 case BO_GE: return Success(LHS >= RHS, E);
4303 case BO_EQ: return Success(LHS == RHS, E);
4304 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00004305 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004306}
4307
Ken Dyck8b752f12010-01-27 17:10:57 +00004308CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00004309 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4310 // the result is the size of the referenced type."
4311 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4312 // result shall be the alignment of the referenced type."
4313 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4314 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00004315
4316 // __alignof is defined to return the preferred alignment.
4317 return Info.Ctx.toCharUnitsFromBits(
4318 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00004319}
4320
Ken Dyck8b752f12010-01-27 17:10:57 +00004321CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00004322 E = E->IgnoreParens();
4323
4324 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00004325 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00004326 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004327 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4328 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00004329
Chris Lattneraf707ab2009-01-24 21:53:27 +00004330 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004331 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4332 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00004333
Chris Lattnere9feb472009-01-24 21:09:06 +00004334 return GetAlignOfType(E->getType());
4335}
4336
4337
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004338/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4339/// a result as the expression's type.
4340bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4341 const UnaryExprOrTypeTraitExpr *E) {
4342 switch(E->getKind()) {
4343 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00004344 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004345 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004346 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004347 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004348 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004349
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004350 case UETT_VecStep: {
4351 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00004352
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004353 if (Ty->isVectorType()) {
4354 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00004355
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004356 // The vec_step built-in functions that take a 3-component
4357 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4358 if (n == 3)
4359 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00004360
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004361 return Success(n, E);
4362 } else
4363 return Success(1, E);
4364 }
4365
4366 case UETT_SizeOf: {
4367 QualType SrcTy = E->getTypeOfArgument();
4368 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4369 // the result is the size of the referenced type."
4370 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4371 // result shall be the alignment of the referenced type."
4372 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4373 SrcTy = Ref->getPointeeType();
4374
Richard Smith180f4792011-11-10 06:34:14 +00004375 CharUnits Sizeof;
4376 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004377 return false;
Richard Smith180f4792011-11-10 06:34:14 +00004378 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004379 }
4380 }
4381
4382 llvm_unreachable("unknown expr/type trait");
Richard Smithf48fdb02011-12-09 22:58:01 +00004383 return Error(E);
Chris Lattnerfcee0012008-07-11 21:24:13 +00004384}
4385
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004386bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004387 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004388 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004389 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004390 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004391 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004392 for (unsigned i = 0; i != n; ++i) {
4393 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4394 switch (ON.getKind()) {
4395 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004396 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004397 APSInt IdxResult;
4398 if (!EvaluateInteger(Idx, IdxResult, Info))
4399 return false;
4400 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4401 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004402 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004403 CurrentType = AT->getElementType();
4404 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4405 Result += IdxResult.getSExtValue() * ElementSize;
4406 break;
4407 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004408
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004409 case OffsetOfExpr::OffsetOfNode::Field: {
4410 FieldDecl *MemberDecl = ON.getField();
4411 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004412 if (!RT)
4413 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004414 RecordDecl *RD = RT->getDecl();
4415 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00004416 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004417 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00004418 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004419 CurrentType = MemberDecl->getType().getNonReferenceType();
4420 break;
4421 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004422
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004423 case OffsetOfExpr::OffsetOfNode::Identifier:
4424 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00004425 return Error(OOE);
4426
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004427 case OffsetOfExpr::OffsetOfNode::Base: {
4428 CXXBaseSpecifier *BaseSpec = ON.getBase();
4429 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00004430 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004431
4432 // Find the layout of the class whose base we are looking into.
4433 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004434 if (!RT)
4435 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004436 RecordDecl *RD = RT->getDecl();
4437 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4438
4439 // Find the base class itself.
4440 CurrentType = BaseSpec->getType();
4441 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4442 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004443 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004444
4445 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00004446 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004447 break;
4448 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004449 }
4450 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004451 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004452}
4453
Chris Lattnerb542afe2008-07-11 19:10:17 +00004454bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004455 switch (E->getOpcode()) {
4456 default:
4457 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4458 // See C99 6.6p3.
4459 return Error(E);
4460 case UO_Extension:
4461 // FIXME: Should extension allow i-c-e extension expressions in its scope?
4462 // If so, we could clear the diagnostic ID.
4463 return Visit(E->getSubExpr());
4464 case UO_Plus:
4465 // The result is just the value.
4466 return Visit(E->getSubExpr());
4467 case UO_Minus: {
4468 if (!Visit(E->getSubExpr()))
4469 return false;
4470 if (!Result.isInt()) return Error(E);
4471 return Success(-Result.getInt(), E);
4472 }
4473 case UO_Not: {
4474 if (!Visit(E->getSubExpr()))
4475 return false;
4476 if (!Result.isInt()) return Error(E);
4477 return Success(~Result.getInt(), E);
4478 }
4479 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00004480 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00004481 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00004482 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004483 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004484 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004485 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004486}
Mike Stump1eb44332009-09-09 15:08:12 +00004487
Chris Lattner732b2232008-07-12 01:15:53 +00004488/// HandleCast - This is used to evaluate implicit or explicit casts where the
4489/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004490bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4491 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00004492 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00004493 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00004494
Eli Friedman46a52322011-03-25 00:43:55 +00004495 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00004496 case CK_BaseToDerived:
4497 case CK_DerivedToBase:
4498 case CK_UncheckedDerivedToBase:
4499 case CK_Dynamic:
4500 case CK_ToUnion:
4501 case CK_ArrayToPointerDecay:
4502 case CK_FunctionToPointerDecay:
4503 case CK_NullToPointer:
4504 case CK_NullToMemberPointer:
4505 case CK_BaseToDerivedMemberPointer:
4506 case CK_DerivedToBaseMemberPointer:
4507 case CK_ConstructorConversion:
4508 case CK_IntegralToPointer:
4509 case CK_ToVoid:
4510 case CK_VectorSplat:
4511 case CK_IntegralToFloating:
4512 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00004513 case CK_CPointerToObjCPointerCast:
4514 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004515 case CK_AnyPointerToBlockPointerCast:
4516 case CK_ObjCObjectLValueCast:
4517 case CK_FloatingRealToComplex:
4518 case CK_FloatingComplexToReal:
4519 case CK_FloatingComplexCast:
4520 case CK_FloatingComplexToIntegralComplex:
4521 case CK_IntegralRealToComplex:
4522 case CK_IntegralComplexCast:
4523 case CK_IntegralComplexToFloatingComplex:
4524 llvm_unreachable("invalid cast kind for integral value");
4525
Eli Friedmane50c2972011-03-25 19:07:11 +00004526 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004527 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00004528 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00004529 case CK_ARCProduceObject:
4530 case CK_ARCConsumeObject:
4531 case CK_ARCReclaimReturnedObject:
4532 case CK_ARCExtendBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00004533 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004534
Richard Smith7d580a42012-01-17 21:17:26 +00004535 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00004536 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00004537 case CK_AtomicToNonAtomic:
4538 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00004539 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00004540 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004541
4542 case CK_MemberPointerToBoolean:
4543 case CK_PointerToBoolean:
4544 case CK_IntegralToBoolean:
4545 case CK_FloatingToBoolean:
4546 case CK_FloatingComplexToBoolean:
4547 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004548 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00004549 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00004550 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004551 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004552 }
4553
Eli Friedman46a52322011-03-25 00:43:55 +00004554 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00004555 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004556 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00004557
Eli Friedmanbe265702009-02-20 01:15:07 +00004558 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00004559 // Allow casts of address-of-label differences if they are no-ops
4560 // or narrowing. (The narrowing case isn't actually guaranteed to
4561 // be constant-evaluatable except in some narrow cases which are hard
4562 // to detect here. We let it through on the assumption the user knows
4563 // what they are doing.)
4564 if (Result.isAddrLabelDiff())
4565 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00004566 // Only allow casts of lvalues if they are lossless.
4567 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
4568 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004569
Daniel Dunbardd211642009-02-19 22:24:01 +00004570 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004571 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00004572 }
Mike Stump1eb44332009-09-09 15:08:12 +00004573
Eli Friedman46a52322011-03-25 00:43:55 +00004574 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00004575 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4576
John McCallefdb83e2010-05-07 21:00:08 +00004577 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00004578 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004579 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00004580
Daniel Dunbardd211642009-02-19 22:24:01 +00004581 if (LV.getLValueBase()) {
4582 // Only allow based lvalue casts if they are lossless.
4583 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00004584 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004585
Richard Smithb755a9d2011-11-16 07:18:12 +00004586 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00004587 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00004588 return true;
4589 }
4590
Ken Dycka7305832010-01-15 12:37:54 +00004591 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
4592 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00004593 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00004594 }
Eli Friedman4efaa272008-11-12 09:44:48 +00004595
Eli Friedman46a52322011-03-25 00:43:55 +00004596 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00004597 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00004598 if (!EvaluateComplex(SubExpr, C, Info))
4599 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00004600 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00004601 }
Eli Friedman2217c872009-02-22 11:46:18 +00004602
Eli Friedman46a52322011-03-25 00:43:55 +00004603 case CK_FloatingToIntegral: {
4604 APFloat F(0.0);
4605 if (!EvaluateFloat(SubExpr, F, Info))
4606 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00004607
Richard Smithc1c5f272011-12-13 06:39:58 +00004608 APSInt Value;
4609 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
4610 return false;
4611 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00004612 }
4613 }
Mike Stump1eb44332009-09-09 15:08:12 +00004614
Eli Friedman46a52322011-03-25 00:43:55 +00004615 llvm_unreachable("unknown cast resulting in integral value");
Richard Smithf48fdb02011-12-09 22:58:01 +00004616 return Error(E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004617}
Anders Carlsson2bad1682008-07-08 14:30:00 +00004618
Eli Friedman722c7172009-02-28 03:59:05 +00004619bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4620 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004621 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004622 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4623 return false;
4624 if (!LV.isComplexInt())
4625 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004626 return Success(LV.getComplexIntReal(), E);
4627 }
4628
4629 return Visit(E->getSubExpr());
4630}
4631
Eli Friedman664a1042009-02-27 04:45:43 +00004632bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00004633 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004634 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004635 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4636 return false;
4637 if (!LV.isComplexInt())
4638 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004639 return Success(LV.getComplexIntImag(), E);
4640 }
4641
Richard Smith8327fad2011-10-24 18:44:57 +00004642 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00004643 return Success(0, E);
4644}
4645
Douglas Gregoree8aff02011-01-04 17:33:58 +00004646bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4647 return Success(E->getPackLength(), E);
4648}
4649
Sebastian Redl295995c2010-09-10 20:55:47 +00004650bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4651 return Success(E->getValue(), E);
4652}
4653
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004654//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004655// Float Evaluation
4656//===----------------------------------------------------------------------===//
4657
4658namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004659class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004660 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004661 APFloat &Result;
4662public:
4663 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004664 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004665
Richard Smith47a1eed2011-10-29 20:57:55 +00004666 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004667 Result = V.getFloat();
4668 return true;
4669 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004670
Richard Smith51201882011-12-30 21:15:51 +00004671 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00004672 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4673 return true;
4674 }
4675
Chris Lattner019f4e82008-10-06 05:28:25 +00004676 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004677
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004678 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004679 bool VisitBinaryOperator(const BinaryOperator *E);
4680 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004681 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00004682
John McCallabd3a852010-05-07 22:08:54 +00004683 bool VisitUnaryReal(const UnaryOperator *E);
4684 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00004685
Richard Smith51201882011-12-30 21:15:51 +00004686 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004687};
4688} // end anonymous namespace
4689
4690static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004691 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004692 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004693}
4694
Jay Foad4ba2a172011-01-12 09:06:06 +00004695static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00004696 QualType ResultTy,
4697 const Expr *Arg,
4698 bool SNaN,
4699 llvm::APFloat &Result) {
4700 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4701 if (!S) return false;
4702
4703 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4704
4705 llvm::APInt fill;
4706
4707 // Treat empty strings as if they were zero.
4708 if (S->getString().empty())
4709 fill = llvm::APInt(32, 0);
4710 else if (S->getString().getAsInteger(0, fill))
4711 return false;
4712
4713 if (SNaN)
4714 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
4715 else
4716 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
4717 return true;
4718}
4719
Chris Lattner019f4e82008-10-06 05:28:25 +00004720bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004721 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004722 default:
4723 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4724
Chris Lattner019f4e82008-10-06 05:28:25 +00004725 case Builtin::BI__builtin_huge_val:
4726 case Builtin::BI__builtin_huge_valf:
4727 case Builtin::BI__builtin_huge_vall:
4728 case Builtin::BI__builtin_inf:
4729 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004730 case Builtin::BI__builtin_infl: {
4731 const llvm::fltSemantics &Sem =
4732 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00004733 Result = llvm::APFloat::getInf(Sem);
4734 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004735 }
Mike Stump1eb44332009-09-09 15:08:12 +00004736
John McCalldb7b72a2010-02-28 13:00:19 +00004737 case Builtin::BI__builtin_nans:
4738 case Builtin::BI__builtin_nansf:
4739 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00004740 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4741 true, Result))
4742 return Error(E);
4743 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00004744
Chris Lattner9e621712008-10-06 06:31:58 +00004745 case Builtin::BI__builtin_nan:
4746 case Builtin::BI__builtin_nanf:
4747 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00004748 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00004749 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00004750 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4751 false, Result))
4752 return Error(E);
4753 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004754
4755 case Builtin::BI__builtin_fabs:
4756 case Builtin::BI__builtin_fabsf:
4757 case Builtin::BI__builtin_fabsl:
4758 if (!EvaluateFloat(E->getArg(0), Result, Info))
4759 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004760
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004761 if (Result.isNegative())
4762 Result.changeSign();
4763 return true;
4764
Mike Stump1eb44332009-09-09 15:08:12 +00004765 case Builtin::BI__builtin_copysign:
4766 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004767 case Builtin::BI__builtin_copysignl: {
4768 APFloat RHS(0.);
4769 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4770 !EvaluateFloat(E->getArg(1), RHS, Info))
4771 return false;
4772 Result.copySign(RHS);
4773 return true;
4774 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004775 }
4776}
4777
John McCallabd3a852010-05-07 22:08:54 +00004778bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00004779 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4780 ComplexValue CV;
4781 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4782 return false;
4783 Result = CV.FloatReal;
4784 return true;
4785 }
4786
4787 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00004788}
4789
4790bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00004791 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4792 ComplexValue CV;
4793 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4794 return false;
4795 Result = CV.FloatImag;
4796 return true;
4797 }
4798
Richard Smith8327fad2011-10-24 18:44:57 +00004799 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00004800 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4801 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00004802 return true;
4803}
4804
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004805bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004806 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004807 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004808 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00004809 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00004810 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00004811 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
4812 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004813 Result.changeSign();
4814 return true;
4815 }
4816}
Chris Lattner019f4e82008-10-06 05:28:25 +00004817
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004818bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004819 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
4820 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00004821
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004822 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004823 if (!EvaluateFloat(E->getLHS(), Result, Info))
4824 return false;
4825 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4826 return false;
4827
4828 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004829 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004830 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004831 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
4832 return true;
John McCall2de56d12010-08-25 11:45:40 +00004833 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004834 Result.add(RHS, APFloat::rmNearestTiesToEven);
4835 return true;
John McCall2de56d12010-08-25 11:45:40 +00004836 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004837 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
4838 return true;
John McCall2de56d12010-08-25 11:45:40 +00004839 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004840 Result.divide(RHS, APFloat::rmNearestTiesToEven);
4841 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004842 }
4843}
4844
4845bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
4846 Result = E->getValue();
4847 return true;
4848}
4849
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004850bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4851 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00004852
Eli Friedman2a523ee2011-03-25 00:54:52 +00004853 switch (E->getCastKind()) {
4854 default:
Richard Smithc49bd112011-10-28 17:51:58 +00004855 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00004856
4857 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004858 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00004859 return EvaluateInteger(SubExpr, IntResult, Info) &&
4860 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
4861 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00004862 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00004863
4864 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004865 if (!Visit(SubExpr))
4866 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00004867 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
4868 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00004869 }
John McCallf3ea8cf2010-11-14 08:17:51 +00004870
Eli Friedman2a523ee2011-03-25 00:54:52 +00004871 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00004872 ComplexValue V;
4873 if (!EvaluateComplex(SubExpr, V, Info))
4874 return false;
4875 Result = V.getComplexFloatReal();
4876 return true;
4877 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00004878 }
Eli Friedman4efaa272008-11-12 09:44:48 +00004879
Richard Smithf48fdb02011-12-09 22:58:01 +00004880 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004881}
4882
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004883//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004884// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004885//===----------------------------------------------------------------------===//
4886
4887namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004888class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004889 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00004890 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00004891
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004892public:
John McCallf4cf1a12010-05-07 17:22:02 +00004893 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004894 : ExprEvaluatorBaseTy(info), Result(Result) {}
4895
Richard Smith47a1eed2011-10-29 20:57:55 +00004896 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004897 Result.setFrom(V);
4898 return true;
4899 }
Mike Stump1eb44332009-09-09 15:08:12 +00004900
Eli Friedman7ead5c72012-01-10 04:58:17 +00004901 bool ZeroInitialization(const Expr *E);
4902
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004903 //===--------------------------------------------------------------------===//
4904 // Visitor Methods
4905 //===--------------------------------------------------------------------===//
4906
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004907 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004908 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00004909 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004910 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00004911 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004912};
4913} // end anonymous namespace
4914
John McCallf4cf1a12010-05-07 17:22:02 +00004915static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
4916 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004917 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004918 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004919}
4920
Eli Friedman7ead5c72012-01-10 04:58:17 +00004921bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00004922 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00004923 if (ElemTy->isRealFloatingType()) {
4924 Result.makeComplexFloat();
4925 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
4926 Result.FloatReal = Zero;
4927 Result.FloatImag = Zero;
4928 } else {
4929 Result.makeComplexInt();
4930 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
4931 Result.IntReal = Zero;
4932 Result.IntImag = Zero;
4933 }
4934 return true;
4935}
4936
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004937bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
4938 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004939
4940 if (SubExpr->getType()->isRealFloatingType()) {
4941 Result.makeComplexFloat();
4942 APFloat &Imag = Result.FloatImag;
4943 if (!EvaluateFloat(SubExpr, Imag, Info))
4944 return false;
4945
4946 Result.FloatReal = APFloat(Imag.getSemantics());
4947 return true;
4948 } else {
4949 assert(SubExpr->getType()->isIntegerType() &&
4950 "Unexpected imaginary literal.");
4951
4952 Result.makeComplexInt();
4953 APSInt &Imag = Result.IntImag;
4954 if (!EvaluateInteger(SubExpr, Imag, Info))
4955 return false;
4956
4957 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
4958 return true;
4959 }
4960}
4961
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004962bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004963
John McCall8786da72010-12-14 17:51:41 +00004964 switch (E->getCastKind()) {
4965 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00004966 case CK_BaseToDerived:
4967 case CK_DerivedToBase:
4968 case CK_UncheckedDerivedToBase:
4969 case CK_Dynamic:
4970 case CK_ToUnion:
4971 case CK_ArrayToPointerDecay:
4972 case CK_FunctionToPointerDecay:
4973 case CK_NullToPointer:
4974 case CK_NullToMemberPointer:
4975 case CK_BaseToDerivedMemberPointer:
4976 case CK_DerivedToBaseMemberPointer:
4977 case CK_MemberPointerToBoolean:
4978 case CK_ConstructorConversion:
4979 case CK_IntegralToPointer:
4980 case CK_PointerToIntegral:
4981 case CK_PointerToBoolean:
4982 case CK_ToVoid:
4983 case CK_VectorSplat:
4984 case CK_IntegralCast:
4985 case CK_IntegralToBoolean:
4986 case CK_IntegralToFloating:
4987 case CK_FloatingToIntegral:
4988 case CK_FloatingToBoolean:
4989 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00004990 case CK_CPointerToObjCPointerCast:
4991 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00004992 case CK_AnyPointerToBlockPointerCast:
4993 case CK_ObjCObjectLValueCast:
4994 case CK_FloatingComplexToReal:
4995 case CK_FloatingComplexToBoolean:
4996 case CK_IntegralComplexToReal:
4997 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00004998 case CK_ARCProduceObject:
4999 case CK_ARCConsumeObject:
5000 case CK_ARCReclaimReturnedObject:
5001 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005002 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005003
John McCall8786da72010-12-14 17:51:41 +00005004 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005005 case CK_AtomicToNonAtomic:
5006 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005007 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005008 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005009
5010 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005011 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005012 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005013 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005014
5015 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005016 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005017 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005018 return false;
5019
John McCall8786da72010-12-14 17:51:41 +00005020 Result.makeComplexFloat();
5021 Result.FloatImag = APFloat(Real.getSemantics());
5022 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005023 }
5024
John McCall8786da72010-12-14 17:51:41 +00005025 case CK_FloatingComplexCast: {
5026 if (!Visit(E->getSubExpr()))
5027 return false;
5028
5029 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5030 QualType From
5031 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5032
Richard Smithc1c5f272011-12-13 06:39:58 +00005033 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5034 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005035 }
5036
5037 case CK_FloatingComplexToIntegralComplex: {
5038 if (!Visit(E->getSubExpr()))
5039 return false;
5040
5041 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5042 QualType From
5043 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5044 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005045 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5046 To, Result.IntReal) &&
5047 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5048 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005049 }
5050
5051 case CK_IntegralRealToComplex: {
5052 APSInt &Real = Result.IntReal;
5053 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5054 return false;
5055
5056 Result.makeComplexInt();
5057 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5058 return true;
5059 }
5060
5061 case CK_IntegralComplexCast: {
5062 if (!Visit(E->getSubExpr()))
5063 return false;
5064
5065 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5066 QualType From
5067 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5068
5069 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
5070 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
5071 return true;
5072 }
5073
5074 case CK_IntegralComplexToFloatingComplex: {
5075 if (!Visit(E->getSubExpr()))
5076 return false;
5077
5078 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5079 QualType From
5080 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5081 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005082 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5083 To, Result.FloatReal) &&
5084 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5085 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005086 }
5087 }
5088
5089 llvm_unreachable("unknown cast resulting in complex value");
Richard Smithf48fdb02011-12-09 22:58:01 +00005090 return Error(E);
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005091}
5092
John McCallf4cf1a12010-05-07 17:22:02 +00005093bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005094 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005095 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5096
John McCallf4cf1a12010-05-07 17:22:02 +00005097 if (!Visit(E->getLHS()))
5098 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005099
John McCallf4cf1a12010-05-07 17:22:02 +00005100 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005101 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00005102 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005103
Daniel Dunbar3f279872009-01-29 01:32:56 +00005104 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5105 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005106 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005107 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005108 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005109 if (Result.isComplexFloat()) {
5110 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5111 APFloat::rmNearestTiesToEven);
5112 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5113 APFloat::rmNearestTiesToEven);
5114 } else {
5115 Result.getComplexIntReal() += RHS.getComplexIntReal();
5116 Result.getComplexIntImag() += RHS.getComplexIntImag();
5117 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005118 break;
John McCall2de56d12010-08-25 11:45:40 +00005119 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005120 if (Result.isComplexFloat()) {
5121 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5122 APFloat::rmNearestTiesToEven);
5123 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5124 APFloat::rmNearestTiesToEven);
5125 } else {
5126 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5127 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5128 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005129 break;
John McCall2de56d12010-08-25 11:45:40 +00005130 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005131 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005132 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005133 APFloat &LHS_r = LHS.getComplexFloatReal();
5134 APFloat &LHS_i = LHS.getComplexFloatImag();
5135 APFloat &RHS_r = RHS.getComplexFloatReal();
5136 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005137
Daniel Dunbar3f279872009-01-29 01:32:56 +00005138 APFloat Tmp = LHS_r;
5139 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5140 Result.getComplexFloatReal() = Tmp;
5141 Tmp = LHS_i;
5142 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5143 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5144
5145 Tmp = LHS_r;
5146 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5147 Result.getComplexFloatImag() = Tmp;
5148 Tmp = LHS_i;
5149 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5150 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5151 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005152 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005153 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005154 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5155 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00005156 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005157 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5158 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5159 }
5160 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005161 case BO_Div:
5162 if (Result.isComplexFloat()) {
5163 ComplexValue LHS = Result;
5164 APFloat &LHS_r = LHS.getComplexFloatReal();
5165 APFloat &LHS_i = LHS.getComplexFloatImag();
5166 APFloat &RHS_r = RHS.getComplexFloatReal();
5167 APFloat &RHS_i = RHS.getComplexFloatImag();
5168 APFloat &Res_r = Result.getComplexFloatReal();
5169 APFloat &Res_i = Result.getComplexFloatImag();
5170
5171 APFloat Den = RHS_r;
5172 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5173 APFloat Tmp = RHS_i;
5174 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5175 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5176
5177 Res_r = LHS_r;
5178 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5179 Tmp = LHS_i;
5180 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5181 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5182 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5183
5184 Res_i = LHS_i;
5185 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5186 Tmp = LHS_r;
5187 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5188 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5189 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5190 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00005191 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5192 return Error(E, diag::note_expr_divide_by_zero);
5193
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005194 ComplexValue LHS = Result;
5195 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5196 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5197 Result.getComplexIntReal() =
5198 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5199 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5200 Result.getComplexIntImag() =
5201 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5202 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5203 }
5204 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005205 }
5206
John McCallf4cf1a12010-05-07 17:22:02 +00005207 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005208}
5209
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005210bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5211 // Get the operand value into 'Result'.
5212 if (!Visit(E->getSubExpr()))
5213 return false;
5214
5215 switch (E->getOpcode()) {
5216 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00005217 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005218 case UO_Extension:
5219 return true;
5220 case UO_Plus:
5221 // The result is always just the subexpr.
5222 return true;
5223 case UO_Minus:
5224 if (Result.isComplexFloat()) {
5225 Result.getComplexFloatReal().changeSign();
5226 Result.getComplexFloatImag().changeSign();
5227 }
5228 else {
5229 Result.getComplexIntReal() = -Result.getComplexIntReal();
5230 Result.getComplexIntImag() = -Result.getComplexIntImag();
5231 }
5232 return true;
5233 case UO_Not:
5234 if (Result.isComplexFloat())
5235 Result.getComplexFloatImag().changeSign();
5236 else
5237 Result.getComplexIntImag() = -Result.getComplexIntImag();
5238 return true;
5239 }
5240}
5241
Eli Friedman7ead5c72012-01-10 04:58:17 +00005242bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5243 if (E->getNumInits() == 2) {
5244 if (E->getType()->isComplexType()) {
5245 Result.makeComplexFloat();
5246 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5247 return false;
5248 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5249 return false;
5250 } else {
5251 Result.makeComplexInt();
5252 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5253 return false;
5254 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5255 return false;
5256 }
5257 return true;
5258 }
5259 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5260}
5261
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005262//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00005263// Void expression evaluation, primarily for a cast to void on the LHS of a
5264// comma operator
5265//===----------------------------------------------------------------------===//
5266
5267namespace {
5268class VoidExprEvaluator
5269 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5270public:
5271 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5272
5273 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00005274
5275 bool VisitCastExpr(const CastExpr *E) {
5276 switch (E->getCastKind()) {
5277 default:
5278 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5279 case CK_ToVoid:
5280 VisitIgnoredValue(E->getSubExpr());
5281 return true;
5282 }
5283 }
5284};
5285} // end anonymous namespace
5286
5287static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5288 assert(E->isRValue() && E->getType()->isVoidType());
5289 return VoidExprEvaluator(Info).Visit(E);
5290}
5291
5292//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00005293// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005294//===----------------------------------------------------------------------===//
5295
Richard Smith47a1eed2011-10-29 20:57:55 +00005296static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00005297 // In C, function designators are not lvalues, but we evaluate them as if they
5298 // are.
5299 if (E->isGLValue() || E->getType()->isFunctionType()) {
5300 LValue LV;
5301 if (!EvaluateLValue(E, LV, Info))
5302 return false;
5303 LV.moveInto(Result);
5304 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005305 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00005306 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00005307 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005308 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005309 return false;
John McCallefdb83e2010-05-07 21:00:08 +00005310 } else if (E->getType()->hasPointerRepresentation()) {
5311 LValue LV;
5312 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005313 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005314 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00005315 } else if (E->getType()->isRealFloatingType()) {
5316 llvm::APFloat F(0.0);
5317 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005318 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00005319 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00005320 } else if (E->getType()->isAnyComplexType()) {
5321 ComplexValue C;
5322 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005323 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005324 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00005325 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005326 MemberPtr P;
5327 if (!EvaluateMemberPointer(E, P, Info))
5328 return false;
5329 P.moveInto(Result);
5330 return true;
Richard Smith51201882011-12-30 21:15:51 +00005331 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005332 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005333 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005334 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00005335 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005336 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00005337 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005338 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005339 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005340 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5341 return false;
5342 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00005343 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00005344 if (Info.getLangOpts().CPlusPlus0x)
5345 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5346 << E->getType();
5347 else
5348 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00005349 if (!EvaluateVoid(E, Info))
5350 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005351 } else if (Info.getLangOpts().CPlusPlus0x) {
5352 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5353 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005354 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00005355 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00005356 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005357 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005358
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00005359 return true;
5360}
5361
Richard Smith69c2c502011-11-04 05:33:44 +00005362/// EvaluateConstantExpression - Evaluate an expression as a constant expression
5363/// in-place in an APValue. In some cases, the in-place evaluation is essential,
5364/// since later initializers for an object can indirectly refer to subobjects
5365/// which were initialized earlier.
5366static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +00005367 const LValue &This, const Expr *E,
5368 CheckConstantExpressionKind CCEK) {
Richard Smith51201882011-12-30 21:15:51 +00005369 if (!CheckLiteralType(Info, E))
5370 return false;
5371
5372 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00005373 // Evaluate arrays and record types in-place, so that later initializers can
5374 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00005375 if (E->getType()->isArrayType())
5376 return EvaluateArray(E, This, Result, Info);
5377 else if (E->getType()->isRecordType())
5378 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00005379 }
5380
5381 // For any other type, in-place evaluation is unimportant.
5382 CCValue CoreConstResult;
5383 return Evaluate(CoreConstResult, Info, E) &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005384 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smith69c2c502011-11-04 05:33:44 +00005385}
5386
Richard Smithf48fdb02011-12-09 22:58:01 +00005387/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5388/// lvalue-to-rvalue cast if it is an lvalue.
5389static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00005390 if (!CheckLiteralType(Info, E))
5391 return false;
5392
Richard Smithf48fdb02011-12-09 22:58:01 +00005393 CCValue Value;
5394 if (!::Evaluate(Value, Info, E))
5395 return false;
5396
5397 if (E->isGLValue()) {
5398 LValue LV;
5399 LV.setFrom(Value);
5400 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
5401 return false;
5402 }
5403
5404 // Check this core constant expression is a constant expression, and if so,
5405 // convert it to one.
5406 return CheckConstantExpression(Info, E, Value, Result);
5407}
Richard Smithc49bd112011-10-28 17:51:58 +00005408
Richard Smith51f47082011-10-29 00:50:52 +00005409/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00005410/// any crazy technique (that has nothing to do with language standards) that
5411/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00005412/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
5413/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00005414bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00005415 // Fast-path evaluations of integer literals, since we sometimes see files
5416 // containing vast quantities of these.
5417 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
5418 Result.Val = APValue(APSInt(L->getValue(),
5419 L->getType()->isUnsignedIntegerType()));
5420 return true;
5421 }
5422
Richard Smith2d6a5672012-01-14 04:30:29 +00005423 // FIXME: Evaluating values of large array and record types can cause
5424 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00005425 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5426 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00005427 return false;
5428
Richard Smithf48fdb02011-12-09 22:58:01 +00005429 EvalInfo Info(Ctx, Result);
5430 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00005431}
5432
Jay Foad4ba2a172011-01-12 09:06:06 +00005433bool Expr::EvaluateAsBooleanCondition(bool &Result,
5434 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00005435 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00005436 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithb4e85ed2012-01-06 16:39:00 +00005437 HandleConversionToBool(CCValue(const_cast<ASTContext&>(Ctx),
5438 Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00005439 Result);
John McCallcd7a4452010-01-05 23:42:56 +00005440}
5441
Richard Smith80d4b552011-12-28 19:48:30 +00005442bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
5443 SideEffectsKind AllowSideEffects) const {
5444 if (!getType()->isIntegralOrEnumerationType())
5445 return false;
5446
Richard Smithc49bd112011-10-28 17:51:58 +00005447 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00005448 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
5449 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00005450 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005451
Richard Smithc49bd112011-10-28 17:51:58 +00005452 Result = ExprResult.Val.getInt();
5453 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005454}
5455
Jay Foad4ba2a172011-01-12 09:06:06 +00005456bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00005457 EvalInfo Info(Ctx, Result);
5458
John McCallefdb83e2010-05-07 21:00:08 +00005459 LValue LV;
Richard Smith9a17a682011-11-07 05:07:52 +00005460 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005461 CheckLValueConstantExpression(Info, this, LV, Result.Val,
5462 CCEK_Constant);
Eli Friedmanb2f295c2009-09-13 10:17:44 +00005463}
5464
Richard Smith099e7f62011-12-19 06:19:21 +00005465bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
5466 const VarDecl *VD,
5467 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00005468 // FIXME: Evaluating initializers for large array and record types can cause
5469 // performance problems. Only do so in C++11 for now.
5470 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5471 !Ctx.getLangOptions().CPlusPlus0x)
5472 return false;
5473
Richard Smith099e7f62011-12-19 06:19:21 +00005474 Expr::EvalStatus EStatus;
5475 EStatus.Diag = &Notes;
5476
5477 EvalInfo InitInfo(Ctx, EStatus);
5478 InitInfo.setEvaluatingDecl(VD, Value);
5479
Richard Smith51201882011-12-30 21:15:51 +00005480 if (!CheckLiteralType(InitInfo, this))
5481 return false;
5482
Richard Smith099e7f62011-12-19 06:19:21 +00005483 LValue LVal;
5484 LVal.set(VD);
5485
Richard Smith51201882011-12-30 21:15:51 +00005486 // C++11 [basic.start.init]p2:
5487 // Variables with static storage duration or thread storage duration shall be
5488 // zero-initialized before any other initialization takes place.
5489 // This behavior is not present in C.
5490 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
5491 !VD->getType()->isReferenceType()) {
5492 ImplicitValueInitExpr VIE(VD->getType());
5493 if (!EvaluateConstantExpression(Value, InitInfo, LVal, &VIE))
5494 return false;
5495 }
5496
Richard Smith099e7f62011-12-19 06:19:21 +00005497 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
5498 !EStatus.HasSideEffects;
5499}
5500
Richard Smith51f47082011-10-29 00:50:52 +00005501/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
5502/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00005503bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00005504 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00005505 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00005506}
Anders Carlsson51fe9962008-11-22 21:04:56 +00005507
Jay Foad4ba2a172011-01-12 09:06:06 +00005508bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00005509 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00005510}
5511
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005512APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005513 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00005514 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00005515 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00005516 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005517 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00005518
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005519 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00005520}
John McCalld905f5a2010-05-07 05:32:02 +00005521
Abramo Bagnarae17a6432010-05-14 17:07:14 +00005522 bool Expr::EvalResult::isGlobalLValue() const {
5523 assert(Val.isLValue());
5524 return IsGlobalLValue(Val.getLValueBase());
5525 }
5526
5527
John McCalld905f5a2010-05-07 05:32:02 +00005528/// isIntegerConstantExpr - this recursive routine will test if an expression is
5529/// an integer constant expression.
5530
5531/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
5532/// comma, etc
5533///
5534/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
5535/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
5536/// cast+dereference.
5537
5538// CheckICE - This function does the fundamental ICE checking: the returned
5539// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
5540// Note that to reduce code duplication, this helper does no evaluation
5541// itself; the caller checks whether the expression is evaluatable, and
5542// in the rare cases where CheckICE actually cares about the evaluated
5543// value, it calls into Evalute.
5544//
5545// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00005546// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00005547// 1: This expression is not an ICE, but if it isn't evaluated, it's
5548// a legal subexpression for an ICE. This return value is used to handle
5549// the comma operator in C99 mode.
5550// 2: This expression is not an ICE, and is not a legal subexpression for one.
5551
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005552namespace {
5553
John McCalld905f5a2010-05-07 05:32:02 +00005554struct ICEDiag {
5555 unsigned Val;
5556 SourceLocation Loc;
5557
5558 public:
5559 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
5560 ICEDiag() : Val(0) {}
5561};
5562
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005563}
5564
5565static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00005566
5567static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
5568 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00005569 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00005570 !EVResult.Val.isInt()) {
5571 return ICEDiag(2, E->getLocStart());
5572 }
5573 return NoDiag();
5574}
5575
5576static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
5577 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00005578 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00005579 return ICEDiag(2, E->getLocStart());
5580 }
5581
5582 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00005583#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00005584#define STMT(Node, Base) case Expr::Node##Class:
5585#define EXPR(Node, Base)
5586#include "clang/AST/StmtNodes.inc"
5587 case Expr::PredefinedExprClass:
5588 case Expr::FloatingLiteralClass:
5589 case Expr::ImaginaryLiteralClass:
5590 case Expr::StringLiteralClass:
5591 case Expr::ArraySubscriptExprClass:
5592 case Expr::MemberExprClass:
5593 case Expr::CompoundAssignOperatorClass:
5594 case Expr::CompoundLiteralExprClass:
5595 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005596 case Expr::DesignatedInitExprClass:
5597 case Expr::ImplicitValueInitExprClass:
5598 case Expr::ParenListExprClass:
5599 case Expr::VAArgExprClass:
5600 case Expr::AddrLabelExprClass:
5601 case Expr::StmtExprClass:
5602 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00005603 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005604 case Expr::CXXDynamicCastExprClass:
5605 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00005606 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005607 case Expr::CXXNullPtrLiteralExprClass:
5608 case Expr::CXXThisExprClass:
5609 case Expr::CXXThrowExprClass:
5610 case Expr::CXXNewExprClass:
5611 case Expr::CXXDeleteExprClass:
5612 case Expr::CXXPseudoDestructorExprClass:
5613 case Expr::UnresolvedLookupExprClass:
5614 case Expr::DependentScopeDeclRefExprClass:
5615 case Expr::CXXConstructExprClass:
5616 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00005617 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00005618 case Expr::CXXTemporaryObjectExprClass:
5619 case Expr::CXXUnresolvedConstructExprClass:
5620 case Expr::CXXDependentScopeMemberExprClass:
5621 case Expr::UnresolvedMemberExprClass:
5622 case Expr::ObjCStringLiteralClass:
5623 case Expr::ObjCEncodeExprClass:
5624 case Expr::ObjCMessageExprClass:
5625 case Expr::ObjCSelectorExprClass:
5626 case Expr::ObjCProtocolExprClass:
5627 case Expr::ObjCIvarRefExprClass:
5628 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005629 case Expr::ObjCIsaExprClass:
5630 case Expr::ShuffleVectorExprClass:
5631 case Expr::BlockExprClass:
5632 case Expr::BlockDeclRefExprClass:
5633 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00005634 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00005635 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00005636 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00005637 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005638 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00005639 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00005640 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00005641 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005642 case Expr::InitListExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005643 return ICEDiag(2, E->getLocStart());
5644
Douglas Gregoree8aff02011-01-04 17:33:58 +00005645 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005646 case Expr::GNUNullExprClass:
5647 // GCC considers the GNU __null value to be an integral constant expression.
5648 return NoDiag();
5649
John McCall91a57552011-07-15 05:09:51 +00005650 case Expr::SubstNonTypeTemplateParmExprClass:
5651 return
5652 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
5653
John McCalld905f5a2010-05-07 05:32:02 +00005654 case Expr::ParenExprClass:
5655 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00005656 case Expr::GenericSelectionExprClass:
5657 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005658 case Expr::IntegerLiteralClass:
5659 case Expr::CharacterLiteralClass:
5660 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00005661 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005662 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00005663 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00005664 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00005665 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00005666 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005667 return NoDiag();
5668 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00005669 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00005670 // C99 6.6/3 allows function calls within unevaluated subexpressions of
5671 // constant expressions, but they can never be ICEs because an ICE cannot
5672 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00005673 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00005674 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00005675 return CheckEvalInICE(E, Ctx);
5676 return ICEDiag(2, E->getLocStart());
5677 }
5678 case Expr::DeclRefExprClass:
5679 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
5680 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00005681 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00005682 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
5683
5684 // Parameter variables are never constants. Without this check,
5685 // getAnyInitializer() can find a default argument, which leads
5686 // to chaos.
5687 if (isa<ParmVarDecl>(D))
5688 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5689
5690 // C++ 7.1.5.1p2
5691 // A variable of non-volatile const-qualified integral or enumeration
5692 // type initialized by an ICE can be used in ICEs.
5693 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00005694 if (!Dcl->getType()->isIntegralOrEnumerationType())
5695 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5696
Richard Smith099e7f62011-12-19 06:19:21 +00005697 const VarDecl *VD;
5698 // Look for a declaration of this variable that has an initializer, and
5699 // check whether it is an ICE.
5700 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
5701 return NoDiag();
5702 else
5703 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00005704 }
5705 }
5706 return ICEDiag(2, E->getLocStart());
5707 case Expr::UnaryOperatorClass: {
5708 const UnaryOperator *Exp = cast<UnaryOperator>(E);
5709 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005710 case UO_PostInc:
5711 case UO_PostDec:
5712 case UO_PreInc:
5713 case UO_PreDec:
5714 case UO_AddrOf:
5715 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00005716 // C99 6.6/3 allows increment and decrement within unevaluated
5717 // subexpressions of constant expressions, but they can never be ICEs
5718 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00005719 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00005720 case UO_Extension:
5721 case UO_LNot:
5722 case UO_Plus:
5723 case UO_Minus:
5724 case UO_Not:
5725 case UO_Real:
5726 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00005727 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005728 }
5729
5730 // OffsetOf falls through here.
5731 }
5732 case Expr::OffsetOfExprClass: {
5733 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00005734 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00005735 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00005736 // compliance: we should warn earlier for offsetof expressions with
5737 // array subscripts that aren't ICEs, and if the array subscripts
5738 // are ICEs, the value of the offsetof must be an integer constant.
5739 return CheckEvalInICE(E, Ctx);
5740 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005741 case Expr::UnaryExprOrTypeTraitExprClass: {
5742 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
5743 if ((Exp->getKind() == UETT_SizeOf) &&
5744 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00005745 return ICEDiag(2, E->getLocStart());
5746 return NoDiag();
5747 }
5748 case Expr::BinaryOperatorClass: {
5749 const BinaryOperator *Exp = cast<BinaryOperator>(E);
5750 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005751 case BO_PtrMemD:
5752 case BO_PtrMemI:
5753 case BO_Assign:
5754 case BO_MulAssign:
5755 case BO_DivAssign:
5756 case BO_RemAssign:
5757 case BO_AddAssign:
5758 case BO_SubAssign:
5759 case BO_ShlAssign:
5760 case BO_ShrAssign:
5761 case BO_AndAssign:
5762 case BO_XorAssign:
5763 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00005764 // C99 6.6/3 allows assignments within unevaluated subexpressions of
5765 // constant expressions, but they can never be ICEs because an ICE cannot
5766 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00005767 return ICEDiag(2, E->getLocStart());
5768
John McCall2de56d12010-08-25 11:45:40 +00005769 case BO_Mul:
5770 case BO_Div:
5771 case BO_Rem:
5772 case BO_Add:
5773 case BO_Sub:
5774 case BO_Shl:
5775 case BO_Shr:
5776 case BO_LT:
5777 case BO_GT:
5778 case BO_LE:
5779 case BO_GE:
5780 case BO_EQ:
5781 case BO_NE:
5782 case BO_And:
5783 case BO_Xor:
5784 case BO_Or:
5785 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00005786 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5787 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00005788 if (Exp->getOpcode() == BO_Div ||
5789 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00005790 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00005791 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00005792 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005793 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005794 if (REval == 0)
5795 return ICEDiag(1, E->getLocStart());
5796 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005797 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005798 if (LEval.isMinSignedValue())
5799 return ICEDiag(1, E->getLocStart());
5800 }
5801 }
5802 }
John McCall2de56d12010-08-25 11:45:40 +00005803 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00005804 if (Ctx.getLangOptions().C99) {
5805 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
5806 // if it isn't evaluated.
5807 if (LHSResult.Val == 0 && RHSResult.Val == 0)
5808 return ICEDiag(1, E->getLocStart());
5809 } else {
5810 // In both C89 and C++, commas in ICEs are illegal.
5811 return ICEDiag(2, E->getLocStart());
5812 }
5813 }
5814 if (LHSResult.Val >= RHSResult.Val)
5815 return LHSResult;
5816 return RHSResult;
5817 }
John McCall2de56d12010-08-25 11:45:40 +00005818 case BO_LAnd:
5819 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00005820 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5821 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
5822 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
5823 // Rare case where the RHS has a comma "side-effect"; we need
5824 // to actually check the condition to see whether the side
5825 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00005826 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005827 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00005828 return RHSResult;
5829 return NoDiag();
5830 }
5831
5832 if (LHSResult.Val >= RHSResult.Val)
5833 return LHSResult;
5834 return RHSResult;
5835 }
5836 }
5837 }
5838 case Expr::ImplicitCastExprClass:
5839 case Expr::CStyleCastExprClass:
5840 case Expr::CXXFunctionalCastExprClass:
5841 case Expr::CXXStaticCastExprClass:
5842 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00005843 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005844 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00005845 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00005846 if (isa<ExplicitCastExpr>(E)) {
5847 if (const FloatingLiteral *FL
5848 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
5849 unsigned DestWidth = Ctx.getIntWidth(E->getType());
5850 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
5851 APSInt IgnoredVal(DestWidth, !DestSigned);
5852 bool Ignored;
5853 // If the value does not fit in the destination type, the behavior is
5854 // undefined, so we are not required to treat it as a constant
5855 // expression.
5856 if (FL->getValue().convertToInteger(IgnoredVal,
5857 llvm::APFloat::rmTowardZero,
5858 &Ignored) & APFloat::opInvalidOp)
5859 return ICEDiag(2, E->getLocStart());
5860 return NoDiag();
5861 }
5862 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00005863 switch (cast<CastExpr>(E)->getCastKind()) {
5864 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005865 case CK_AtomicToNonAtomic:
5866 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00005867 case CK_NoOp:
5868 case CK_IntegralToBoolean:
5869 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00005870 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00005871 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00005872 return ICEDiag(2, E->getLocStart());
5873 }
John McCalld905f5a2010-05-07 05:32:02 +00005874 }
John McCall56ca35d2011-02-17 10:25:35 +00005875 case Expr::BinaryConditionalOperatorClass: {
5876 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
5877 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
5878 if (CommonResult.Val == 2) return CommonResult;
5879 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
5880 if (FalseResult.Val == 2) return FalseResult;
5881 if (CommonResult.Val == 1) return CommonResult;
5882 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005883 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00005884 return FalseResult;
5885 }
John McCalld905f5a2010-05-07 05:32:02 +00005886 case Expr::ConditionalOperatorClass: {
5887 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
5888 // If the condition (ignoring parens) is a __builtin_constant_p call,
5889 // then only the true side is actually considered in an integer constant
5890 // expression, and it is fully evaluated. This is an important GNU
5891 // extension. See GCC PR38377 for discussion.
5892 if (const CallExpr *CallCE
5893 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00005894 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
5895 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005896 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005897 if (CondResult.Val == 2)
5898 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00005899
Richard Smithf48fdb02011-12-09 22:58:01 +00005900 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
5901 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00005902
John McCalld905f5a2010-05-07 05:32:02 +00005903 if (TrueResult.Val == 2)
5904 return TrueResult;
5905 if (FalseResult.Val == 2)
5906 return FalseResult;
5907 if (CondResult.Val == 1)
5908 return CondResult;
5909 if (TrueResult.Val == 0 && FalseResult.Val == 0)
5910 return NoDiag();
5911 // Rare case where the diagnostics depend on which side is evaluated
5912 // Note that if we get here, CondResult is 0, and at least one of
5913 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005914 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00005915 return FalseResult;
5916 }
5917 return TrueResult;
5918 }
5919 case Expr::CXXDefaultArgExprClass:
5920 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
5921 case Expr::ChooseExprClass: {
5922 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
5923 }
5924 }
5925
5926 // Silence a GCC warning
5927 return ICEDiag(2, E->getLocStart());
5928}
5929
Richard Smithf48fdb02011-12-09 22:58:01 +00005930/// Evaluate an expression as a C++11 integral constant expression.
5931static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
5932 const Expr *E,
5933 llvm::APSInt *Value,
5934 SourceLocation *Loc) {
5935 if (!E->getType()->isIntegralOrEnumerationType()) {
5936 if (Loc) *Loc = E->getExprLoc();
5937 return false;
5938 }
5939
5940 Expr::EvalResult Result;
Richard Smithdd1f29b2011-12-12 09:28:41 +00005941 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
5942 Result.Diag = &Diags;
5943 EvalInfo Info(Ctx, Result);
5944
5945 bool IsICE = EvaluateAsRValue(Info, E, Result.Val);
5946 if (!Diags.empty()) {
5947 IsICE = false;
5948 if (Loc) *Loc = Diags[0].first;
5949 } else if (!IsICE && Loc) {
5950 *Loc = E->getExprLoc();
Richard Smithf48fdb02011-12-09 22:58:01 +00005951 }
Richard Smithdd1f29b2011-12-12 09:28:41 +00005952
5953 if (!IsICE)
5954 return false;
5955
5956 assert(Result.Val.isInt() && "pointer cast to int is not an ICE");
5957 if (Value) *Value = Result.Val.getInt();
5958 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00005959}
5960
Richard Smithdd1f29b2011-12-12 09:28:41 +00005961bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00005962 if (Ctx.getLangOptions().CPlusPlus0x)
5963 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
5964
John McCalld905f5a2010-05-07 05:32:02 +00005965 ICEDiag d = CheckICE(this, Ctx);
5966 if (d.Val != 0) {
5967 if (Loc) *Loc = d.Loc;
5968 return false;
5969 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005970 return true;
5971}
5972
5973bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
5974 SourceLocation *Loc, bool isEvaluated) const {
5975 if (Ctx.getLangOptions().CPlusPlus0x)
5976 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
5977
5978 if (!isIntegerConstantExpr(Ctx, Loc))
5979 return false;
5980 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00005981 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00005982 return true;
5983}