blob: 698761f117148818535e5252df3e003ca2e90edf [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 Smith9a17a682011-11-07 05:07:52 +000079 /// Determine whether the described subobject is an array element.
80 static bool SubobjectIsArrayElement(QualType Base,
81 ArrayRef<APValue::LValuePathEntry> Path) {
82 bool IsArrayElement = false;
83 const Type *T = Base.getTypePtr();
84 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
85 IsArrayElement = T && T->isArrayType();
86 if (IsArrayElement)
87 T = T->getBaseElementTypeUnsafe();
Richard Smith180f4792011-11-10 06:34:14 +000088 else if (const FieldDecl *FD = getAsField(Path[I]))
Richard Smith9a17a682011-11-07 05:07:52 +000089 T = FD->getType().getTypePtr();
90 else
91 // Path[I] describes a base class.
92 T = 0;
93 }
94 return IsArrayElement;
95 }
96
Richard Smith0a3bdb62011-11-04 02:25:55 +000097 /// A path from a glvalue to a subobject of that glvalue.
98 struct SubobjectDesignator {
99 /// True if the subobject was named in a manner not supported by C++11. Such
100 /// lvalues can still be folded, but they are not core constant expressions
101 /// and we cannot perform lvalue-to-rvalue conversions on them.
102 bool Invalid : 1;
103
104 /// Whether this designates an array element.
105 bool ArrayElement : 1;
106
107 /// Whether this designates 'one past the end' of the current subobject.
108 bool OnePastTheEnd : 1;
109
Richard Smith9a17a682011-11-07 05:07:52 +0000110 typedef APValue::LValuePathEntry PathEntry;
111
Richard Smith0a3bdb62011-11-04 02:25:55 +0000112 /// The entries on the path from the glvalue to the designated subobject.
113 SmallVector<PathEntry, 8> Entries;
114
115 SubobjectDesignator() :
116 Invalid(false), ArrayElement(false), OnePastTheEnd(false) {}
117
Richard Smith9a17a682011-11-07 05:07:52 +0000118 SubobjectDesignator(const APValue &V) :
119 Invalid(!V.isLValue() || !V.hasLValuePath()), ArrayElement(false),
120 OnePastTheEnd(false) {
121 if (!Invalid) {
122 ArrayRef<PathEntry> VEntries = V.getLValuePath();
123 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
124 if (V.getLValueBase())
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000125 ArrayElement = SubobjectIsArrayElement(getType(V.getLValueBase()),
Richard Smith9a17a682011-11-07 05:07:52 +0000126 V.getLValuePath());
127 else
128 assert(V.getLValuePath().empty() &&"Null pointer with nonempty path");
Richard Smithe24f5fc2011-11-17 22:56:20 +0000129 OnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000130 }
131 }
132
Richard Smith0a3bdb62011-11-04 02:25:55 +0000133 void setInvalid() {
134 Invalid = true;
135 Entries.clear();
136 }
137 /// Update this designator to refer to the given element within this array.
138 void addIndex(uint64_t N) {
139 if (Invalid) return;
140 if (OnePastTheEnd) {
141 setInvalid();
142 return;
143 }
144 PathEntry Entry;
Richard Smith9a17a682011-11-07 05:07:52 +0000145 Entry.ArrayIndex = N;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000146 Entries.push_back(Entry);
147 ArrayElement = true;
148 }
149 /// Update this designator to refer to the given base or member of this
150 /// object.
Richard Smith180f4792011-11-10 06:34:14 +0000151 void addDecl(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000152 if (Invalid) return;
153 if (OnePastTheEnd) {
154 setInvalid();
155 return;
156 }
157 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000158 APValue::BaseOrMemberType Value(D, Virtual);
159 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000160 Entries.push_back(Entry);
161 ArrayElement = false;
162 }
163 /// Add N to the address of this subobject.
164 void adjustIndex(uint64_t N) {
165 if (Invalid) return;
166 if (ArrayElement) {
Richard Smithcc5d4f62011-11-07 09:22:26 +0000167 // FIXME: Make sure the index stays within bounds, or one past the end.
Richard Smith9a17a682011-11-07 05:07:52 +0000168 Entries.back().ArrayIndex += N;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000169 return;
170 }
171 if (OnePastTheEnd && N == (uint64_t)-1)
172 OnePastTheEnd = false;
173 else if (!OnePastTheEnd && N == 1)
174 OnePastTheEnd = true;
175 else if (N != 0)
176 setInvalid();
177 }
178 };
179
Richard Smith47a1eed2011-10-29 20:57:55 +0000180 /// A core constant value. This can be the value of any constant expression,
181 /// or a pointer or reference to a non-static object or function parameter.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000182 ///
183 /// For an LValue, the base and offset are stored in the APValue subobject,
184 /// but the other information is stored in the SubobjectDesignator. For all
185 /// other value kinds, the value is stored directly in the APValue subobject.
Richard Smith47a1eed2011-10-29 20:57:55 +0000186 class CCValue : public APValue {
187 typedef llvm::APSInt APSInt;
188 typedef llvm::APFloat APFloat;
Richard Smith177dce72011-11-01 16:57:24 +0000189 /// If the value is a reference or pointer into a parameter or temporary,
190 /// this is the corresponding call stack frame.
191 CallStackFrame *CallFrame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000192 /// If the value is a reference or pointer, this is a description of how the
193 /// subobject was specified.
194 SubobjectDesignator Designator;
Richard Smith47a1eed2011-10-29 20:57:55 +0000195 public:
Richard Smith177dce72011-11-01 16:57:24 +0000196 struct GlobalValue {};
197
Richard Smith47a1eed2011-10-29 20:57:55 +0000198 CCValue() {}
199 explicit CCValue(const APSInt &I) : APValue(I) {}
200 explicit CCValue(const APFloat &F) : APValue(F) {}
201 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
202 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
203 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smith177dce72011-11-01 16:57:24 +0000204 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000205 CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F,
Richard Smith0a3bdb62011-11-04 02:25:55 +0000206 const SubobjectDesignator &D) :
Richard Smith9a17a682011-11-07 05:07:52 +0000207 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smith177dce72011-11-01 16:57:24 +0000208 CCValue(const APValue &V, GlobalValue) :
Richard Smith9a17a682011-11-07 05:07:52 +0000209 APValue(V), CallFrame(0), Designator(V) {}
Richard Smithe24f5fc2011-11-17 22:56:20 +0000210 CCValue(const ValueDecl *D, bool IsDerivedMember,
211 ArrayRef<const CXXRecordDecl*> Path) :
212 APValue(D, IsDerivedMember, Path) {}
Richard Smith47a1eed2011-10-29 20:57:55 +0000213
Richard Smith177dce72011-11-01 16:57:24 +0000214 CallStackFrame *getLValueFrame() const {
Richard Smith47a1eed2011-10-29 20:57:55 +0000215 assert(getKind() == LValue);
Richard Smith177dce72011-11-01 16:57:24 +0000216 return CallFrame;
Richard Smith47a1eed2011-10-29 20:57:55 +0000217 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000218 SubobjectDesignator &getLValueDesignator() {
219 assert(getKind() == LValue);
220 return Designator;
221 }
222 const SubobjectDesignator &getLValueDesignator() const {
223 return const_cast<CCValue*>(this)->getLValueDesignator();
224 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000225 };
226
Richard Smithd0dccea2011-10-28 22:34:42 +0000227 /// A stack frame in the constexpr call stack.
228 struct CallStackFrame {
229 EvalInfo &Info;
230
231 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000232 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000233
Richard Smith08d6e032011-12-16 19:06:07 +0000234 /// CallLoc - The location of the call expression for this call.
235 SourceLocation CallLoc;
236
237 /// Callee - The function which was called.
238 const FunctionDecl *Callee;
239
Richard Smith180f4792011-11-10 06:34:14 +0000240 /// This - The binding for the this pointer in this call, if any.
241 const LValue *This;
242
Richard Smithd0dccea2011-10-28 22:34:42 +0000243 /// ParmBindings - Parameter bindings for this function call, indexed by
244 /// parameters' function scope indices.
Richard Smith47a1eed2011-10-29 20:57:55 +0000245 const CCValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000246
Richard Smithbd552ef2011-10-31 05:52:43 +0000247 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
248 typedef MapTy::const_iterator temp_iterator;
249 /// Temporaries - Temporary lvalues materialized within this stack frame.
250 MapTy Temporaries;
251
Richard Smith08d6e032011-12-16 19:06:07 +0000252 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
253 const FunctionDecl *Callee, const LValue *This,
Richard Smith180f4792011-11-10 06:34:14 +0000254 const CCValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000255 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000256 };
257
Richard Smithdd1f29b2011-12-12 09:28:41 +0000258 /// A partial diagnostic which we might know in advance that we are not going
259 /// to emit.
260 class OptionalDiagnostic {
261 PartialDiagnostic *Diag;
262
263 public:
264 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
265
266 template<typename T>
267 OptionalDiagnostic &operator<<(const T &v) {
268 if (Diag)
269 *Diag << v;
270 return *this;
271 }
272 };
273
Richard Smithbd552ef2011-10-31 05:52:43 +0000274 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000275 ASTContext &Ctx;
Richard Smithbd552ef2011-10-31 05:52:43 +0000276
277 /// EvalStatus - Contains information about the evaluation.
278 Expr::EvalStatus &EvalStatus;
279
280 /// CurrentCall - The top of the constexpr call stack.
281 CallStackFrame *CurrentCall;
282
Richard Smithbd552ef2011-10-31 05:52:43 +0000283 /// CallStackDepth - The number of calls in the call stack right now.
284 unsigned CallStackDepth;
285
286 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
287 /// OpaqueValues - Values used as the common expression in a
288 /// BinaryConditionalOperator.
289 MapTy OpaqueValues;
290
291 /// BottomFrame - The frame in which evaluation started. This must be
292 /// initialized last.
293 CallStackFrame BottomFrame;
294
Richard Smith180f4792011-11-10 06:34:14 +0000295 /// EvaluatingDecl - This is the declaration whose initializer is being
296 /// evaluated, if any.
297 const VarDecl *EvaluatingDecl;
298
299 /// EvaluatingDeclValue - This is the value being constructed for the
300 /// declaration whose initializer is being evaluated, if any.
301 APValue *EvaluatingDeclValue;
302
Richard Smithc1c5f272011-12-13 06:39:58 +0000303 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
304 /// notes attached to it will also be stored, otherwise they will not be.
305 bool HasActiveDiagnostic;
306
Richard Smithbd552ef2011-10-31 05:52:43 +0000307
308 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000309 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith08d6e032011-12-16 19:06:07 +0000310 CallStackDepth(0), BottomFrame(*this, SourceLocation(), 0, 0, 0),
311 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000312
Richard Smithbd552ef2011-10-31 05:52:43 +0000313 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
314 MapTy::const_iterator i = OpaqueValues.find(e);
315 if (i == OpaqueValues.end()) return 0;
316 return &i->second;
317 }
318
Richard Smith180f4792011-11-10 06:34:14 +0000319 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
320 EvaluatingDecl = VD;
321 EvaluatingDeclValue = &Value;
322 }
323
Richard Smithc18c4232011-11-21 19:36:32 +0000324 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
325
Richard Smithc1c5f272011-12-13 06:39:58 +0000326 bool CheckCallLimit(SourceLocation Loc) {
327 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
328 return true;
329 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
330 << getLangOpts().ConstexprCallDepth;
331 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000332 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000333
Richard Smithc1c5f272011-12-13 06:39:58 +0000334 private:
335 /// Add a diagnostic to the diagnostics list.
336 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
337 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
338 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
339 return EvalStatus.Diag->back().second;
340 }
341
Richard Smith08d6e032011-12-16 19:06:07 +0000342 /// Add notes containing a call stack to the current point of evaluation.
343 void addCallStack(unsigned Limit);
344
Richard Smithc1c5f272011-12-13 06:39:58 +0000345 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000346 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000347 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
348 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000349 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000350 // If we have a prior diagnostic, it will be noting that the expression
351 // isn't a constant expression. This diagnostic is more important.
352 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000353 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000354 unsigned CallStackNotes = CallStackDepth - 1;
355 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
356 if (Limit)
357 CallStackNotes = std::min(CallStackNotes, Limit + 1);
358
Richard Smithc1c5f272011-12-13 06:39:58 +0000359 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000360 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000361 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
362 addDiag(Loc, DiagId);
363 addCallStack(Limit);
364 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000365 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000366 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000367 return OptionalDiagnostic();
368 }
369
370 /// Diagnose that the evaluation does not produce a C++11 core constant
371 /// expression.
Richard Smith7098cbd2011-12-21 05:04:46 +0000372 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
373 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000374 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000375 // Don't override a previous diagnostic.
376 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
377 return OptionalDiagnostic();
Richard Smithc1c5f272011-12-13 06:39:58 +0000378 return Diag(Loc, DiagId, ExtraNotes);
379 }
380
381 /// Add a note to a prior diagnostic.
382 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
383 if (!HasActiveDiagnostic)
384 return OptionalDiagnostic();
385 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000386 }
Richard Smith099e7f62011-12-19 06:19:21 +0000387
388 /// Add a stack of notes to a prior diagnostic.
389 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
390 if (HasActiveDiagnostic) {
391 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
392 Diags.begin(), Diags.end());
393 }
394 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000395 };
Richard Smith08d6e032011-12-16 19:06:07 +0000396}
Richard Smithbd552ef2011-10-31 05:52:43 +0000397
Richard Smith08d6e032011-12-16 19:06:07 +0000398CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
399 const FunctionDecl *Callee, const LValue *This,
400 const CCValue *Arguments)
401 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
402 This(This), Arguments(Arguments) {
403 Info.CurrentCall = this;
404 ++Info.CallStackDepth;
405}
406
407CallStackFrame::~CallStackFrame() {
408 assert(Info.CurrentCall == this && "calls retired out of order");
409 --Info.CallStackDepth;
410 Info.CurrentCall = Caller;
411}
412
413/// Produce a string describing the given constexpr call.
414static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
415 unsigned ArgIndex = 0;
416 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
417 !isa<CXXConstructorDecl>(Frame->Callee);
418
419 if (!IsMemberCall)
420 Out << *Frame->Callee << '(';
421
422 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
423 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
424 if (ArgIndex > IsMemberCall)
425 Out << ", ";
426
427 const ParmVarDecl *Param = *I;
428 const CCValue &Arg = Frame->Arguments[ArgIndex];
429 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
430 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
431 else {
432 // Deliberately slice off the frame to form an APValue we can print.
433 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
434 Arg.getLValueDesignator().Entries,
435 Arg.getLValueDesignator().OnePastTheEnd);
436 Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
437 }
438
439 if (ArgIndex == 0 && IsMemberCall)
440 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000441 }
442
Richard Smith08d6e032011-12-16 19:06:07 +0000443 Out << ')';
444}
445
446void EvalInfo::addCallStack(unsigned Limit) {
447 // Determine which calls to skip, if any.
448 unsigned ActiveCalls = CallStackDepth - 1;
449 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
450 if (Limit && Limit < ActiveCalls) {
451 SkipStart = Limit / 2 + Limit % 2;
452 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000453 }
454
Richard Smith08d6e032011-12-16 19:06:07 +0000455 // Walk the call stack and add the diagnostics.
456 unsigned CallIdx = 0;
457 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
458 Frame = Frame->Caller, ++CallIdx) {
459 // Skip this call?
460 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
461 if (CallIdx == SkipStart) {
462 // Note that we're skipping calls.
463 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
464 << unsigned(ActiveCalls - Limit);
465 }
466 continue;
467 }
468
469 llvm::SmallVector<char, 128> Buffer;
470 llvm::raw_svector_ostream Out(Buffer);
471 describeCall(Frame, Out);
472 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
473 }
474}
475
476namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000477 struct ComplexValue {
478 private:
479 bool IsInt;
480
481 public:
482 APSInt IntReal, IntImag;
483 APFloat FloatReal, FloatImag;
484
485 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
486
487 void makeComplexFloat() { IsInt = false; }
488 bool isComplexFloat() const { return !IsInt; }
489 APFloat &getComplexFloatReal() { return FloatReal; }
490 APFloat &getComplexFloatImag() { return FloatImag; }
491
492 void makeComplexInt() { IsInt = true; }
493 bool isComplexInt() const { return IsInt; }
494 APSInt &getComplexIntReal() { return IntReal; }
495 APSInt &getComplexIntImag() { return IntImag; }
496
Richard Smith47a1eed2011-10-29 20:57:55 +0000497 void moveInto(CCValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000498 if (isComplexFloat())
Richard Smith47a1eed2011-10-29 20:57:55 +0000499 v = CCValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000500 else
Richard Smith47a1eed2011-10-29 20:57:55 +0000501 v = CCValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000502 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000503 void setFrom(const CCValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000504 assert(v.isComplexFloat() || v.isComplexInt());
505 if (v.isComplexFloat()) {
506 makeComplexFloat();
507 FloatReal = v.getComplexFloatReal();
508 FloatImag = v.getComplexFloatImag();
509 } else {
510 makeComplexInt();
511 IntReal = v.getComplexIntReal();
512 IntImag = v.getComplexIntImag();
513 }
514 }
John McCallf4cf1a12010-05-07 17:22:02 +0000515 };
John McCallefdb83e2010-05-07 21:00:08 +0000516
517 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000518 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000519 CharUnits Offset;
Richard Smith177dce72011-11-01 16:57:24 +0000520 CallStackFrame *Frame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000521 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000522
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000523 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000524 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000525 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith177dce72011-11-01 16:57:24 +0000526 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000527 SubobjectDesignator &getLValueDesignator() { return Designator; }
528 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000529
Richard Smith47a1eed2011-10-29 20:57:55 +0000530 void moveInto(CCValue &V) const {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000531 V = CCValue(Base, Offset, Frame, Designator);
John McCallefdb83e2010-05-07 21:00:08 +0000532 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000533 void setFrom(const CCValue &V) {
534 assert(V.isLValue());
535 Base = V.getLValueBase();
536 Offset = V.getLValueOffset();
Richard Smith177dce72011-11-01 16:57:24 +0000537 Frame = V.getLValueFrame();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000538 Designator = V.getLValueDesignator();
539 }
540
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000541 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
542 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000543 Offset = CharUnits::Zero();
544 Frame = F;
545 Designator = SubobjectDesignator();
John McCall56ca35d2011-02-17 10:25:35 +0000546 }
John McCallefdb83e2010-05-07 21:00:08 +0000547 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000548
549 struct MemberPtr {
550 MemberPtr() {}
551 explicit MemberPtr(const ValueDecl *Decl) :
552 DeclAndIsDerivedMember(Decl, false), Path() {}
553
554 /// The member or (direct or indirect) field referred to by this member
555 /// pointer, or 0 if this is a null member pointer.
556 const ValueDecl *getDecl() const {
557 return DeclAndIsDerivedMember.getPointer();
558 }
559 /// Is this actually a member of some type derived from the relevant class?
560 bool isDerivedMember() const {
561 return DeclAndIsDerivedMember.getInt();
562 }
563 /// Get the class which the declaration actually lives in.
564 const CXXRecordDecl *getContainingRecord() const {
565 return cast<CXXRecordDecl>(
566 DeclAndIsDerivedMember.getPointer()->getDeclContext());
567 }
568
569 void moveInto(CCValue &V) const {
570 V = CCValue(getDecl(), isDerivedMember(), Path);
571 }
572 void setFrom(const CCValue &V) {
573 assert(V.isMemberPointer());
574 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
575 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
576 Path.clear();
577 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
578 Path.insert(Path.end(), P.begin(), P.end());
579 }
580
581 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
582 /// whether the member is a member of some class derived from the class type
583 /// of the member pointer.
584 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
585 /// Path - The path of base/derived classes from the member declaration's
586 /// class (exclusive) to the class type of the member pointer (inclusive).
587 SmallVector<const CXXRecordDecl*, 4> Path;
588
589 /// Perform a cast towards the class of the Decl (either up or down the
590 /// hierarchy).
591 bool castBack(const CXXRecordDecl *Class) {
592 assert(!Path.empty());
593 const CXXRecordDecl *Expected;
594 if (Path.size() >= 2)
595 Expected = Path[Path.size() - 2];
596 else
597 Expected = getContainingRecord();
598 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
599 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
600 // if B does not contain the original member and is not a base or
601 // derived class of the class containing the original member, the result
602 // of the cast is undefined.
603 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
604 // (D::*). We consider that to be a language defect.
605 return false;
606 }
607 Path.pop_back();
608 return true;
609 }
610 /// Perform a base-to-derived member pointer cast.
611 bool castToDerived(const CXXRecordDecl *Derived) {
612 if (!getDecl())
613 return true;
614 if (!isDerivedMember()) {
615 Path.push_back(Derived);
616 return true;
617 }
618 if (!castBack(Derived))
619 return false;
620 if (Path.empty())
621 DeclAndIsDerivedMember.setInt(false);
622 return true;
623 }
624 /// Perform a derived-to-base member pointer cast.
625 bool castToBase(const CXXRecordDecl *Base) {
626 if (!getDecl())
627 return true;
628 if (Path.empty())
629 DeclAndIsDerivedMember.setInt(true);
630 if (isDerivedMember()) {
631 Path.push_back(Base);
632 return true;
633 }
634 return castBack(Base);
635 }
636 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000637
638 /// Kinds of constant expression checking, for diagnostics.
639 enum CheckConstantExpressionKind {
640 CCEK_Constant, ///< A normal constant.
641 CCEK_ReturnValue, ///< A constexpr function return value.
642 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
643 };
John McCallf4cf1a12010-05-07 17:22:02 +0000644}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000645
Richard Smith47a1eed2011-10-29 20:57:55 +0000646static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith69c2c502011-11-04 05:33:44 +0000647static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +0000648 const LValue &This, const Expr *E,
649 CheckConstantExpressionKind CCEK
650 = CCEK_Constant);
John McCallefdb83e2010-05-07 21:00:08 +0000651static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
652static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000653static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
654 EvalInfo &Info);
655static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000656static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith47a1eed2011-10-29 20:57:55 +0000657static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000658 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000659static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000660static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000661
662//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000663// Misc utilities
664//===----------------------------------------------------------------------===//
665
Richard Smith180f4792011-11-10 06:34:14 +0000666/// Should this call expression be treated as a string literal?
667static bool IsStringLiteralCall(const CallExpr *E) {
668 unsigned Builtin = E->isBuiltinCall();
669 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
670 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
671}
672
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000673static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000674 // C++11 [expr.const]p3 An address constant expression is a prvalue core
675 // constant expression of pointer type that evaluates to...
676
677 // ... a null pointer value, or a prvalue core constant expression of type
678 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000679 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000680
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000681 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
682 // ... the address of an object with static storage duration,
683 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
684 return VD->hasGlobalStorage();
685 // ... the address of a function,
686 return isa<FunctionDecl>(D);
687 }
688
689 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000690 switch (E->getStmtClass()) {
691 default:
692 return false;
Richard Smith180f4792011-11-10 06:34:14 +0000693 case Expr::CompoundLiteralExprClass:
694 return cast<CompoundLiteralExpr>(E)->isFileScope();
695 // A string literal has static storage duration.
696 case Expr::StringLiteralClass:
697 case Expr::PredefinedExprClass:
698 case Expr::ObjCStringLiteralClass:
699 case Expr::ObjCEncodeExprClass:
700 return true;
701 case Expr::CallExprClass:
702 return IsStringLiteralCall(cast<CallExpr>(E));
703 // For GCC compatibility, &&label has static storage duration.
704 case Expr::AddrLabelExprClass:
705 return true;
706 // A Block literal expression may be used as the initialization value for
707 // Block variables at global or local static scope.
708 case Expr::BlockExprClass:
709 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
710 }
John McCall42c8f872010-05-10 23:27:23 +0000711}
712
Richard Smith9a17a682011-11-07 05:07:52 +0000713/// Check that this reference or pointer core constant expression is a valid
714/// value for a constant expression. Type T should be either LValue or CCValue.
715template<typename T>
Richard Smithf48fdb02011-12-09 22:58:01 +0000716static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000717 const T &LVal, APValue &Value,
718 CheckConstantExpressionKind CCEK) {
719 APValue::LValueBase Base = LVal.getLValueBase();
720 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
721
722 if (!IsGlobalLValue(Base)) {
723 if (Info.getLangOpts().CPlusPlus0x) {
724 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
725 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
726 << E->isGLValue() << !Designator.Entries.empty()
727 << !!VD << CCEK << VD;
728 if (VD)
729 Info.Note(VD->getLocation(), diag::note_declared_at);
730 else
731 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
732 diag::note_constexpr_temporary_here);
733 } else {
Richard Smith7098cbd2011-12-21 05:04:46 +0000734 Info.Diag(E->getExprLoc());
Richard Smithc1c5f272011-12-13 06:39:58 +0000735 }
Richard Smith9a17a682011-11-07 05:07:52 +0000736 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000737 }
Richard Smith9a17a682011-11-07 05:07:52 +0000738
Richard Smith9a17a682011-11-07 05:07:52 +0000739 // A constant expression must refer to an object or be a null pointer.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000740 if (Designator.Invalid ||
Richard Smith9a17a682011-11-07 05:07:52 +0000741 (!LVal.getLValueBase() && !Designator.Entries.empty())) {
Richard Smithc1c5f272011-12-13 06:39:58 +0000742 // FIXME: This is not a core constant expression. We should have already
743 // produced a CCE diagnostic.
Richard Smith9a17a682011-11-07 05:07:52 +0000744 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
745 APValue::NoLValuePath());
746 return true;
747 }
748
Richard Smithc1c5f272011-12-13 06:39:58 +0000749 // Does this refer one past the end of some object?
750 // This is technically not an address constant expression nor a reference
751 // constant expression, but we allow it for address constant expressions.
752 if (E->isGLValue() && Base && Designator.OnePastTheEnd) {
753 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
754 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
755 << !Designator.Entries.empty() << !!VD << VD;
756 if (VD)
757 Info.Note(VD->getLocation(), diag::note_declared_at);
758 else
759 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
760 diag::note_constexpr_temporary_here);
761 return false;
762 }
763
Richard Smith9a17a682011-11-07 05:07:52 +0000764 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
Richard Smithe24f5fc2011-11-17 22:56:20 +0000765 Designator.Entries, Designator.OnePastTheEnd);
Richard Smith9a17a682011-11-07 05:07:52 +0000766 return true;
767}
768
Richard Smith47a1eed2011-10-29 20:57:55 +0000769/// Check that this core constant expression value is a valid value for a
Richard Smith69c2c502011-11-04 05:33:44 +0000770/// constant expression, and if it is, produce the corresponding constant value.
Richard Smithf48fdb02011-12-09 22:58:01 +0000771/// If not, report an appropriate diagnostic.
772static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000773 const CCValue &CCValue, APValue &Value,
774 CheckConstantExpressionKind CCEK
775 = CCEK_Constant) {
Richard Smith9a17a682011-11-07 05:07:52 +0000776 if (!CCValue.isLValue()) {
777 Value = CCValue;
778 return true;
779 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000780 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith47a1eed2011-10-29 20:57:55 +0000781}
782
Richard Smith9e36b532011-10-31 05:11:32 +0000783const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000784 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +0000785}
786
787static bool IsLiteralLValue(const LValue &Value) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000788 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith9e36b532011-10-31 05:11:32 +0000789}
790
Richard Smith65ac5982011-11-01 21:06:14 +0000791static bool IsWeakLValue(const LValue &Value) {
792 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +0000793 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +0000794}
795
Richard Smithe24f5fc2011-11-17 22:56:20 +0000796static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +0000797 // A null base expression indicates a null pointer. These are always
798 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000799 if (!Value.getLValueBase()) {
800 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +0000801 return true;
802 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000803
John McCall42c8f872010-05-10 23:27:23 +0000804 // Require the base expression to be a global l-value.
Richard Smith47a1eed2011-10-29 20:57:55 +0000805 // FIXME: C++11 requires such conversions. Remove this check.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000806 if (!IsGlobalLValue(Value.getLValueBase())) return false;
John McCall42c8f872010-05-10 23:27:23 +0000807
Richard Smithe24f5fc2011-11-17 22:56:20 +0000808 // We have a non-null base. These are generally known to be true, but if it's
809 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +0000810 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +0000811 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +0000812 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +0000813}
814
Richard Smith47a1eed2011-10-29 20:57:55 +0000815static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +0000816 switch (Val.getKind()) {
817 case APValue::Uninitialized:
818 return false;
819 case APValue::Int:
820 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +0000821 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000822 case APValue::Float:
823 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +0000824 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000825 case APValue::ComplexInt:
826 Result = Val.getComplexIntReal().getBoolValue() ||
827 Val.getComplexIntImag().getBoolValue();
828 return true;
829 case APValue::ComplexFloat:
830 Result = !Val.getComplexFloatReal().isZero() ||
831 !Val.getComplexFloatImag().isZero();
832 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +0000833 case APValue::LValue:
834 return EvalPointerValueAsBool(Val, Result);
835 case APValue::MemberPointer:
836 Result = Val.getMemberPointerDecl();
837 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000838 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +0000839 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +0000840 case APValue::Struct:
841 case APValue::Union:
Richard Smithc49bd112011-10-28 17:51:58 +0000842 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000843 }
844
Richard Smithc49bd112011-10-28 17:51:58 +0000845 llvm_unreachable("unknown APValue kind");
846}
847
848static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
849 EvalInfo &Info) {
850 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith47a1eed2011-10-29 20:57:55 +0000851 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +0000852 if (!Evaluate(Val, Info, E))
853 return false;
854 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +0000855}
856
Richard Smithc1c5f272011-12-13 06:39:58 +0000857template<typename T>
858static bool HandleOverflow(EvalInfo &Info, const Expr *E,
859 const T &SrcValue, QualType DestType) {
860 llvm::SmallVector<char, 32> Buffer;
861 SrcValue.toString(Buffer);
862 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
863 << StringRef(Buffer.data(), Buffer.size()) << DestType;
864 return false;
865}
866
867static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
868 QualType SrcType, const APFloat &Value,
869 QualType DestType, APSInt &Result) {
870 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000871 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000872 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000873
Richard Smithc1c5f272011-12-13 06:39:58 +0000874 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000875 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +0000876 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
877 & APFloat::opInvalidOp)
878 return HandleOverflow(Info, E, Value, DestType);
879 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000880}
881
Richard Smithc1c5f272011-12-13 06:39:58 +0000882static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
883 QualType SrcType, QualType DestType,
884 APFloat &Result) {
885 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000886 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +0000887 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
888 APFloat::rmNearestTiesToEven, &ignored)
889 & APFloat::opOverflow)
890 return HandleOverflow(Info, E, Value, DestType);
891 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000892}
893
Mike Stump1eb44332009-09-09 15:08:12 +0000894static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000895 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000896 unsigned DestWidth = Ctx.getIntWidth(DestType);
897 APSInt Result = Value;
898 // Figure out if this is a truncate, extend or noop cast.
899 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000900 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +0000901 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000902 return Result;
903}
904
Richard Smithc1c5f272011-12-13 06:39:58 +0000905static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
906 QualType SrcType, const APSInt &Value,
907 QualType DestType, APFloat &Result) {
908 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
909 if (Result.convertFromAPInt(Value, Value.isSigned(),
910 APFloat::rmNearestTiesToEven)
911 & APFloat::opOverflow)
912 return HandleOverflow(Info, E, Value, DestType);
913 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000914}
915
Richard Smithe24f5fc2011-11-17 22:56:20 +0000916static bool FindMostDerivedObject(EvalInfo &Info, const LValue &LVal,
917 const CXXRecordDecl *&MostDerivedType,
918 unsigned &MostDerivedPathLength,
919 bool &MostDerivedIsArrayElement) {
920 const SubobjectDesignator &D = LVal.Designator;
921 if (D.Invalid || !LVal.Base)
Richard Smith180f4792011-11-10 06:34:14 +0000922 return false;
923
Richard Smithe24f5fc2011-11-17 22:56:20 +0000924 const Type *T = getType(LVal.Base).getTypePtr();
Richard Smith180f4792011-11-10 06:34:14 +0000925
926 // Find path prefix which leads to the most-derived subobject.
Richard Smith180f4792011-11-10 06:34:14 +0000927 MostDerivedType = T->getAsCXXRecordDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +0000928 MostDerivedPathLength = 0;
929 MostDerivedIsArrayElement = false;
Richard Smith180f4792011-11-10 06:34:14 +0000930
931 for (unsigned I = 0, N = D.Entries.size(); I != N; ++I) {
932 bool IsArray = T && T->isArrayType();
933 if (IsArray)
934 T = T->getBaseElementTypeUnsafe();
935 else if (const FieldDecl *FD = getAsField(D.Entries[I]))
936 T = FD->getType().getTypePtr();
937 else
938 T = 0;
939
940 if (T) {
941 MostDerivedType = T->getAsCXXRecordDecl();
942 MostDerivedPathLength = I + 1;
943 MostDerivedIsArrayElement = IsArray;
944 }
945 }
946
Richard Smith180f4792011-11-10 06:34:14 +0000947 // (B*)&d + 1 has no most-derived object.
948 if (D.OnePastTheEnd && MostDerivedPathLength != D.Entries.size())
949 return false;
950
Richard Smithe24f5fc2011-11-17 22:56:20 +0000951 return MostDerivedType != 0;
952}
953
954static void TruncateLValueBasePath(EvalInfo &Info, LValue &Result,
955 const RecordDecl *TruncatedType,
956 unsigned TruncatedElements,
957 bool IsArrayElement) {
958 SubobjectDesignator &D = Result.Designator;
959 const RecordDecl *RD = TruncatedType;
960 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +0000961 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
962 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000963 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +0000964 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000965 else
Richard Smith180f4792011-11-10 06:34:14 +0000966 Result.Offset -= Layout.getBaseClassOffset(Base);
967 RD = Base;
968 }
Richard Smithe24f5fc2011-11-17 22:56:20 +0000969 D.Entries.resize(TruncatedElements);
970 D.ArrayElement = IsArrayElement;
971}
972
973/// If the given LValue refers to a base subobject of some object, find the most
974/// derived object and the corresponding complete record type. This is necessary
975/// in order to find the offset of a virtual base class.
976static bool ExtractMostDerivedObject(EvalInfo &Info, LValue &Result,
977 const CXXRecordDecl *&MostDerivedType) {
978 unsigned MostDerivedPathLength;
979 bool MostDerivedIsArrayElement;
980 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
981 MostDerivedPathLength, MostDerivedIsArrayElement))
982 return false;
983
984 // Remove the trailing base class path entries and their offsets.
985 TruncateLValueBasePath(Info, Result, MostDerivedType, MostDerivedPathLength,
986 MostDerivedIsArrayElement);
Richard Smith180f4792011-11-10 06:34:14 +0000987 return true;
988}
989
990static void HandleLValueDirectBase(EvalInfo &Info, LValue &Obj,
991 const CXXRecordDecl *Derived,
992 const CXXRecordDecl *Base,
993 const ASTRecordLayout *RL = 0) {
994 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
995 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
996 Obj.Designator.addDecl(Base, /*Virtual*/ false);
997}
998
999static bool HandleLValueBase(EvalInfo &Info, LValue &Obj,
1000 const CXXRecordDecl *DerivedDecl,
1001 const CXXBaseSpecifier *Base) {
1002 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1003
1004 if (!Base->isVirtual()) {
1005 HandleLValueDirectBase(Info, Obj, DerivedDecl, BaseDecl);
1006 return true;
1007 }
1008
1009 // Extract most-derived object and corresponding type.
1010 if (!ExtractMostDerivedObject(Info, Obj, DerivedDecl))
1011 return false;
1012
1013 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1014 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1015 Obj.Designator.addDecl(BaseDecl, /*Virtual*/ true);
1016 return true;
1017}
1018
1019/// Update LVal to refer to the given field, which must be a member of the type
1020/// currently described by LVal.
1021static void HandleLValueMember(EvalInfo &Info, LValue &LVal,
1022 const FieldDecl *FD,
1023 const ASTRecordLayout *RL = 0) {
1024 if (!RL)
1025 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1026
1027 unsigned I = FD->getFieldIndex();
1028 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
1029 LVal.Designator.addDecl(FD);
1030}
1031
1032/// Get the size of the given type in char units.
1033static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1034 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1035 // extension.
1036 if (Type->isVoidType() || Type->isFunctionType()) {
1037 Size = CharUnits::One();
1038 return true;
1039 }
1040
1041 if (!Type->isConstantSizeType()) {
1042 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1043 return false;
1044 }
1045
1046 Size = Info.Ctx.getTypeSizeInChars(Type);
1047 return true;
1048}
1049
1050/// Update a pointer value to model pointer arithmetic.
1051/// \param Info - Information about the ongoing evaluation.
1052/// \param LVal - The pointer value to be updated.
1053/// \param EltTy - The pointee type represented by LVal.
1054/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
1055static bool HandleLValueArrayAdjustment(EvalInfo &Info, LValue &LVal,
1056 QualType EltTy, int64_t Adjustment) {
1057 CharUnits SizeOfPointee;
1058 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1059 return false;
1060
1061 // Compute the new offset in the appropriate width.
1062 LVal.Offset += Adjustment * SizeOfPointee;
1063 LVal.Designator.adjustIndex(Adjustment);
1064 return true;
1065}
1066
Richard Smith03f96112011-10-24 17:54:18 +00001067/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001068static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1069 const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +00001070 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001071 // If this is a parameter to an active constexpr function call, perform
1072 // argument substitution.
1073 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00001074 if (!Frame || !Frame->Arguments) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001075 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001076 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001077 }
Richard Smith177dce72011-11-01 16:57:24 +00001078 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1079 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001080 }
Richard Smith03f96112011-10-24 17:54:18 +00001081
Richard Smith099e7f62011-12-19 06:19:21 +00001082 // Dig out the initializer, and use the declaration which it's attached to.
1083 const Expr *Init = VD->getAnyInitializer(VD);
1084 if (!Init || Init->isValueDependent()) {
1085 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1086 return false;
1087 }
1088
Richard Smith180f4792011-11-10 06:34:14 +00001089 // If we're currently evaluating the initializer of this declaration, use that
1090 // in-flight value.
1091 if (Info.EvaluatingDecl == VD) {
1092 Result = CCValue(*Info.EvaluatingDeclValue, CCValue::GlobalValue());
1093 return !Result.isUninit();
1094 }
1095
Richard Smith65ac5982011-11-01 21:06:14 +00001096 // Never evaluate the initializer of a weak variable. We can't be sure that
1097 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001098 if (VD->isWeak()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001099 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001100 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001101 }
Richard Smith65ac5982011-11-01 21:06:14 +00001102
Richard Smith099e7f62011-12-19 06:19:21 +00001103 // Check that we can fold the initializer. In C++, we will have already done
1104 // this in the cases where it matters for conformance.
1105 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1106 if (!VD->evaluateValue(Notes)) {
1107 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1108 Notes.size() + 1) << VD;
1109 Info.Note(VD->getLocation(), diag::note_declared_at);
1110 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001111 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001112 } else if (!VD->checkInitIsICE()) {
1113 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1114 Notes.size() + 1) << VD;
1115 Info.Note(VD->getLocation(), diag::note_declared_at);
1116 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001117 }
Richard Smith03f96112011-10-24 17:54:18 +00001118
Richard Smith099e7f62011-12-19 06:19:21 +00001119 Result = CCValue(*VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +00001120 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001121}
1122
Richard Smithc49bd112011-10-28 17:51:58 +00001123static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001124 Qualifiers Quals = T.getQualifiers();
1125 return Quals.hasConst() && !Quals.hasVolatile();
1126}
1127
Richard Smith59efe262011-11-11 04:05:33 +00001128/// Get the base index of the given base class within an APValue representing
1129/// the given derived class.
1130static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1131 const CXXRecordDecl *Base) {
1132 Base = Base->getCanonicalDecl();
1133 unsigned Index = 0;
1134 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1135 E = Derived->bases_end(); I != E; ++I, ++Index) {
1136 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1137 return Index;
1138 }
1139
1140 llvm_unreachable("base class missing from derived class's bases list");
1141}
1142
Richard Smithcc5d4f62011-11-07 09:22:26 +00001143/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001144static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1145 CCValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001146 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001147 if (Sub.Invalid) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001148 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001149 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001150 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001151 if (Sub.OnePastTheEnd) {
1152 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
1153 diag::note_constexpr_read_past_end :
1154 diag::note_invalid_subexpr_in_const_expr);
1155 return false;
1156 }
Richard Smithf64699e2011-11-11 08:28:03 +00001157 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001158 return true;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001159
1160 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1161 const APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001162 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001163 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001164 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001165 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001166 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001167 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001168 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001169 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001170 // Note, it should not be possible to form a pointer with a valid
1171 // designator which points more than one past the end of the array.
1172 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
1173 diag::note_constexpr_read_past_end :
1174 diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001175 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001176 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001177 if (O->getArrayInitializedElts() > Index)
1178 O = &O->getArrayInitializedElt(Index);
1179 else
1180 O = &O->getArrayFiller();
1181 ObjType = CAT->getElementType();
Richard Smith180f4792011-11-10 06:34:14 +00001182 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1183 // Next subobject is a class, struct or union field.
1184 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1185 if (RD->isUnion()) {
1186 const FieldDecl *UnionField = O->getUnionField();
1187 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001188 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001189 Info.Diag(E->getExprLoc(),
1190 diag::note_constexpr_read_inactive_union_member)
1191 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001192 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001193 }
Richard Smith180f4792011-11-10 06:34:14 +00001194 O = &O->getUnionValue();
1195 } else
1196 O = &O->getStructField(Field->getFieldIndex());
1197 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001198
1199 if (ObjType.isVolatileQualified()) {
1200 if (Info.getLangOpts().CPlusPlus) {
1201 // FIXME: Include a description of the path to the volatile subobject.
1202 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1203 << 2 << Field;
1204 Info.Note(Field->getLocation(), diag::note_declared_at);
1205 } else {
1206 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1207 }
1208 return false;
1209 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001210 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001211 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001212 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1213 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1214 O = &O->getStructBase(getBaseIndex(Derived, Base));
1215 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001216 }
Richard Smith180f4792011-11-10 06:34:14 +00001217
Richard Smithf48fdb02011-12-09 22:58:01 +00001218 if (O->isUninit()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001219 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001220 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001221 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001222 }
1223
Richard Smithcc5d4f62011-11-07 09:22:26 +00001224 Obj = CCValue(*O, CCValue::GlobalValue());
1225 return true;
1226}
1227
Richard Smith180f4792011-11-10 06:34:14 +00001228/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1229/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1230/// for looking up the glvalue referred to by an entity of reference type.
1231///
1232/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001233/// \param Conv - The expression for which we are performing the conversion.
1234/// Used for diagnostics.
Richard Smith180f4792011-11-10 06:34:14 +00001235/// \param Type - The type we expect this conversion to produce.
1236/// \param LVal - The glvalue on which we are attempting to perform this action.
1237/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001238static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1239 QualType Type,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001240 const LValue &LVal, CCValue &RVal) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001241 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1242 if (!Info.getLangOpts().CPlusPlus)
1243 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1244
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001245 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001246 CallStackFrame *Frame = LVal.Frame;
Richard Smith7098cbd2011-12-21 05:04:46 +00001247 SourceLocation Loc = Conv->getExprLoc();
Richard Smithc49bd112011-10-28 17:51:58 +00001248
Richard Smithf48fdb02011-12-09 22:58:01 +00001249 if (!LVal.Base) {
1250 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith7098cbd2011-12-21 05:04:46 +00001251 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1252 return false;
1253 }
1254
1255 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1256 // is not a constant expression (even if the object is non-volatile). We also
1257 // apply this rule to C++98, in order to conform to the expected 'volatile'
1258 // semantics.
1259 if (Type.isVolatileQualified()) {
1260 if (Info.getLangOpts().CPlusPlus)
1261 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1262 else
1263 Info.Diag(Loc);
Richard Smithc49bd112011-10-28 17:51:58 +00001264 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001265 }
Richard Smithc49bd112011-10-28 17:51:58 +00001266
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001267 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001268 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1269 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001270 // expressions are constant expressions too. Inside constexpr functions,
1271 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001272 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001273 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf48fdb02011-12-09 22:58:01 +00001274 if (!VD || VD->isInvalidDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001275 Info.Diag(Loc);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001276 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001277 }
1278
Richard Smith7098cbd2011-12-21 05:04:46 +00001279 // DR1313: If the object is volatile-qualified but the glvalue was not,
1280 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001281 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001282 if (VT.isVolatileQualified()) {
1283 if (Info.getLangOpts().CPlusPlus) {
1284 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1285 Info.Note(VD->getLocation(), diag::note_declared_at);
1286 } else {
1287 Info.Diag(Loc);
Richard Smithf48fdb02011-12-09 22:58:01 +00001288 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001289 return false;
1290 }
1291
1292 if (!isa<ParmVarDecl>(VD)) {
1293 if (VD->isConstexpr()) {
1294 // OK, we can read this variable.
1295 } else if (VT->isIntegralOrEnumerationType()) {
1296 if (!VT.isConstQualified()) {
1297 if (Info.getLangOpts().CPlusPlus) {
1298 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1299 Info.Note(VD->getLocation(), diag::note_declared_at);
1300 } else {
1301 Info.Diag(Loc);
1302 }
1303 return false;
1304 }
1305 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1306 // We support folding of const floating-point types, in order to make
1307 // static const data members of such types (supported as an extension)
1308 // more useful.
1309 if (Info.getLangOpts().CPlusPlus0x) {
1310 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1311 Info.Note(VD->getLocation(), diag::note_declared_at);
1312 } else {
1313 Info.CCEDiag(Loc);
1314 }
1315 } else {
1316 // FIXME: Allow folding of values of any literal type in all languages.
1317 if (Info.getLangOpts().CPlusPlus0x) {
1318 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1319 Info.Note(VD->getLocation(), diag::note_declared_at);
1320 } else {
1321 Info.Diag(Loc);
1322 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001323 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001324 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001325 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001326
Richard Smithf48fdb02011-12-09 22:58:01 +00001327 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001328 return false;
1329
Richard Smith47a1eed2011-10-29 20:57:55 +00001330 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001331 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001332
1333 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1334 // conversion. This happens when the declaration and the lvalue should be
1335 // considered synonymous, for instance when initializing an array of char
1336 // from a string literal. Continue as if the initializer lvalue was the
1337 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001338 assert(RVal.getLValueOffset().isZero() &&
1339 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001340 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001341 Frame = RVal.getLValueFrame();
Richard Smithc49bd112011-10-28 17:51:58 +00001342 }
1343
Richard Smith7098cbd2011-12-21 05:04:46 +00001344 // Volatile temporary objects cannot be read in constant expressions.
1345 if (Base->getType().isVolatileQualified()) {
1346 if (Info.getLangOpts().CPlusPlus) {
1347 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1348 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1349 } else {
1350 Info.Diag(Loc);
1351 }
1352 return false;
1353 }
1354
Richard Smith0a3bdb62011-11-04 02:25:55 +00001355 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1356 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1357 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf48fdb02011-12-09 22:58:01 +00001358 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001359 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001360 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001361 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001362
1363 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith9a17a682011-11-07 05:07:52 +00001364 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smith7098cbd2011-12-21 05:04:46 +00001365 const ConstantArrayType *CAT =
1366 Info.Ctx.getAsConstantArrayType(S->getType());
1367 if (Index >= CAT->getSize().getZExtValue()) {
1368 // Note, it should not be possible to form a pointer which points more
1369 // than one past the end of the array without producing a prior const expr
1370 // diagnostic.
1371 Info.Diag(Loc, diag::note_constexpr_read_past_end);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001372 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001373 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001374 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1375 Type->isUnsignedIntegerType());
1376 if (Index < S->getLength())
1377 Value = S->getCodeUnit(Index);
1378 RVal = CCValue(Value);
1379 return true;
1380 }
1381
Richard Smithcc5d4f62011-11-07 09:22:26 +00001382 if (Frame) {
1383 // If this is a temporary expression with a nontrivial initializer, grab the
1384 // value from the relevant stack frame.
1385 RVal = Frame->Temporaries[Base];
1386 } else if (const CompoundLiteralExpr *CLE
1387 = dyn_cast<CompoundLiteralExpr>(Base)) {
1388 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1389 // initializer until now for such expressions. Such an expression can't be
1390 // an ICE in C, so this only matters for fold.
1391 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1392 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1393 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001394 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001395 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001396 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001397 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001398
Richard Smithf48fdb02011-12-09 22:58:01 +00001399 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1400 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001401}
1402
Richard Smith59efe262011-11-11 04:05:33 +00001403/// Build an lvalue for the object argument of a member function call.
1404static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1405 LValue &This) {
1406 if (Object->getType()->isPointerType())
1407 return EvaluatePointer(Object, This, Info);
1408
1409 if (Object->isGLValue())
1410 return EvaluateLValue(Object, This, Info);
1411
Richard Smithe24f5fc2011-11-17 22:56:20 +00001412 if (Object->getType()->isLiteralType())
1413 return EvaluateTemporary(Object, This, Info);
1414
1415 return false;
1416}
1417
1418/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1419/// lvalue referring to the result.
1420///
1421/// \param Info - Information about the ongoing evaluation.
1422/// \param BO - The member pointer access operation.
1423/// \param LV - Filled in with a reference to the resulting object.
1424/// \param IncludeMember - Specifies whether the member itself is included in
1425/// the resulting LValue subobject designator. This is not possible when
1426/// creating a bound member function.
1427/// \return The field or method declaration to which the member pointer refers,
1428/// or 0 if evaluation fails.
1429static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1430 const BinaryOperator *BO,
1431 LValue &LV,
1432 bool IncludeMember = true) {
1433 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1434
1435 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV))
1436 return 0;
1437
1438 MemberPtr MemPtr;
1439 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1440 return 0;
1441
1442 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1443 // member value, the behavior is undefined.
1444 if (!MemPtr.getDecl())
1445 return 0;
1446
1447 if (MemPtr.isDerivedMember()) {
1448 // This is a member of some derived class. Truncate LV appropriately.
1449 const CXXRecordDecl *MostDerivedType;
1450 unsigned MostDerivedPathLength;
1451 bool MostDerivedIsArrayElement;
1452 if (!FindMostDerivedObject(Info, LV, MostDerivedType, MostDerivedPathLength,
1453 MostDerivedIsArrayElement))
1454 return 0;
1455
1456 // The end of the derived-to-base path for the base object must match the
1457 // derived-to-base path for the member pointer.
1458 if (MostDerivedPathLength + MemPtr.Path.size() >
1459 LV.Designator.Entries.size())
1460 return 0;
1461 unsigned PathLengthToMember =
1462 LV.Designator.Entries.size() - MemPtr.Path.size();
1463 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1464 const CXXRecordDecl *LVDecl = getAsBaseClass(
1465 LV.Designator.Entries[PathLengthToMember + I]);
1466 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1467 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1468 return 0;
1469 }
1470
1471 // Truncate the lvalue to the appropriate derived class.
1472 bool ResultIsArray = false;
1473 if (PathLengthToMember == MostDerivedPathLength)
1474 ResultIsArray = MostDerivedIsArrayElement;
1475 TruncateLValueBasePath(Info, LV, MemPtr.getContainingRecord(),
1476 PathLengthToMember, ResultIsArray);
1477 } else if (!MemPtr.Path.empty()) {
1478 // Extend the LValue path with the member pointer's path.
1479 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1480 MemPtr.Path.size() + IncludeMember);
1481
1482 // Walk down to the appropriate base class.
1483 QualType LVType = BO->getLHS()->getType();
1484 if (const PointerType *PT = LVType->getAs<PointerType>())
1485 LVType = PT->getPointeeType();
1486 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1487 assert(RD && "member pointer access on non-class-type expression");
1488 // The first class in the path is that of the lvalue.
1489 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1490 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
1491 HandleLValueDirectBase(Info, LV, RD, Base);
1492 RD = Base;
1493 }
1494 // Finally cast to the class containing the member.
1495 HandleLValueDirectBase(Info, LV, RD, MemPtr.getContainingRecord());
1496 }
1497
1498 // Add the member. Note that we cannot build bound member functions here.
1499 if (IncludeMember) {
1500 // FIXME: Deal with IndirectFieldDecls.
1501 const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl());
1502 if (!FD) return 0;
1503 HandleLValueMember(Info, LV, FD);
1504 }
1505
1506 return MemPtr.getDecl();
1507}
1508
1509/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1510/// the provided lvalue, which currently refers to the base object.
1511static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1512 LValue &Result) {
1513 const CXXRecordDecl *MostDerivedType;
1514 unsigned MostDerivedPathLength;
1515 bool MostDerivedIsArrayElement;
1516
1517 // Check this cast doesn't take us outside the object.
1518 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
1519 MostDerivedPathLength,
1520 MostDerivedIsArrayElement))
1521 return false;
1522 SubobjectDesignator &D = Result.Designator;
1523 if (MostDerivedPathLength + E->path_size() > D.Entries.size())
1524 return false;
1525
1526 // Check the type of the final cast. We don't need to check the path,
1527 // since a cast can only be formed if the path is unique.
1528 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
1529 bool ResultIsArray = false;
1530 QualType TargetQT = E->getType();
1531 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1532 TargetQT = PT->getPointeeType();
1533 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1534 const CXXRecordDecl *FinalType;
1535 if (NewEntriesSize == MostDerivedPathLength) {
1536 ResultIsArray = MostDerivedIsArrayElement;
1537 FinalType = MostDerivedType;
1538 } else
1539 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
1540 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
1541 return false;
1542
1543 // Truncate the lvalue to the appropriate derived class.
1544 TruncateLValueBasePath(Info, Result, TargetType, NewEntriesSize,
1545 ResultIsArray);
1546 return true;
Richard Smith59efe262011-11-11 04:05:33 +00001547}
1548
Mike Stumpc4c90452009-10-27 22:09:17 +00001549namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00001550enum EvalStmtResult {
1551 /// Evaluation failed.
1552 ESR_Failed,
1553 /// Hit a 'return' statement.
1554 ESR_Returned,
1555 /// Evaluation succeeded.
1556 ESR_Succeeded
1557};
1558}
1559
1560// Evaluate a statement.
Richard Smithc1c5f272011-12-13 06:39:58 +00001561static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00001562 const Stmt *S) {
1563 switch (S->getStmtClass()) {
1564 default:
1565 return ESR_Failed;
1566
1567 case Stmt::NullStmtClass:
1568 case Stmt::DeclStmtClass:
1569 return ESR_Succeeded;
1570
Richard Smithc1c5f272011-12-13 06:39:58 +00001571 case Stmt::ReturnStmtClass: {
1572 CCValue CCResult;
1573 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1574 if (!Evaluate(CCResult, Info, RetExpr) ||
1575 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1576 CCEK_ReturnValue))
1577 return ESR_Failed;
1578 return ESR_Returned;
1579 }
Richard Smithd0dccea2011-10-28 22:34:42 +00001580
1581 case Stmt::CompoundStmtClass: {
1582 const CompoundStmt *CS = cast<CompoundStmt>(S);
1583 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1584 BE = CS->body_end(); BI != BE; ++BI) {
1585 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1586 if (ESR != ESR_Succeeded)
1587 return ESR;
1588 }
1589 return ESR_Succeeded;
1590 }
1591 }
1592}
1593
Richard Smithc1c5f272011-12-13 06:39:58 +00001594/// CheckConstexprFunction - Check that a function can be called in a constant
1595/// expression.
1596static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1597 const FunctionDecl *Declaration,
1598 const FunctionDecl *Definition) {
1599 // Can we evaluate this function call?
1600 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1601 return true;
1602
1603 if (Info.getLangOpts().CPlusPlus0x) {
1604 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00001605 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1606 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00001607 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1608 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1609 << DiagDecl;
1610 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1611 } else {
1612 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1613 }
1614 return false;
1615}
1616
Richard Smith180f4792011-11-10 06:34:14 +00001617namespace {
Richard Smithcd99b072011-11-11 05:48:57 +00001618typedef SmallVector<CCValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00001619}
1620
1621/// EvaluateArgs - Evaluate the arguments to a function call.
1622static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1623 EvalInfo &Info) {
1624 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1625 I != E; ++I)
1626 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1627 return false;
1628 return true;
1629}
1630
Richard Smithd0dccea2011-10-28 22:34:42 +00001631/// Evaluate a function call.
Richard Smith08d6e032011-12-16 19:06:07 +00001632static bool HandleFunctionCall(const Expr *CallExpr, const FunctionDecl *Callee,
1633 const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00001634 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smithc1c5f272011-12-13 06:39:58 +00001635 EvalInfo &Info, APValue &Result) {
1636 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smithd0dccea2011-10-28 22:34:42 +00001637 return false;
1638
Richard Smith180f4792011-11-10 06:34:14 +00001639 ArgVector ArgValues(Args.size());
1640 if (!EvaluateArgs(Args, ArgValues, Info))
1641 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00001642
Richard Smith08d6e032011-12-16 19:06:07 +00001643 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Callee, This,
1644 ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00001645 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1646}
1647
Richard Smith180f4792011-11-10 06:34:14 +00001648/// Evaluate a constructor call.
Richard Smithf48fdb02011-12-09 22:58:01 +00001649static bool HandleConstructorCall(const Expr *CallExpr, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00001650 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00001651 const CXXConstructorDecl *Definition,
Richard Smith59efe262011-11-11 04:05:33 +00001652 EvalInfo &Info,
Richard Smith180f4792011-11-10 06:34:14 +00001653 APValue &Result) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001654 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smith180f4792011-11-10 06:34:14 +00001655 return false;
1656
1657 ArgVector ArgValues(Args.size());
1658 if (!EvaluateArgs(Args, ArgValues, Info))
1659 return false;
1660
Richard Smith08d6e032011-12-16 19:06:07 +00001661 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Definition,
1662 &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00001663
1664 // If it's a delegating constructor, just delegate.
1665 if (Definition->isDelegatingConstructor()) {
1666 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1667 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1668 }
1669
1670 // Reserve space for the struct members.
1671 const CXXRecordDecl *RD = Definition->getParent();
1672 if (!RD->isUnion())
1673 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1674 std::distance(RD->field_begin(), RD->field_end()));
1675
1676 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1677
1678 unsigned BasesSeen = 0;
1679#ifndef NDEBUG
1680 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1681#endif
1682 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1683 E = Definition->init_end(); I != E; ++I) {
1684 if ((*I)->isBaseInitializer()) {
1685 QualType BaseType((*I)->getBaseClass(), 0);
1686#ifndef NDEBUG
1687 // Non-virtual base classes are initialized in the order in the class
1688 // definition. We cannot have a virtual base class for a literal type.
1689 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1690 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1691 "base class initializers not in expected order");
1692 ++BaseIt;
1693#endif
1694 LValue Subobject = This;
1695 HandleLValueDirectBase(Info, Subobject, RD,
1696 BaseType->getAsCXXRecordDecl(), &Layout);
1697 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1698 Subobject, (*I)->getInit()))
1699 return false;
1700 } else if (FieldDecl *FD = (*I)->getMember()) {
1701 LValue Subobject = This;
1702 HandleLValueMember(Info, Subobject, FD, &Layout);
1703 if (RD->isUnion()) {
1704 Result = APValue(FD);
Richard Smithc1c5f272011-12-13 06:39:58 +00001705 if (!EvaluateConstantExpression(Result.getUnionValue(), Info, Subobject,
1706 (*I)->getInit(), CCEK_MemberInit))
Richard Smith180f4792011-11-10 06:34:14 +00001707 return false;
1708 } else if (!EvaluateConstantExpression(
1709 Result.getStructField(FD->getFieldIndex()),
Richard Smithc1c5f272011-12-13 06:39:58 +00001710 Info, Subobject, (*I)->getInit(), CCEK_MemberInit))
Richard Smith180f4792011-11-10 06:34:14 +00001711 return false;
1712 } else {
1713 // FIXME: handle indirect field initializers
Richard Smithdd1f29b2011-12-12 09:28:41 +00001714 Info.Diag((*I)->getInit()->getExprLoc(),
Richard Smithf48fdb02011-12-09 22:58:01 +00001715 diag::note_invalid_subexpr_in_const_expr);
Richard Smith180f4792011-11-10 06:34:14 +00001716 return false;
1717 }
1718 }
1719
1720 return true;
1721}
1722
Richard Smithd0dccea2011-10-28 22:34:42 +00001723namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001724class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001725 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00001726 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00001727public:
1728
Richard Smith1e12c592011-10-16 21:26:27 +00001729 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00001730
1731 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001732 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00001733 return true;
1734 }
1735
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001736 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1737 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00001738 return Visit(E->getResultExpr());
1739 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001740 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001741 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00001742 return true;
1743 return false;
1744 }
John McCallf85e1932011-06-15 23:02:42 +00001745 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001746 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00001747 return true;
1748 return false;
1749 }
1750 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001751 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00001752 return true;
1753 return false;
1754 }
1755
Mike Stumpc4c90452009-10-27 22:09:17 +00001756 // We don't want to evaluate BlockExprs multiple times, as they generate
1757 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001758 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1759 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1760 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00001761 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001762 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1763 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1764 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1765 bool VisitStringLiteral(const StringLiteral *E) { return false; }
1766 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1767 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001768 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001769 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00001770 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001771 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00001772 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001773 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
1774 bool VisitBinAssign(const BinaryOperator *E) { return true; }
1775 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
1776 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00001777 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001778 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
1779 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
1780 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
1781 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
1782 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001783 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00001784 return true;
Mike Stump980ca222009-10-29 20:48:09 +00001785 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00001786 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001787 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00001788
1789 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001790 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00001791 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
1792 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001793 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00001794 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00001795 return false;
1796 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00001797
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001798 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00001799};
1800
John McCall56ca35d2011-02-17 10:25:35 +00001801class OpaqueValueEvaluation {
1802 EvalInfo &info;
1803 OpaqueValueExpr *opaqueValue;
1804
1805public:
1806 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
1807 Expr *value)
1808 : info(info), opaqueValue(opaqueValue) {
1809
1810 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00001811 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00001812 this->opaqueValue = 0;
1813 return;
1814 }
John McCall56ca35d2011-02-17 10:25:35 +00001815 }
1816
1817 bool hasError() const { return opaqueValue == 0; }
1818
1819 ~OpaqueValueEvaluation() {
Richard Smith1e12c592011-10-16 21:26:27 +00001820 // FIXME: This will not work for recursive constexpr functions using opaque
1821 // values. Restore the former value.
John McCall56ca35d2011-02-17 10:25:35 +00001822 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
1823 }
1824};
1825
Mike Stumpc4c90452009-10-27 22:09:17 +00001826} // end anonymous namespace
1827
Eli Friedman4efaa272008-11-12 09:44:48 +00001828//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001829// Generic Evaluation
1830//===----------------------------------------------------------------------===//
1831namespace {
1832
Richard Smithf48fdb02011-12-09 22:58:01 +00001833// FIXME: RetTy is always bool. Remove it.
1834template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001835class ExprEvaluatorBase
1836 : public ConstStmtVisitor<Derived, RetTy> {
1837private:
Richard Smith47a1eed2011-10-29 20:57:55 +00001838 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001839 return static_cast<Derived*>(this)->Success(V, E);
1840 }
Richard Smithf10d9172011-10-11 21:43:33 +00001841 RetTy DerivedValueInitialization(const Expr *E) {
1842 return static_cast<Derived*>(this)->ValueInitialization(E);
1843 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001844
1845protected:
1846 EvalInfo &Info;
1847 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
1848 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
1849
Richard Smithdd1f29b2011-12-12 09:28:41 +00001850 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd5093422011-12-12 09:41:58 +00001851 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00001852 }
1853
1854 /// Report an evaluation error. This should only be called when an error is
1855 /// first discovered. When propagating an error, just return false.
1856 bool Error(const Expr *E, diag::kind D) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001857 Info.Diag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00001858 return false;
1859 }
1860 bool Error(const Expr *E) {
1861 return Error(E, diag::note_invalid_subexpr_in_const_expr);
1862 }
1863
1864 RetTy ValueInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00001865
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001866public:
1867 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
1868
1869 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001870 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001871 }
1872 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00001873 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001874 }
1875
1876 RetTy VisitParenExpr(const ParenExpr *E)
1877 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1878 RetTy VisitUnaryExtension(const UnaryOperator *E)
1879 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1880 RetTy VisitUnaryPlus(const UnaryOperator *E)
1881 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1882 RetTy VisitChooseExpr(const ChooseExpr *E)
1883 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
1884 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
1885 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00001886 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
1887 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00001888 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
1889 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00001890 // We cannot create any objects for which cleanups are required, so there is
1891 // nothing to do here; all cleanups must come from unevaluated subexpressions.
1892 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
1893 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001894
Richard Smithc216a012011-12-12 12:46:16 +00001895 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
1896 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
1897 return static_cast<Derived*>(this)->VisitCastExpr(E);
1898 }
1899 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
1900 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
1901 return static_cast<Derived*>(this)->VisitCastExpr(E);
1902 }
1903
Richard Smithe24f5fc2011-11-17 22:56:20 +00001904 RetTy VisitBinaryOperator(const BinaryOperator *E) {
1905 switch (E->getOpcode()) {
1906 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00001907 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001908
1909 case BO_Comma:
1910 VisitIgnoredValue(E->getLHS());
1911 return StmtVisitorTy::Visit(E->getRHS());
1912
1913 case BO_PtrMemD:
1914 case BO_PtrMemI: {
1915 LValue Obj;
1916 if (!HandleMemberPointerAccess(Info, E, Obj))
1917 return false;
1918 CCValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00001919 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001920 return false;
1921 return DerivedSuccess(Result, E);
1922 }
1923 }
1924 }
1925
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001926 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
1927 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
1928 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00001929 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001930
1931 bool cond;
Richard Smithc49bd112011-10-28 17:51:58 +00001932 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00001933 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001934
1935 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
1936 }
1937
1938 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
1939 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00001940 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00001941 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001942
Richard Smithc49bd112011-10-28 17:51:58 +00001943 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001944 return StmtVisitorTy::Visit(EvalExpr);
1945 }
1946
1947 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00001948 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00001949 if (!Value) {
1950 const Expr *Source = E->getSourceExpr();
1951 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00001952 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00001953 if (Source == E) { // sanity checking.
1954 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00001955 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00001956 }
1957 return StmtVisitorTy::Visit(Source);
1958 }
Richard Smith47a1eed2011-10-29 20:57:55 +00001959 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001960 }
Richard Smithf10d9172011-10-11 21:43:33 +00001961
Richard Smithd0dccea2011-10-28 22:34:42 +00001962 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001963 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00001964 QualType CalleeType = Callee->getType();
1965
Richard Smithd0dccea2011-10-28 22:34:42 +00001966 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00001967 LValue *This = 0, ThisVal;
1968 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith6c957872011-11-10 09:31:24 +00001969
Richard Smith59efe262011-11-11 04:05:33 +00001970 // Extract function decl and 'this' pointer from the callee.
1971 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00001972 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001973 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
1974 // Explicit bound member calls, such as x.f() or p->g();
1975 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00001976 return false;
1977 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001978 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001979 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
1980 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00001981 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
1982 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001983 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001984 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00001985 return Error(Callee);
1986
1987 FD = dyn_cast<FunctionDecl>(Member);
1988 if (!FD)
1989 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00001990 } else if (CalleeType->isFunctionPointerType()) {
1991 CCValue Call;
Richard Smithf48fdb02011-12-09 22:58:01 +00001992 if (!Evaluate(Call, Info, Callee))
1993 return false;
Richard Smith59efe262011-11-11 04:05:33 +00001994
Richard Smithf48fdb02011-12-09 22:58:01 +00001995 if (!Call.isLValue() || !Call.getLValueOffset().isZero())
1996 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001997 FD = dyn_cast_or_null<FunctionDecl>(
1998 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00001999 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002000 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002001
2002 // Overloaded operator calls to member functions are represented as normal
2003 // calls with '*this' as the first argument.
2004 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2005 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002006 // FIXME: When selecting an implicit conversion for an overloaded
2007 // operator delete, we sometimes try to evaluate calls to conversion
2008 // operators without a 'this' parameter!
2009 if (Args.empty())
2010 return Error(E);
2011
Richard Smith59efe262011-11-11 04:05:33 +00002012 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2013 return false;
2014 This = &ThisVal;
2015 Args = Args.slice(1);
2016 }
2017
2018 // Don't call function pointers which have been cast to some other type.
2019 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002020 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002021 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002022 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002023
Richard Smithc1c5f272011-12-13 06:39:58 +00002024 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002025 Stmt *Body = FD->getBody(Definition);
Richard Smith69c2c502011-11-04 05:33:44 +00002026 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002027
Richard Smithc1c5f272011-12-13 06:39:58 +00002028 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith08d6e032011-12-16 19:06:07 +00002029 !HandleFunctionCall(E, Definition, This, Args, Body, Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002030 return false;
2031
2032 return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002033 }
2034
Richard Smithc49bd112011-10-28 17:51:58 +00002035 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2036 return StmtVisitorTy::Visit(E->getInitializer());
2037 }
Richard Smithf10d9172011-10-11 21:43:33 +00002038 RetTy VisitInitListExpr(const InitListExpr *E) {
2039 if (Info.getLangOpts().CPlusPlus0x) {
2040 if (E->getNumInits() == 0)
2041 return DerivedValueInitialization(E);
2042 if (E->getNumInits() == 1)
2043 return StmtVisitorTy::Visit(E->getInit(0));
2044 }
Richard Smithf48fdb02011-12-09 22:58:01 +00002045 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002046 }
2047 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
2048 return DerivedValueInitialization(E);
2049 }
2050 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
2051 return DerivedValueInitialization(E);
2052 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002053 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
2054 return DerivedValueInitialization(E);
2055 }
Richard Smithf10d9172011-10-11 21:43:33 +00002056
Richard Smith180f4792011-11-10 06:34:14 +00002057 /// A member expression where the object is a prvalue is itself a prvalue.
2058 RetTy VisitMemberExpr(const MemberExpr *E) {
2059 assert(!E->isArrow() && "missing call to bound member function?");
2060
2061 CCValue Val;
2062 if (!Evaluate(Val, Info, E->getBase()))
2063 return false;
2064
2065 QualType BaseTy = E->getBase()->getType();
2066
2067 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002068 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002069 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2070 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2071 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2072
2073 SubobjectDesignator Designator;
2074 Designator.addDecl(FD);
2075
Richard Smithf48fdb02011-12-09 22:58:01 +00002076 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002077 DerivedSuccess(Val, E);
2078 }
2079
Richard Smithc49bd112011-10-28 17:51:58 +00002080 RetTy VisitCastExpr(const CastExpr *E) {
2081 switch (E->getCastKind()) {
2082 default:
2083 break;
2084
2085 case CK_NoOp:
2086 return StmtVisitorTy::Visit(E->getSubExpr());
2087
2088 case CK_LValueToRValue: {
2089 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002090 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2091 return false;
2092 CCValue RVal;
2093 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2094 return false;
2095 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002096 }
2097 }
2098
Richard Smithf48fdb02011-12-09 22:58:01 +00002099 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002100 }
2101
Richard Smith8327fad2011-10-24 18:44:57 +00002102 /// Visit a value which is evaluated, but whose value is ignored.
2103 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002104 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002105 if (!Evaluate(Scratch, Info, E))
2106 Info.EvalStatus.HasSideEffects = true;
2107 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002108};
2109
2110}
2111
2112//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002113// Common base class for lvalue and temporary evaluation.
2114//===----------------------------------------------------------------------===//
2115namespace {
2116template<class Derived>
2117class LValueExprEvaluatorBase
2118 : public ExprEvaluatorBase<Derived, bool> {
2119protected:
2120 LValue &Result;
2121 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2122 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2123
2124 bool Success(APValue::LValueBase B) {
2125 Result.set(B);
2126 return true;
2127 }
2128
2129public:
2130 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2131 ExprEvaluatorBaseTy(Info), Result(Result) {}
2132
2133 bool Success(const CCValue &V, const Expr *E) {
2134 Result.setFrom(V);
2135 return true;
2136 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002137
2138 bool CheckValidLValue() {
2139 // C++11 [basic.lval]p1: An lvalue designates a function or an object. Hence
2140 // there are no null references, nor once-past-the-end references.
2141 // FIXME: Check for one-past-the-end array indices
2142 return Result.Base && !Result.Designator.Invalid &&
2143 !Result.Designator.OnePastTheEnd;
2144 }
2145
2146 bool VisitMemberExpr(const MemberExpr *E) {
2147 // Handle non-static data members.
2148 QualType BaseTy;
2149 if (E->isArrow()) {
2150 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2151 return false;
2152 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002153 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002154 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002155 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2156 return false;
2157 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002158 } else {
2159 if (!this->Visit(E->getBase()))
2160 return false;
2161 BaseTy = E->getBase()->getType();
2162 }
2163 // FIXME: In C++11, require the result to be a valid lvalue.
2164
2165 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2166 // FIXME: Handle IndirectFieldDecls
Richard Smithf48fdb02011-12-09 22:58:01 +00002167 if (!FD) return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002168 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2169 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2170 (void)BaseTy;
2171
2172 HandleLValueMember(this->Info, Result, FD);
2173
2174 if (FD->getType()->isReferenceType()) {
2175 CCValue RefValue;
Richard Smithf48fdb02011-12-09 22:58:01 +00002176 if (!HandleLValueToRValueConversion(this->Info, E, FD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002177 RefValue))
2178 return false;
2179 return Success(RefValue, E);
2180 }
2181 return true;
2182 }
2183
2184 bool VisitBinaryOperator(const BinaryOperator *E) {
2185 switch (E->getOpcode()) {
2186 default:
2187 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2188
2189 case BO_PtrMemD:
2190 case BO_PtrMemI:
2191 return HandleMemberPointerAccess(this->Info, E, Result);
2192 }
2193 }
2194
2195 bool VisitCastExpr(const CastExpr *E) {
2196 switch (E->getCastKind()) {
2197 default:
2198 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2199
2200 case CK_DerivedToBase:
2201 case CK_UncheckedDerivedToBase: {
2202 if (!this->Visit(E->getSubExpr()))
2203 return false;
2204 if (!CheckValidLValue())
2205 return false;
2206
2207 // Now figure out the necessary offset to add to the base LV to get from
2208 // the derived class to the base class.
2209 QualType Type = E->getSubExpr()->getType();
2210
2211 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2212 PathE = E->path_end(); PathI != PathE; ++PathI) {
2213 if (!HandleLValueBase(this->Info, Result, Type->getAsCXXRecordDecl(),
2214 *PathI))
2215 return false;
2216 Type = (*PathI)->getType();
2217 }
2218
2219 return true;
2220 }
2221 }
2222 }
2223};
2224}
2225
2226//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002227// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002228//
2229// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2230// function designators (in C), decl references to void objects (in C), and
2231// temporaries (if building with -Wno-address-of-temporary).
2232//
2233// LValue evaluation produces values comprising a base expression of one of the
2234// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002235// - Declarations
2236// * VarDecl
2237// * FunctionDecl
2238// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002239// * CompoundLiteralExpr in C
2240// * StringLiteral
2241// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002242// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002243// * ObjCEncodeExpr
2244// * AddrLabelExpr
2245// * BlockExpr
2246// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002247// - Locals and temporaries
2248// * Any Expr, with a Frame indicating the function in which the temporary was
2249// evaluated.
2250// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002251//===----------------------------------------------------------------------===//
2252namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002253class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002254 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002255public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002256 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2257 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002258
Richard Smithc49bd112011-10-28 17:51:58 +00002259 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2260
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002261 bool VisitDeclRefExpr(const DeclRefExpr *E);
2262 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002263 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002264 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2265 bool VisitMemberExpr(const MemberExpr *E);
2266 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2267 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
2268 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2269 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002270
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002271 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002272 switch (E->getCastKind()) {
2273 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002274 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002275
Eli Friedmandb924222011-10-11 00:13:24 +00002276 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002277 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002278 if (!Visit(E->getSubExpr()))
2279 return false;
2280 Result.Designator.setInvalid();
2281 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002282
Richard Smithe24f5fc2011-11-17 22:56:20 +00002283 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002284 if (!Visit(E->getSubExpr()))
2285 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002286 if (!CheckValidLValue())
2287 return false;
2288 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002289 }
2290 }
Sebastian Redlcea8d962011-09-24 17:48:14 +00002291
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002292 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002293
Eli Friedman4efaa272008-11-12 09:44:48 +00002294};
2295} // end anonymous namespace
2296
Richard Smithc49bd112011-10-28 17:51:58 +00002297/// Evaluate an expression as an lvalue. This can be legitimately called on
2298/// expressions which are not glvalues, in a few cases:
2299/// * function designators in C,
2300/// * "extern void" objects,
2301/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002302static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002303 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2304 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2305 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002306 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002307}
2308
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002309bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002310 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2311 return Success(FD);
2312 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002313 return VisitVarDecl(E, VD);
2314 return Error(E);
2315}
Richard Smith436c8892011-10-24 23:14:33 +00002316
Richard Smithc49bd112011-10-28 17:51:58 +00002317bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002318 if (!VD->getType()->isReferenceType()) {
2319 if (isa<ParmVarDecl>(VD)) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002320 Result.set(VD, Info.CurrentCall);
Richard Smith177dce72011-11-01 16:57:24 +00002321 return true;
2322 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002323 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002324 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002325
Richard Smith47a1eed2011-10-29 20:57:55 +00002326 CCValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002327 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2328 return false;
2329 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002330}
2331
Richard Smithbd552ef2011-10-31 05:52:43 +00002332bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2333 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002334 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002335 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002336 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2337
2338 Result.set(E, Info.CurrentCall);
2339 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2340 Result, E->GetTemporaryExpr());
2341 }
2342
2343 // Materialization of an lvalue temporary occurs when we need to force a copy
2344 // (for instance, if it's a bitfield).
2345 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2346 if (!Visit(E->GetTemporaryExpr()))
2347 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002348 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002349 Info.CurrentCall->Temporaries[E]))
2350 return false;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002351 Result.set(E, Info.CurrentCall);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002352 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002353}
2354
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002355bool
2356LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002357 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2358 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2359 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002360 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002361}
2362
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002363bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002364 // Handle static data members.
2365 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2366 VisitIgnoredValue(E->getBase());
2367 return VisitVarDecl(E, VD);
2368 }
2369
Richard Smithd0dccea2011-10-28 22:34:42 +00002370 // Handle static member functions.
2371 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2372 if (MD->isStatic()) {
2373 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002374 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002375 }
2376 }
2377
Richard Smith180f4792011-11-10 06:34:14 +00002378 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002379 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002380}
2381
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002382bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002383 // FIXME: Deal with vectors as array subscript bases.
2384 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002385 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002386
Anders Carlsson3068d112008-11-16 19:01:22 +00002387 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002388 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002389
Anders Carlsson3068d112008-11-16 19:01:22 +00002390 APSInt Index;
2391 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002392 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002393 int64_t IndexValue
2394 = Index.isSigned() ? Index.getSExtValue()
2395 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00002396
Richard Smithe24f5fc2011-11-17 22:56:20 +00002397 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smith180f4792011-11-10 06:34:14 +00002398 return HandleLValueArrayAdjustment(Info, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00002399}
Eli Friedman4efaa272008-11-12 09:44:48 +00002400
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002401bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002402 // FIXME: In C++11, require the result to be a valid lvalue.
John McCallefdb83e2010-05-07 21:00:08 +00002403 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00002404}
2405
Eli Friedman4efaa272008-11-12 09:44:48 +00002406//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002407// Pointer Evaluation
2408//===----------------------------------------------------------------------===//
2409
Anders Carlssonc754aa62008-07-08 05:13:58 +00002410namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002411class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002412 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00002413 LValue &Result;
2414
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002415 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002416 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00002417 return true;
2418 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002419public:
Mike Stump1eb44332009-09-09 15:08:12 +00002420
John McCallefdb83e2010-05-07 21:00:08 +00002421 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002422 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002423
Richard Smith47a1eed2011-10-29 20:57:55 +00002424 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002425 Result.setFrom(V);
2426 return true;
2427 }
Richard Smithf10d9172011-10-11 21:43:33 +00002428 bool ValueInitialization(const Expr *E) {
2429 return Success((Expr*)0);
2430 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002431
John McCallefdb83e2010-05-07 21:00:08 +00002432 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002433 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00002434 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002435 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00002436 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002437 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00002438 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002439 bool VisitCallExpr(const CallExpr *E);
2440 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00002441 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00002442 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00002443 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00002444 }
Richard Smith180f4792011-11-10 06:34:14 +00002445 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2446 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00002447 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002448 Result = *Info.CurrentCall->This;
2449 return true;
2450 }
John McCall56ca35d2011-02-17 10:25:35 +00002451
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002452 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00002453};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002454} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00002455
John McCallefdb83e2010-05-07 21:00:08 +00002456static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002457 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002458 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002459}
2460
John McCallefdb83e2010-05-07 21:00:08 +00002461bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002462 if (E->getOpcode() != BO_Add &&
2463 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00002464 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002465
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002466 const Expr *PExp = E->getLHS();
2467 const Expr *IExp = E->getRHS();
2468 if (IExp->getType()->isPointerType())
2469 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002470
John McCallefdb83e2010-05-07 21:00:08 +00002471 if (!EvaluatePointer(PExp, Result, Info))
2472 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002473
John McCallefdb83e2010-05-07 21:00:08 +00002474 llvm::APSInt Offset;
2475 if (!EvaluateInteger(IExp, Offset, Info))
2476 return false;
2477 int64_t AdditionalOffset
2478 = Offset.isSigned() ? Offset.getSExtValue()
2479 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00002480 if (E->getOpcode() == BO_Sub)
2481 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002482
Richard Smith180f4792011-11-10 06:34:14 +00002483 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002484 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smith180f4792011-11-10 06:34:14 +00002485 return HandleLValueArrayAdjustment(Info, Result, Pointee, AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002486}
Eli Friedman4efaa272008-11-12 09:44:48 +00002487
John McCallefdb83e2010-05-07 21:00:08 +00002488bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2489 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002490}
Mike Stump1eb44332009-09-09 15:08:12 +00002491
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002492bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2493 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002494
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002495 switch (E->getCastKind()) {
2496 default:
2497 break;
2498
John McCall2de56d12010-08-25 11:45:40 +00002499 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002500 case CK_CPointerToObjCPointerCast:
2501 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00002502 case CK_AnyPointerToBlockPointerCast:
Richard Smithc216a012011-12-12 12:46:16 +00002503 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2504 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2505 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002506 if (!E->getType()->isVoidPointerType()) {
2507 if (SubExpr->getType()->isVoidPointerType())
2508 CCEDiag(E, diag::note_constexpr_invalid_cast)
2509 << 3 << SubExpr->getType();
2510 else
2511 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2512 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002513 if (!Visit(SubExpr))
2514 return false;
2515 Result.Designator.setInvalid();
2516 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002517
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002518 case CK_DerivedToBase:
2519 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00002520 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002521 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002522 if (!Result.Base && Result.Offset.isZero())
2523 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002524
Richard Smith180f4792011-11-10 06:34:14 +00002525 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002526 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00002527 QualType Type =
2528 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002529
Richard Smith180f4792011-11-10 06:34:14 +00002530 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002531 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smith180f4792011-11-10 06:34:14 +00002532 if (!HandleLValueBase(Info, Result, Type->getAsCXXRecordDecl(), *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002533 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002534 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002535 }
2536
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002537 return true;
2538 }
2539
Richard Smithe24f5fc2011-11-17 22:56:20 +00002540 case CK_BaseToDerived:
2541 if (!Visit(E->getSubExpr()))
2542 return false;
2543 if (!Result.Base && Result.Offset.isZero())
2544 return true;
2545 return HandleBaseToDerivedCast(Info, E, Result);
2546
Richard Smith47a1eed2011-10-29 20:57:55 +00002547 case CK_NullToPointer:
2548 return ValueInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00002549
John McCall2de56d12010-08-25 11:45:40 +00002550 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00002551 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2552
Richard Smith47a1eed2011-10-29 20:57:55 +00002553 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00002554 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002555 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00002556
John McCallefdb83e2010-05-07 21:00:08 +00002557 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002558 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2559 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002560 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00002561 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith177dce72011-11-01 16:57:24 +00002562 Result.Frame = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002563 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00002564 return true;
2565 } else {
2566 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00002567 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00002568 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002569 }
2570 }
John McCall2de56d12010-08-25 11:45:40 +00002571 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002572 if (SubExpr->isGLValue()) {
2573 if (!EvaluateLValue(SubExpr, Result, Info))
2574 return false;
2575 } else {
2576 Result.set(SubExpr, Info.CurrentCall);
2577 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2578 Info, Result, SubExpr))
2579 return false;
2580 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002581 // The result is a pointer to the first element of the array.
2582 Result.Designator.addIndex(0);
2583 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00002584
John McCall2de56d12010-08-25 11:45:40 +00002585 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00002586 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002587 }
2588
Richard Smithc49bd112011-10-28 17:51:58 +00002589 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002590}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002591
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002592bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00002593 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00002594 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00002595
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002596 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002597}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002598
2599//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002600// Member Pointer Evaluation
2601//===----------------------------------------------------------------------===//
2602
2603namespace {
2604class MemberPointerExprEvaluator
2605 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2606 MemberPtr &Result;
2607
2608 bool Success(const ValueDecl *D) {
2609 Result = MemberPtr(D);
2610 return true;
2611 }
2612public:
2613
2614 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2615 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2616
2617 bool Success(const CCValue &V, const Expr *E) {
2618 Result.setFrom(V);
2619 return true;
2620 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002621 bool ValueInitialization(const Expr *E) {
2622 return Success((const ValueDecl*)0);
2623 }
2624
2625 bool VisitCastExpr(const CastExpr *E);
2626 bool VisitUnaryAddrOf(const UnaryOperator *E);
2627};
2628} // end anonymous namespace
2629
2630static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2631 EvalInfo &Info) {
2632 assert(E->isRValue() && E->getType()->isMemberPointerType());
2633 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2634}
2635
2636bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2637 switch (E->getCastKind()) {
2638 default:
2639 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2640
2641 case CK_NullToMemberPointer:
2642 return ValueInitialization(E);
2643
2644 case CK_BaseToDerivedMemberPointer: {
2645 if (!Visit(E->getSubExpr()))
2646 return false;
2647 if (E->path_empty())
2648 return true;
2649 // Base-to-derived member pointer casts store the path in derived-to-base
2650 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2651 // the wrong end of the derived->base arc, so stagger the path by one class.
2652 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2653 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2654 PathI != PathE; ++PathI) {
2655 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2656 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2657 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00002658 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002659 }
2660 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2661 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002662 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002663 return true;
2664 }
2665
2666 case CK_DerivedToBaseMemberPointer:
2667 if (!Visit(E->getSubExpr()))
2668 return false;
2669 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2670 PathE = E->path_end(); PathI != PathE; ++PathI) {
2671 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2672 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2673 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00002674 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002675 }
2676 return true;
2677 }
2678}
2679
2680bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2681 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
2682 // member can be formed.
2683 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
2684}
2685
2686//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00002687// Record Evaluation
2688//===----------------------------------------------------------------------===//
2689
2690namespace {
2691 class RecordExprEvaluator
2692 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
2693 const LValue &This;
2694 APValue &Result;
2695 public:
2696
2697 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
2698 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
2699
2700 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002701 return CheckConstantExpression(Info, E, V, Result);
Richard Smith180f4792011-11-10 06:34:14 +00002702 }
Richard Smith180f4792011-11-10 06:34:14 +00002703
Richard Smith59efe262011-11-11 04:05:33 +00002704 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00002705 bool VisitInitListExpr(const InitListExpr *E);
2706 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
2707 };
2708}
2709
Richard Smith59efe262011-11-11 04:05:33 +00002710bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
2711 switch (E->getCastKind()) {
2712 default:
2713 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2714
2715 case CK_ConstructorConversion:
2716 return Visit(E->getSubExpr());
2717
2718 case CK_DerivedToBase:
2719 case CK_UncheckedDerivedToBase: {
2720 CCValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00002721 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00002722 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002723 if (!DerivedObject.isStruct())
2724 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00002725
2726 // Derived-to-base rvalue conversion: just slice off the derived part.
2727 APValue *Value = &DerivedObject;
2728 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
2729 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2730 PathE = E->path_end(); PathI != PathE; ++PathI) {
2731 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
2732 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2733 Value = &Value->getStructBase(getBaseIndex(RD, Base));
2734 RD = Base;
2735 }
2736 Result = *Value;
2737 return true;
2738 }
2739 }
2740}
2741
Richard Smith180f4792011-11-10 06:34:14 +00002742bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2743 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2744 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2745
2746 if (RD->isUnion()) {
2747 Result = APValue(E->getInitializedFieldInUnion());
2748 if (!E->getNumInits())
2749 return true;
2750 LValue Subobject = This;
2751 HandleLValueMember(Info, Subobject, E->getInitializedFieldInUnion(),
2752 &Layout);
2753 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2754 Subobject, E->getInit(0));
2755 }
2756
2757 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
2758 "initializer list for class with base classes");
2759 Result = APValue(APValue::UninitStruct(), 0,
2760 std::distance(RD->field_begin(), RD->field_end()));
2761 unsigned ElementNo = 0;
2762 for (RecordDecl::field_iterator Field = RD->field_begin(),
2763 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
2764 // Anonymous bit-fields are not considered members of the class for
2765 // purposes of aggregate initialization.
2766 if (Field->isUnnamedBitfield())
2767 continue;
2768
2769 LValue Subobject = This;
2770 HandleLValueMember(Info, Subobject, *Field, &Layout);
2771
2772 if (ElementNo < E->getNumInits()) {
2773 if (!EvaluateConstantExpression(
2774 Result.getStructField((*Field)->getFieldIndex()),
2775 Info, Subobject, E->getInit(ElementNo++)))
2776 return false;
2777 } else {
2778 // Perform an implicit value-initialization for members beyond the end of
2779 // the initializer list.
2780 ImplicitValueInitExpr VIE(Field->getType());
2781 if (!EvaluateConstantExpression(
2782 Result.getStructField((*Field)->getFieldIndex()),
2783 Info, Subobject, &VIE))
2784 return false;
2785 }
2786 }
2787
2788 return true;
2789}
2790
2791bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
2792 const CXXConstructorDecl *FD = E->getConstructor();
2793 const FunctionDecl *Definition = 0;
2794 FD->getBody(Definition);
2795
Richard Smithc1c5f272011-12-13 06:39:58 +00002796 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
2797 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002798
2799 // FIXME: Elide the copy/move construction wherever we can.
2800 if (E->isElidable())
2801 if (const MaterializeTemporaryExpr *ME
2802 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
2803 return Visit(ME->GetTemporaryExpr());
2804
2805 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf48fdb02011-12-09 22:58:01 +00002806 return HandleConstructorCall(E, This, Args,
2807 cast<CXXConstructorDecl>(Definition), Info,
2808 Result);
Richard Smith180f4792011-11-10 06:34:14 +00002809}
2810
2811static bool EvaluateRecord(const Expr *E, const LValue &This,
2812 APValue &Result, EvalInfo &Info) {
2813 assert(E->isRValue() && E->getType()->isRecordType() &&
2814 E->getType()->isLiteralType() &&
2815 "can't evaluate expression as a record rvalue");
2816 return RecordExprEvaluator(Info, This, Result).Visit(E);
2817}
2818
2819//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002820// Temporary Evaluation
2821//
2822// Temporaries are represented in the AST as rvalues, but generally behave like
2823// lvalues. The full-object of which the temporary is a subobject is implicitly
2824// materialized so that a reference can bind to it.
2825//===----------------------------------------------------------------------===//
2826namespace {
2827class TemporaryExprEvaluator
2828 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
2829public:
2830 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
2831 LValueExprEvaluatorBaseTy(Info, Result) {}
2832
2833 /// Visit an expression which constructs the value of this temporary.
2834 bool VisitConstructExpr(const Expr *E) {
2835 Result.set(E, Info.CurrentCall);
2836 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2837 Result, E);
2838 }
2839
2840 bool VisitCastExpr(const CastExpr *E) {
2841 switch (E->getCastKind()) {
2842 default:
2843 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
2844
2845 case CK_ConstructorConversion:
2846 return VisitConstructExpr(E->getSubExpr());
2847 }
2848 }
2849 bool VisitInitListExpr(const InitListExpr *E) {
2850 return VisitConstructExpr(E);
2851 }
2852 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
2853 return VisitConstructExpr(E);
2854 }
2855 bool VisitCallExpr(const CallExpr *E) {
2856 return VisitConstructExpr(E);
2857 }
2858};
2859} // end anonymous namespace
2860
2861/// Evaluate an expression of record type as a temporary.
2862static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002863 assert(E->isRValue() && E->getType()->isRecordType());
2864 if (!E->getType()->isLiteralType()) {
2865 if (Info.getLangOpts().CPlusPlus0x)
2866 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
2867 << E->getType();
2868 else
2869 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
2870 return false;
2871 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002872 return TemporaryExprEvaluator(Info, Result).Visit(E);
2873}
2874
2875//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00002876// Vector Evaluation
2877//===----------------------------------------------------------------------===//
2878
2879namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002880 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00002881 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
2882 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00002883 public:
Mike Stump1eb44332009-09-09 15:08:12 +00002884
Richard Smith07fc6572011-10-22 21:10:00 +00002885 VectorExprEvaluator(EvalInfo &info, APValue &Result)
2886 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002887
Richard Smith07fc6572011-10-22 21:10:00 +00002888 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
2889 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
2890 // FIXME: remove this APValue copy.
2891 Result = APValue(V.data(), V.size());
2892 return true;
2893 }
Richard Smith69c2c502011-11-04 05:33:44 +00002894 bool Success(const CCValue &V, const Expr *E) {
2895 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00002896 Result = V;
2897 return true;
2898 }
Richard Smith07fc6572011-10-22 21:10:00 +00002899 bool ValueInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002900
Richard Smith07fc6572011-10-22 21:10:00 +00002901 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00002902 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00002903 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00002904 bool VisitInitListExpr(const InitListExpr *E);
2905 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00002906 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00002907 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00002908 // shufflevector, ExtVectorElementExpr
2909 // (Note that these require implementing conversions
2910 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +00002911 };
2912} // end anonymous namespace
2913
2914static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002915 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00002916 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00002917}
2918
Richard Smith07fc6572011-10-22 21:10:00 +00002919bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
2920 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00002921 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00002922
Richard Smithd62ca372011-12-06 22:44:34 +00002923 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00002924 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00002925
Eli Friedman46a52322011-03-25 00:43:55 +00002926 switch (E->getCastKind()) {
2927 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00002928 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00002929 if (SETy->isIntegerType()) {
2930 APSInt IntResult;
2931 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002932 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00002933 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00002934 } else if (SETy->isRealFloatingType()) {
2935 APFloat F(0.0);
2936 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002937 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00002938 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00002939 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00002940 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00002941 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00002942
2943 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00002944 SmallVector<APValue, 4> Elts(NElts, Val);
2945 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00002946 }
Eli Friedman46a52322011-03-25 00:43:55 +00002947 default:
Richard Smithc49bd112011-10-28 17:51:58 +00002948 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00002949 }
Nate Begeman59b5da62009-01-18 03:20:47 +00002950}
2951
Richard Smith07fc6572011-10-22 21:10:00 +00002952bool
Nate Begeman59b5da62009-01-18 03:20:47 +00002953VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00002954 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00002955 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00002956 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00002957
Nate Begeman59b5da62009-01-18 03:20:47 +00002958 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002959 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00002960
John McCalla7d6c222010-06-11 17:54:15 +00002961 // If a vector is initialized with a single element, that value
2962 // becomes every element of the vector, not just the first.
2963 // This is the behavior described in the IBM AltiVec documentation.
2964 if (NumInits == 1) {
Richard Smith07fc6572011-10-22 21:10:00 +00002965
2966 // Handle the case where the vector is initialized by another
Tanya Lattnerb92ae0e2011-04-15 22:42:59 +00002967 // vector (OpenCL 6.1.6).
2968 if (E->getInit(0)->getType()->isVectorType())
Richard Smith07fc6572011-10-22 21:10:00 +00002969 return Visit(E->getInit(0));
2970
John McCalla7d6c222010-06-11 17:54:15 +00002971 APValue InitValue;
Nate Begeman59b5da62009-01-18 03:20:47 +00002972 if (EltTy->isIntegerType()) {
2973 llvm::APSInt sInt(32);
John McCalla7d6c222010-06-11 17:54:15 +00002974 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002975 return false;
John McCalla7d6c222010-06-11 17:54:15 +00002976 InitValue = APValue(sInt);
Nate Begeman59b5da62009-01-18 03:20:47 +00002977 } else {
2978 llvm::APFloat f(0.0);
John McCalla7d6c222010-06-11 17:54:15 +00002979 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002980 return false;
John McCalla7d6c222010-06-11 17:54:15 +00002981 InitValue = APValue(f);
2982 }
2983 for (unsigned i = 0; i < NumElements; i++) {
2984 Elements.push_back(InitValue);
2985 }
2986 } else {
2987 for (unsigned i = 0; i < NumElements; i++) {
2988 if (EltTy->isIntegerType()) {
2989 llvm::APSInt sInt(32);
2990 if (i < NumInits) {
2991 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002992 return false;
John McCalla7d6c222010-06-11 17:54:15 +00002993 } else {
2994 sInt = Info.Ctx.MakeIntValue(0, EltTy);
2995 }
2996 Elements.push_back(APValue(sInt));
Eli Friedman91110ee2009-02-23 04:23:56 +00002997 } else {
John McCalla7d6c222010-06-11 17:54:15 +00002998 llvm::APFloat f(0.0);
2999 if (i < NumInits) {
3000 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003001 return false;
John McCalla7d6c222010-06-11 17:54:15 +00003002 } else {
3003 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3004 }
3005 Elements.push_back(APValue(f));
Eli Friedman91110ee2009-02-23 04:23:56 +00003006 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003007 }
3008 }
Richard Smith07fc6572011-10-22 21:10:00 +00003009 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003010}
3011
Richard Smith07fc6572011-10-22 21:10:00 +00003012bool
3013VectorExprEvaluator::ValueInitialization(const Expr *E) {
3014 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003015 QualType EltTy = VT->getElementType();
3016 APValue ZeroElement;
3017 if (EltTy->isIntegerType())
3018 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3019 else
3020 ZeroElement =
3021 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3022
Chris Lattner5f9e2722011-07-23 10:55:15 +00003023 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003024 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003025}
3026
Richard Smith07fc6572011-10-22 21:10:00 +00003027bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003028 VisitIgnoredValue(E->getSubExpr());
Richard Smith07fc6572011-10-22 21:10:00 +00003029 return ValueInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003030}
3031
Nate Begeman59b5da62009-01-18 03:20:47 +00003032//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003033// Array Evaluation
3034//===----------------------------------------------------------------------===//
3035
3036namespace {
3037 class ArrayExprEvaluator
3038 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003039 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003040 APValue &Result;
3041 public:
3042
Richard Smith180f4792011-11-10 06:34:14 +00003043 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3044 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003045
3046 bool Success(const APValue &V, const Expr *E) {
3047 assert(V.isArray() && "Expected array type");
3048 Result = V;
3049 return true;
3050 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003051
Richard Smith180f4792011-11-10 06:34:14 +00003052 bool ValueInitialization(const Expr *E) {
3053 const ConstantArrayType *CAT =
3054 Info.Ctx.getAsConstantArrayType(E->getType());
3055 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003056 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003057
3058 Result = APValue(APValue::UninitArray(), 0,
3059 CAT->getSize().getZExtValue());
3060 if (!Result.hasArrayFiller()) return true;
3061
3062 // Value-initialize all elements.
3063 LValue Subobject = This;
3064 Subobject.Designator.addIndex(0);
3065 ImplicitValueInitExpr VIE(CAT->getElementType());
3066 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3067 Subobject, &VIE);
3068 }
3069
Richard Smithcc5d4f62011-11-07 09:22:26 +00003070 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003071 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003072 };
3073} // end anonymous namespace
3074
Richard Smith180f4792011-11-10 06:34:14 +00003075static bool EvaluateArray(const Expr *E, const LValue &This,
3076 APValue &Result, EvalInfo &Info) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00003077 assert(E->isRValue() && E->getType()->isArrayType() &&
3078 E->getType()->isLiteralType() && "not a literal array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003079 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003080}
3081
3082bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3083 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3084 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003085 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003086
3087 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3088 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003089 LValue Subobject = This;
3090 Subobject.Designator.addIndex(0);
3091 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003092 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003093 I != End; ++I, ++Index) {
3094 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
3095 Info, Subobject, cast<Expr>(*I)))
Richard Smithcc5d4f62011-11-07 09:22:26 +00003096 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003097 if (!HandleLValueArrayAdjustment(Info, Subobject, CAT->getElementType(), 1))
3098 return false;
3099 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003100
3101 if (!Result.hasArrayFiller()) return true;
3102 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003103 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3104 // but sometimes does:
3105 // struct S { constexpr S() : p(&p) {} void *p; };
3106 // S s[10] = {};
Richard Smithcc5d4f62011-11-07 09:22:26 +00003107 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smith180f4792011-11-10 06:34:14 +00003108 Subobject, E->getArrayFiller());
Richard Smithcc5d4f62011-11-07 09:22:26 +00003109}
3110
Richard Smithe24f5fc2011-11-17 22:56:20 +00003111bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3112 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3113 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003114 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003115
3116 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3117 if (!Result.hasArrayFiller())
3118 return true;
3119
3120 const CXXConstructorDecl *FD = E->getConstructor();
3121 const FunctionDecl *Definition = 0;
3122 FD->getBody(Definition);
3123
Richard Smithc1c5f272011-12-13 06:39:58 +00003124 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3125 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003126
3127 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3128 // but sometimes does:
3129 // struct S { constexpr S() : p(&p) {} void *p; };
3130 // S s[10];
3131 LValue Subobject = This;
3132 Subobject.Designator.addIndex(0);
3133 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf48fdb02011-12-09 22:58:01 +00003134 return HandleConstructorCall(E, Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003135 cast<CXXConstructorDecl>(Definition),
3136 Info, Result.getArrayFiller());
3137}
3138
Richard Smithcc5d4f62011-11-07 09:22:26 +00003139//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003140// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003141//
3142// As a GNU extension, we support casting pointers to sufficiently-wide integer
3143// types and back in constant folding. Integer values are thus represented
3144// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003145//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003146
3147namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003148class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003149 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00003150 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003151public:
Richard Smith47a1eed2011-10-29 20:57:55 +00003152 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003153 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003154
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003155 bool Success(const llvm::APSInt &SI, const Expr *E) {
3156 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003157 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003158 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003159 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003160 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003161 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003162 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003163 return true;
3164 }
3165
Daniel Dunbar131eb432009-02-19 09:06:44 +00003166 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003167 assert(E->getType()->isIntegralOrEnumerationType() &&
3168 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003169 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003170 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003171 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003172 Result.getInt().setIsUnsigned(
3173 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003174 return true;
3175 }
3176
3177 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003178 assert(E->getType()->isIntegralOrEnumerationType() &&
3179 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003180 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003181 return true;
3182 }
3183
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003184 bool Success(CharUnits Size, const Expr *E) {
3185 return Success(Size.getQuantity(), E);
3186 }
3187
Richard Smith47a1eed2011-10-29 20:57:55 +00003188 bool Success(const CCValue &V, const Expr *E) {
Richard Smith342f1f82011-10-29 22:55:55 +00003189 if (V.isLValue()) {
3190 Result = V;
3191 return true;
3192 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003193 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003194 }
Mike Stump1eb44332009-09-09 15:08:12 +00003195
Richard Smithf10d9172011-10-11 21:43:33 +00003196 bool ValueInitialization(const Expr *E) { return Success(0, E); }
3197
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003198 //===--------------------------------------------------------------------===//
3199 // Visitor Methods
3200 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003201
Chris Lattner4c4867e2008-07-12 00:38:25 +00003202 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003203 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003204 }
3205 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003206 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003207 }
Eli Friedman04309752009-11-24 05:28:59 +00003208
3209 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3210 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003211 if (CheckReferencedDecl(E, E->getDecl()))
3212 return true;
3213
3214 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003215 }
3216 bool VisitMemberExpr(const MemberExpr *E) {
3217 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00003218 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00003219 return true;
3220 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003221
3222 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003223 }
3224
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003225 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003226 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003227 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003228 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00003229
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003230 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003231 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00003232
Anders Carlsson3068d112008-11-16 19:01:22 +00003233 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003234 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00003235 }
Mike Stump1eb44332009-09-09 15:08:12 +00003236
Richard Smithf10d9172011-10-11 21:43:33 +00003237 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00003238 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00003239 return ValueInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00003240 }
3241
Sebastian Redl64b45f72009-01-05 20:52:13 +00003242 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003243 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003244 }
3245
Francois Pichet6ad6f282010-12-07 00:08:36 +00003246 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3247 return Success(E->getValue(), E);
3248 }
3249
John Wiegley21ff2e52011-04-28 00:16:57 +00003250 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3251 return Success(E->getValue(), E);
3252 }
3253
John Wiegley55262202011-04-25 06:54:41 +00003254 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3255 return Success(E->getValue(), E);
3256 }
3257
Eli Friedman722c7172009-02-28 03:59:05 +00003258 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003259 bool VisitUnaryImag(const UnaryOperator *E);
3260
Sebastian Redl295995c2010-09-10 20:55:47 +00003261 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00003262 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00003263
Chris Lattnerfcee0012008-07-11 21:24:13 +00003264private:
Ken Dyck8b752f12010-01-27 17:10:57 +00003265 CharUnits GetAlignOfExpr(const Expr *E);
3266 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003267 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003268 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003269 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003270};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003271} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003272
Richard Smithc49bd112011-10-28 17:51:58 +00003273/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3274/// produce either the integer value or a pointer.
3275///
3276/// GCC has a heinous extension which folds casts between pointer types and
3277/// pointer-sized integral types. We support this by allowing the evaluation of
3278/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3279/// Some simple arithmetic on such values is supported (they are treated much
3280/// like char*).
Richard Smithf48fdb02011-12-09 22:58:01 +00003281static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00003282 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003283 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003284 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003285}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003286
Richard Smithf48fdb02011-12-09 22:58:01 +00003287static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003288 CCValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00003289 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003290 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003291 if (!Val.isInt()) {
3292 // FIXME: It would be better to produce the diagnostic for casting
3293 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00003294 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00003295 return false;
3296 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003297 Result = Val.getInt();
3298 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00003299}
Anders Carlsson650c92f2008-07-08 15:34:11 +00003300
Richard Smithf48fdb02011-12-09 22:58:01 +00003301/// Check whether the given declaration can be directly converted to an integral
3302/// rvalue. If not, no diagnostic is produced; there are other things we can
3303/// try.
Eli Friedman04309752009-11-24 05:28:59 +00003304bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00003305 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003306 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003307 // Check for signedness/width mismatches between E type and ECD value.
3308 bool SameSign = (ECD->getInitVal().isSigned()
3309 == E->getType()->isSignedIntegerOrEnumerationType());
3310 bool SameWidth = (ECD->getInitVal().getBitWidth()
3311 == Info.Ctx.getIntWidth(E->getType()));
3312 if (SameSign && SameWidth)
3313 return Success(ECD->getInitVal(), E);
3314 else {
3315 // Get rid of mismatch (otherwise Success assertions will fail)
3316 // by computing a new value matching the type of E.
3317 llvm::APSInt Val = ECD->getInitVal();
3318 if (!SameSign)
3319 Val.setIsSigned(!ECD->getInitVal().isSigned());
3320 if (!SameWidth)
3321 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3322 return Success(Val, E);
3323 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003324 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003325 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00003326}
3327
Chris Lattnera4d55d82008-10-06 06:40:35 +00003328/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3329/// as GCC.
3330static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3331 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003332 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00003333 enum gcc_type_class {
3334 no_type_class = -1,
3335 void_type_class, integer_type_class, char_type_class,
3336 enumeral_type_class, boolean_type_class,
3337 pointer_type_class, reference_type_class, offset_type_class,
3338 real_type_class, complex_type_class,
3339 function_type_class, method_type_class,
3340 record_type_class, union_type_class,
3341 array_type_class, string_type_class,
3342 lang_type_class
3343 };
Mike Stump1eb44332009-09-09 15:08:12 +00003344
3345 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00003346 // ideal, however it is what gcc does.
3347 if (E->getNumArgs() == 0)
3348 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00003349
Chris Lattnera4d55d82008-10-06 06:40:35 +00003350 QualType ArgTy = E->getArg(0)->getType();
3351 if (ArgTy->isVoidType())
3352 return void_type_class;
3353 else if (ArgTy->isEnumeralType())
3354 return enumeral_type_class;
3355 else if (ArgTy->isBooleanType())
3356 return boolean_type_class;
3357 else if (ArgTy->isCharType())
3358 return string_type_class; // gcc doesn't appear to use char_type_class
3359 else if (ArgTy->isIntegerType())
3360 return integer_type_class;
3361 else if (ArgTy->isPointerType())
3362 return pointer_type_class;
3363 else if (ArgTy->isReferenceType())
3364 return reference_type_class;
3365 else if (ArgTy->isRealType())
3366 return real_type_class;
3367 else if (ArgTy->isComplexType())
3368 return complex_type_class;
3369 else if (ArgTy->isFunctionType())
3370 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00003371 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00003372 return record_type_class;
3373 else if (ArgTy->isUnionType())
3374 return union_type_class;
3375 else if (ArgTy->isArrayType())
3376 return array_type_class;
3377 else if (ArgTy->isUnionType())
3378 return union_type_class;
3379 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00003380 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00003381 return -1;
3382}
3383
John McCall42c8f872010-05-10 23:27:23 +00003384/// Retrieves the "underlying object type" of the given expression,
3385/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003386QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3387 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3388 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00003389 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003390 } else if (const Expr *E = B.get<const Expr*>()) {
3391 if (isa<CompoundLiteralExpr>(E))
3392 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00003393 }
3394
3395 return QualType();
3396}
3397
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003398bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00003399 // TODO: Perhaps we should let LLVM lower this?
3400 LValue Base;
3401 if (!EvaluatePointer(E->getArg(0), Base, Info))
3402 return false;
3403
3404 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003405 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00003406
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003407 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00003408 if (T.isNull() ||
3409 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00003410 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00003411 T->isVariablyModifiedType() ||
3412 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00003413 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00003414
3415 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3416 CharUnits Offset = Base.getLValueOffset();
3417
3418 if (!Offset.isNegative() && Offset <= Size)
3419 Size -= Offset;
3420 else
3421 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003422 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00003423}
3424
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003425bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003426 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00003427 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003428 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003429
3430 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00003431 if (TryEvaluateBuiltinObjectSize(E))
3432 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00003433
Eric Christopherb2aaf512010-01-19 22:58:35 +00003434 // If evaluating the argument has side-effects we can't determine
3435 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00003436 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003437 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00003438 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003439 return Success(0, E);
3440 }
Mike Stumpc4c90452009-10-27 22:09:17 +00003441
Richard Smithf48fdb02011-12-09 22:58:01 +00003442 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003443 }
3444
Chris Lattner019f4e82008-10-06 05:28:25 +00003445 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003446 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00003447
Richard Smithe052d462011-12-09 02:04:48 +00003448 case Builtin::BI__builtin_constant_p: {
3449 const Expr *Arg = E->getArg(0);
3450 QualType ArgType = Arg->getType();
3451 // __builtin_constant_p always has one operand. The rules which gcc follows
3452 // are not precisely documented, but are as follows:
3453 //
3454 // - If the operand is of integral, floating, complex or enumeration type,
3455 // and can be folded to a known value of that type, it returns 1.
3456 // - If the operand and can be folded to a pointer to the first character
3457 // of a string literal (or such a pointer cast to an integral type), it
3458 // returns 1.
3459 //
3460 // Otherwise, it returns 0.
3461 //
3462 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3463 // its support for this does not currently work.
3464 int IsConstant = 0;
3465 if (ArgType->isIntegralOrEnumerationType()) {
3466 // Note, a pointer cast to an integral type is only a constant if it is
3467 // a pointer to the first character of a string literal.
3468 Expr::EvalResult Result;
3469 if (Arg->EvaluateAsRValue(Result, Info.Ctx) && !Result.HasSideEffects) {
3470 APValue &V = Result.Val;
3471 if (V.getKind() == APValue::LValue) {
3472 if (const Expr *E = V.getLValueBase().dyn_cast<const Expr*>())
3473 IsConstant = isa<StringLiteral>(E) && V.getLValueOffset().isZero();
3474 } else {
3475 IsConstant = 1;
3476 }
3477 }
3478 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3479 IsConstant = Arg->isEvaluatable(Info.Ctx);
3480 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3481 LValue LV;
3482 // Use a separate EvalInfo: ignore constexpr parameter and 'this' bindings
3483 // during the check.
3484 Expr::EvalStatus Status;
3485 EvalInfo SubInfo(Info.Ctx, Status);
3486 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, SubInfo)
3487 : EvaluatePointer(Arg, LV, SubInfo)) &&
3488 !Status.HasSideEffects)
3489 if (const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>())
3490 IsConstant = isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3491 }
3492
3493 return Success(IsConstant, E);
3494 }
Chris Lattner21fb98e2009-09-23 06:06:36 +00003495 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003496 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003497 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00003498 return Success(Operand, E);
3499 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00003500
3501 case Builtin::BI__builtin_expect:
3502 return Visit(E->getArg(0));
Douglas Gregor5726d402010-09-10 06:27:15 +00003503
3504 case Builtin::BIstrlen:
3505 case Builtin::BI__builtin_strlen:
3506 // As an extension, we support strlen() and __builtin_strlen() as constant
3507 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003508 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00003509 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
3510 // The string literal may have embedded null characters. Find the first
3511 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003512 StringRef Str = S->getString();
3513 StringRef::size_type Pos = Str.find(0);
3514 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00003515 Str = Str.substr(0, Pos);
3516
3517 return Success(Str.size(), E);
3518 }
3519
Richard Smithf48fdb02011-12-09 22:58:01 +00003520 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00003521
3522 case Builtin::BI__atomic_is_lock_free: {
3523 APSInt SizeVal;
3524 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
3525 return false;
3526
3527 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
3528 // of two less than the maximum inline atomic width, we know it is
3529 // lock-free. If the size isn't a power of two, or greater than the
3530 // maximum alignment where we promote atomics, we know it is not lock-free
3531 // (at least not in the sense of atomic_is_lock_free). Otherwise,
3532 // the answer can only be determined at runtime; for example, 16-byte
3533 // atomics have lock-free implementations on some, but not all,
3534 // x86-64 processors.
3535
3536 // Check power-of-two.
3537 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
3538 if (!Size.isPowerOfTwo())
3539#if 0
3540 // FIXME: Suppress this folding until the ABI for the promotion width
3541 // settles.
3542 return Success(0, E);
3543#else
Richard Smithf48fdb02011-12-09 22:58:01 +00003544 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00003545#endif
3546
3547#if 0
3548 // Check against promotion width.
3549 // FIXME: Suppress this folding until the ABI for the promotion width
3550 // settles.
3551 unsigned PromoteWidthBits =
3552 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
3553 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
3554 return Success(0, E);
3555#endif
3556
3557 // Check against inlining width.
3558 unsigned InlineWidthBits =
3559 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
3560 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
3561 return Success(1, E);
3562
Richard Smithf48fdb02011-12-09 22:58:01 +00003563 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00003564 }
Chris Lattner019f4e82008-10-06 05:28:25 +00003565 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00003566}
Anders Carlsson650c92f2008-07-08 15:34:11 +00003567
Richard Smith625b8072011-10-31 01:37:14 +00003568static bool HasSameBase(const LValue &A, const LValue &B) {
3569 if (!A.getLValueBase())
3570 return !B.getLValueBase();
3571 if (!B.getLValueBase())
3572 return false;
3573
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003574 if (A.getLValueBase().getOpaqueValue() !=
3575 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00003576 const Decl *ADecl = GetLValueBaseDecl(A);
3577 if (!ADecl)
3578 return false;
3579 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00003580 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00003581 return false;
3582 }
3583
3584 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith177dce72011-11-01 16:57:24 +00003585 A.getLValueFrame() == B.getLValueFrame();
Richard Smith625b8072011-10-31 01:37:14 +00003586}
3587
Chris Lattnerb542afe2008-07-11 19:10:17 +00003588bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00003589 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00003590 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00003591
John McCall2de56d12010-08-25 11:45:40 +00003592 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00003593 VisitIgnoredValue(E->getLHS());
3594 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00003595 }
3596
3597 if (E->isLogicalOp()) {
3598 // These need to be handled specially because the operands aren't
3599 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00003600 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00003601
Richard Smithc49bd112011-10-28 17:51:58 +00003602 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00003603 // We were able to evaluate the LHS, see if we can get away with not
3604 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00003605 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003606 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003607
Richard Smithc49bd112011-10-28 17:51:58 +00003608 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00003609 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00003610 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003611 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00003612 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003613 }
3614 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00003615 // FIXME: If both evaluations fail, we should produce the diagnostic from
3616 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
3617 // less clear how to diagnose this.
Richard Smithc49bd112011-10-28 17:51:58 +00003618 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003619 // We can't evaluate the LHS; however, sometimes the result
3620 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf48fdb02011-12-09 22:58:01 +00003621 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003622 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00003623 // must have had side effects.
Richard Smith1e12c592011-10-16 21:26:27 +00003624 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00003625
3626 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003627 }
3628 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00003629 }
Eli Friedmana6afa762008-11-13 06:09:17 +00003630
Eli Friedmana6afa762008-11-13 06:09:17 +00003631 return false;
3632 }
3633
Anders Carlsson286f85e2008-11-16 07:17:21 +00003634 QualType LHSTy = E->getLHS()->getType();
3635 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00003636
3637 if (LHSTy->isAnyComplexType()) {
3638 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00003639 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00003640
3641 if (!EvaluateComplex(E->getLHS(), LHS, Info))
3642 return false;
3643
3644 if (!EvaluateComplex(E->getRHS(), RHS, Info))
3645 return false;
3646
3647 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003648 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00003649 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00003650 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00003651 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
3652
John McCall2de56d12010-08-25 11:45:40 +00003653 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00003654 return Success((CR_r == APFloat::cmpEqual &&
3655 CR_i == APFloat::cmpEqual), E);
3656 else {
John McCall2de56d12010-08-25 11:45:40 +00003657 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00003658 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00003659 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00003660 CR_r == APFloat::cmpLessThan ||
3661 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00003662 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00003663 CR_i == APFloat::cmpLessThan ||
3664 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00003665 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00003666 } else {
John McCall2de56d12010-08-25 11:45:40 +00003667 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00003668 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
3669 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
3670 else {
John McCall2de56d12010-08-25 11:45:40 +00003671 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00003672 "Invalid compex comparison.");
3673 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
3674 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
3675 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00003676 }
3677 }
Mike Stump1eb44332009-09-09 15:08:12 +00003678
Anders Carlsson286f85e2008-11-16 07:17:21 +00003679 if (LHSTy->isRealFloatingType() &&
3680 RHSTy->isRealFloatingType()) {
3681 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00003682
Anders Carlsson286f85e2008-11-16 07:17:21 +00003683 if (!EvaluateFloat(E->getRHS(), RHS, Info))
3684 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003685
Anders Carlsson286f85e2008-11-16 07:17:21 +00003686 if (!EvaluateFloat(E->getLHS(), LHS, Info))
3687 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003688
Anders Carlsson286f85e2008-11-16 07:17:21 +00003689 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00003690
Anders Carlsson286f85e2008-11-16 07:17:21 +00003691 switch (E->getOpcode()) {
3692 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00003693 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00003694 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003695 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00003696 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003697 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00003698 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003699 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00003700 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00003701 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00003702 E);
John McCall2de56d12010-08-25 11:45:40 +00003703 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003704 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00003705 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00003706 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00003707 || CR == APFloat::cmpLessThan
3708 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00003709 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00003710 }
Mike Stump1eb44332009-09-09 15:08:12 +00003711
Eli Friedmanad02d7d2009-04-28 19:17:36 +00003712 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00003713 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00003714 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00003715 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
3716 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00003717
John McCallefdb83e2010-05-07 21:00:08 +00003718 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00003719 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
3720 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00003721
Richard Smith625b8072011-10-31 01:37:14 +00003722 // Reject differing bases from the normal codepath; we special-case
3723 // comparisons to null.
3724 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith9e36b532011-10-31 05:11:32 +00003725 // Inequalities and subtractions between unrelated pointers have
3726 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00003727 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00003728 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00003729 // A constant address may compare equal to the address of a symbol.
3730 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00003731 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00003732 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
3733 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003734 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00003735 // It's implementation-defined whether distinct literals will have
Eli Friedmanc45061b2011-10-31 22:54:30 +00003736 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smith74f46342011-11-04 01:10:57 +00003737 // distinct. However, we do know that the address of a literal will be
3738 // non-null.
3739 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
3740 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00003741 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00003742 // We can't tell whether weak symbols will end up pointing to the same
3743 // object.
3744 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00003745 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00003746 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00003747 // (Note that clang defaults to -fmerge-all-constants, which can
3748 // lead to inconsistent results for comparisons involving the address
3749 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00003750 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00003751 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00003752
Richard Smithcc5d4f62011-11-07 09:22:26 +00003753 // FIXME: Implement the C++11 restrictions:
3754 // - Pointer subtractions must be on elements of the same array.
3755 // - Pointer comparisons must be between members with the same access.
3756
John McCall2de56d12010-08-25 11:45:40 +00003757 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00003758 QualType Type = E->getLHS()->getType();
3759 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00003760
Richard Smith180f4792011-11-10 06:34:14 +00003761 CharUnits ElementSize;
3762 if (!HandleSizeof(Info, ElementType, ElementSize))
3763 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00003764
Richard Smith180f4792011-11-10 06:34:14 +00003765 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dycka7305832010-01-15 12:37:54 +00003766 RHSValue.getLValueOffset();
3767 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00003768 }
Richard Smith625b8072011-10-31 01:37:14 +00003769
3770 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
3771 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
3772 switch (E->getOpcode()) {
3773 default: llvm_unreachable("missing comparison operator");
3774 case BO_LT: return Success(LHSOffset < RHSOffset, E);
3775 case BO_GT: return Success(LHSOffset > RHSOffset, E);
3776 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
3777 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
3778 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
3779 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00003780 }
Anders Carlsson3068d112008-11-16 19:01:22 +00003781 }
3782 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003783 if (!LHSTy->isIntegralOrEnumerationType() ||
3784 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003785 // We can't continue from here for non-integral types.
3786 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00003787 }
3788
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003789 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00003790 CCValue LHSVal;
Richard Smithc49bd112011-10-28 17:51:58 +00003791 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003792 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00003793
Richard Smithc49bd112011-10-28 17:51:58 +00003794 if (!Visit(E->getRHS()))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003795 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00003796 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00003797
3798 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00003799 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00003800 CharUnits AdditionalOffset = CharUnits::fromQuantity(
3801 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00003802 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00003803 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00003804 else
Richard Smith47a1eed2011-10-29 20:57:55 +00003805 LHSVal.getLValueOffset() -= AdditionalOffset;
3806 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00003807 return true;
3808 }
3809
3810 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00003811 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00003812 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003813 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
3814 LHSVal.getInt().getZExtValue());
3815 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00003816 return true;
3817 }
3818
3819 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00003820 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00003821 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00003822
Richard Smithc49bd112011-10-28 17:51:58 +00003823 APSInt &LHS = LHSVal.getInt();
3824 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00003825
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003826 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00003827 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00003828 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00003829 case BO_Mul: return Success(LHS * RHS, E);
3830 case BO_Add: return Success(LHS + RHS, E);
3831 case BO_Sub: return Success(LHS - RHS, E);
3832 case BO_And: return Success(LHS & RHS, E);
3833 case BO_Xor: return Success(LHS ^ RHS, E);
3834 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00003835 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00003836 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00003837 return Error(E, diag::note_expr_divide_by_zero);
Richard Smithc49bd112011-10-28 17:51:58 +00003838 return Success(LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00003839 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00003840 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00003841 return Error(E, diag::note_expr_divide_by_zero);
Richard Smithc49bd112011-10-28 17:51:58 +00003842 return Success(LHS % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00003843 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00003844 // During constant-folding, a negative shift is an opposite shift.
3845 if (RHS.isSigned() && RHS.isNegative()) {
3846 RHS = -RHS;
3847 goto shift_right;
3848 }
3849
3850 shift_left:
3851 unsigned SA
Richard Smithc49bd112011-10-28 17:51:58 +00003852 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3853 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003854 }
John McCall2de56d12010-08-25 11:45:40 +00003855 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00003856 // During constant-folding, a negative shift is an opposite shift.
3857 if (RHS.isSigned() && RHS.isNegative()) {
3858 RHS = -RHS;
3859 goto shift_left;
3860 }
3861
3862 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00003863 unsigned SA =
Richard Smithc49bd112011-10-28 17:51:58 +00003864 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3865 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003866 }
Mike Stump1eb44332009-09-09 15:08:12 +00003867
Richard Smithc49bd112011-10-28 17:51:58 +00003868 case BO_LT: return Success(LHS < RHS, E);
3869 case BO_GT: return Success(LHS > RHS, E);
3870 case BO_LE: return Success(LHS <= RHS, E);
3871 case BO_GE: return Success(LHS >= RHS, E);
3872 case BO_EQ: return Success(LHS == RHS, E);
3873 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00003874 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003875}
3876
Ken Dyck8b752f12010-01-27 17:10:57 +00003877CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00003878 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3879 // the result is the size of the referenced type."
3880 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3881 // result shall be the alignment of the referenced type."
3882 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
3883 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00003884
3885 // __alignof is defined to return the preferred alignment.
3886 return Info.Ctx.toCharUnitsFromBits(
3887 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00003888}
3889
Ken Dyck8b752f12010-01-27 17:10:57 +00003890CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00003891 E = E->IgnoreParens();
3892
3893 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00003894 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00003895 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00003896 return Info.Ctx.getDeclAlign(DRE->getDecl(),
3897 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00003898
Chris Lattneraf707ab2009-01-24 21:53:27 +00003899 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00003900 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
3901 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00003902
Chris Lattnere9feb472009-01-24 21:09:06 +00003903 return GetAlignOfType(E->getType());
3904}
3905
3906
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003907/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
3908/// a result as the expression's type.
3909bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
3910 const UnaryExprOrTypeTraitExpr *E) {
3911 switch(E->getKind()) {
3912 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00003913 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003914 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00003915 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003916 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00003917 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00003918
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003919 case UETT_VecStep: {
3920 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00003921
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003922 if (Ty->isVectorType()) {
3923 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00003924
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003925 // The vec_step built-in functions that take a 3-component
3926 // vector return 4. (OpenCL 1.1 spec 6.11.12)
3927 if (n == 3)
3928 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00003929
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003930 return Success(n, E);
3931 } else
3932 return Success(1, E);
3933 }
3934
3935 case UETT_SizeOf: {
3936 QualType SrcTy = E->getTypeOfArgument();
3937 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3938 // the result is the size of the referenced type."
3939 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3940 // result shall be the alignment of the referenced type."
3941 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
3942 SrcTy = Ref->getPointeeType();
3943
Richard Smith180f4792011-11-10 06:34:14 +00003944 CharUnits Sizeof;
3945 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003946 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003947 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003948 }
3949 }
3950
3951 llvm_unreachable("unknown expr/type trait");
Richard Smithf48fdb02011-12-09 22:58:01 +00003952 return Error(E);
Chris Lattnerfcee0012008-07-11 21:24:13 +00003953}
3954
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003955bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003956 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003957 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003958 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00003959 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003960 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003961 for (unsigned i = 0; i != n; ++i) {
3962 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
3963 switch (ON.getKind()) {
3964 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003965 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003966 APSInt IdxResult;
3967 if (!EvaluateInteger(Idx, IdxResult, Info))
3968 return false;
3969 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
3970 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003971 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003972 CurrentType = AT->getElementType();
3973 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
3974 Result += IdxResult.getSExtValue() * ElementSize;
3975 break;
3976 }
Richard Smithf48fdb02011-12-09 22:58:01 +00003977
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003978 case OffsetOfExpr::OffsetOfNode::Field: {
3979 FieldDecl *MemberDecl = ON.getField();
3980 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00003981 if (!RT)
3982 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003983 RecordDecl *RD = RT->getDecl();
3984 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00003985 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00003986 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00003987 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003988 CurrentType = MemberDecl->getType().getNonReferenceType();
3989 break;
3990 }
Richard Smithf48fdb02011-12-09 22:58:01 +00003991
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003992 case OffsetOfExpr::OffsetOfNode::Identifier:
3993 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00003994 return Error(OOE);
3995
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00003996 case OffsetOfExpr::OffsetOfNode::Base: {
3997 CXXBaseSpecifier *BaseSpec = ON.getBase();
3998 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00003999 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004000
4001 // Find the layout of the class whose base we are looking into.
4002 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004003 if (!RT)
4004 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004005 RecordDecl *RD = RT->getDecl();
4006 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4007
4008 // Find the base class itself.
4009 CurrentType = BaseSpec->getType();
4010 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4011 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004012 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004013
4014 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00004015 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004016 break;
4017 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004018 }
4019 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004020 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004021}
4022
Chris Lattnerb542afe2008-07-11 19:10:17 +00004023bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004024 switch (E->getOpcode()) {
4025 default:
4026 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4027 // See C99 6.6p3.
4028 return Error(E);
4029 case UO_Extension:
4030 // FIXME: Should extension allow i-c-e extension expressions in its scope?
4031 // If so, we could clear the diagnostic ID.
4032 return Visit(E->getSubExpr());
4033 case UO_Plus:
4034 // The result is just the value.
4035 return Visit(E->getSubExpr());
4036 case UO_Minus: {
4037 if (!Visit(E->getSubExpr()))
4038 return false;
4039 if (!Result.isInt()) return Error(E);
4040 return Success(-Result.getInt(), E);
4041 }
4042 case UO_Not: {
4043 if (!Visit(E->getSubExpr()))
4044 return false;
4045 if (!Result.isInt()) return Error(E);
4046 return Success(~Result.getInt(), E);
4047 }
4048 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00004049 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00004050 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00004051 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004052 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004053 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004054 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004055}
Mike Stump1eb44332009-09-09 15:08:12 +00004056
Chris Lattner732b2232008-07-12 01:15:53 +00004057/// HandleCast - This is used to evaluate implicit or explicit casts where the
4058/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004059bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4060 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00004061 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00004062 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00004063
Eli Friedman46a52322011-03-25 00:43:55 +00004064 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00004065 case CK_BaseToDerived:
4066 case CK_DerivedToBase:
4067 case CK_UncheckedDerivedToBase:
4068 case CK_Dynamic:
4069 case CK_ToUnion:
4070 case CK_ArrayToPointerDecay:
4071 case CK_FunctionToPointerDecay:
4072 case CK_NullToPointer:
4073 case CK_NullToMemberPointer:
4074 case CK_BaseToDerivedMemberPointer:
4075 case CK_DerivedToBaseMemberPointer:
4076 case CK_ConstructorConversion:
4077 case CK_IntegralToPointer:
4078 case CK_ToVoid:
4079 case CK_VectorSplat:
4080 case CK_IntegralToFloating:
4081 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00004082 case CK_CPointerToObjCPointerCast:
4083 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004084 case CK_AnyPointerToBlockPointerCast:
4085 case CK_ObjCObjectLValueCast:
4086 case CK_FloatingRealToComplex:
4087 case CK_FloatingComplexToReal:
4088 case CK_FloatingComplexCast:
4089 case CK_FloatingComplexToIntegralComplex:
4090 case CK_IntegralRealToComplex:
4091 case CK_IntegralComplexCast:
4092 case CK_IntegralComplexToFloatingComplex:
4093 llvm_unreachable("invalid cast kind for integral value");
4094
Eli Friedmane50c2972011-03-25 19:07:11 +00004095 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004096 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00004097 case CK_LValueBitCast:
4098 case CK_UserDefinedConversion:
John McCall33e56f32011-09-10 06:18:15 +00004099 case CK_ARCProduceObject:
4100 case CK_ARCConsumeObject:
4101 case CK_ARCReclaimReturnedObject:
4102 case CK_ARCExtendBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00004103 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004104
4105 case CK_LValueToRValue:
4106 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00004107 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004108
4109 case CK_MemberPointerToBoolean:
4110 case CK_PointerToBoolean:
4111 case CK_IntegralToBoolean:
4112 case CK_FloatingToBoolean:
4113 case CK_FloatingComplexToBoolean:
4114 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004115 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00004116 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00004117 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004118 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004119 }
4120
Eli Friedman46a52322011-03-25 00:43:55 +00004121 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00004122 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004123 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00004124
Eli Friedmanbe265702009-02-20 01:15:07 +00004125 if (!Result.isInt()) {
4126 // Only allow casts of lvalues if they are lossless.
4127 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
4128 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004129
Daniel Dunbardd211642009-02-19 22:24:01 +00004130 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004131 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00004132 }
Mike Stump1eb44332009-09-09 15:08:12 +00004133
Eli Friedman46a52322011-03-25 00:43:55 +00004134 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00004135 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4136
John McCallefdb83e2010-05-07 21:00:08 +00004137 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00004138 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004139 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00004140
Daniel Dunbardd211642009-02-19 22:24:01 +00004141 if (LV.getLValueBase()) {
4142 // Only allow based lvalue casts if they are lossless.
4143 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00004144 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004145
Richard Smithb755a9d2011-11-16 07:18:12 +00004146 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00004147 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00004148 return true;
4149 }
4150
Ken Dycka7305832010-01-15 12:37:54 +00004151 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
4152 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00004153 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00004154 }
Eli Friedman4efaa272008-11-12 09:44:48 +00004155
Eli Friedman46a52322011-03-25 00:43:55 +00004156 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00004157 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00004158 if (!EvaluateComplex(SubExpr, C, Info))
4159 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00004160 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00004161 }
Eli Friedman2217c872009-02-22 11:46:18 +00004162
Eli Friedman46a52322011-03-25 00:43:55 +00004163 case CK_FloatingToIntegral: {
4164 APFloat F(0.0);
4165 if (!EvaluateFloat(SubExpr, F, Info))
4166 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00004167
Richard Smithc1c5f272011-12-13 06:39:58 +00004168 APSInt Value;
4169 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
4170 return false;
4171 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00004172 }
4173 }
Mike Stump1eb44332009-09-09 15:08:12 +00004174
Eli Friedman46a52322011-03-25 00:43:55 +00004175 llvm_unreachable("unknown cast resulting in integral value");
Richard Smithf48fdb02011-12-09 22:58:01 +00004176 return Error(E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004177}
Anders Carlsson2bad1682008-07-08 14:30:00 +00004178
Eli Friedman722c7172009-02-28 03:59:05 +00004179bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4180 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004181 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004182 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4183 return false;
4184 if (!LV.isComplexInt())
4185 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004186 return Success(LV.getComplexIntReal(), E);
4187 }
4188
4189 return Visit(E->getSubExpr());
4190}
4191
Eli Friedman664a1042009-02-27 04:45:43 +00004192bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00004193 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004194 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004195 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4196 return false;
4197 if (!LV.isComplexInt())
4198 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004199 return Success(LV.getComplexIntImag(), E);
4200 }
4201
Richard Smith8327fad2011-10-24 18:44:57 +00004202 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00004203 return Success(0, E);
4204}
4205
Douglas Gregoree8aff02011-01-04 17:33:58 +00004206bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4207 return Success(E->getPackLength(), E);
4208}
4209
Sebastian Redl295995c2010-09-10 20:55:47 +00004210bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4211 return Success(E->getValue(), E);
4212}
4213
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004214//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004215// Float Evaluation
4216//===----------------------------------------------------------------------===//
4217
4218namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004219class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004220 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004221 APFloat &Result;
4222public:
4223 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004224 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004225
Richard Smith47a1eed2011-10-29 20:57:55 +00004226 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004227 Result = V.getFloat();
4228 return true;
4229 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004230
Richard Smithf10d9172011-10-11 21:43:33 +00004231 bool ValueInitialization(const Expr *E) {
4232 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4233 return true;
4234 }
4235
Chris Lattner019f4e82008-10-06 05:28:25 +00004236 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004237
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004238 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004239 bool VisitBinaryOperator(const BinaryOperator *E);
4240 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004241 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00004242
John McCallabd3a852010-05-07 22:08:54 +00004243 bool VisitUnaryReal(const UnaryOperator *E);
4244 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00004245
John McCallabd3a852010-05-07 22:08:54 +00004246 // FIXME: Missing: array subscript of vector, member of vector,
4247 // ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004248};
4249} // end anonymous namespace
4250
4251static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004252 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004253 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004254}
4255
Jay Foad4ba2a172011-01-12 09:06:06 +00004256static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00004257 QualType ResultTy,
4258 const Expr *Arg,
4259 bool SNaN,
4260 llvm::APFloat &Result) {
4261 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4262 if (!S) return false;
4263
4264 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4265
4266 llvm::APInt fill;
4267
4268 // Treat empty strings as if they were zero.
4269 if (S->getString().empty())
4270 fill = llvm::APInt(32, 0);
4271 else if (S->getString().getAsInteger(0, fill))
4272 return false;
4273
4274 if (SNaN)
4275 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
4276 else
4277 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
4278 return true;
4279}
4280
Chris Lattner019f4e82008-10-06 05:28:25 +00004281bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004282 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004283 default:
4284 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4285
Chris Lattner019f4e82008-10-06 05:28:25 +00004286 case Builtin::BI__builtin_huge_val:
4287 case Builtin::BI__builtin_huge_valf:
4288 case Builtin::BI__builtin_huge_vall:
4289 case Builtin::BI__builtin_inf:
4290 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004291 case Builtin::BI__builtin_infl: {
4292 const llvm::fltSemantics &Sem =
4293 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00004294 Result = llvm::APFloat::getInf(Sem);
4295 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004296 }
Mike Stump1eb44332009-09-09 15:08:12 +00004297
John McCalldb7b72a2010-02-28 13:00:19 +00004298 case Builtin::BI__builtin_nans:
4299 case Builtin::BI__builtin_nansf:
4300 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00004301 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4302 true, Result))
4303 return Error(E);
4304 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00004305
Chris Lattner9e621712008-10-06 06:31:58 +00004306 case Builtin::BI__builtin_nan:
4307 case Builtin::BI__builtin_nanf:
4308 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00004309 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00004310 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00004311 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4312 false, Result))
4313 return Error(E);
4314 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004315
4316 case Builtin::BI__builtin_fabs:
4317 case Builtin::BI__builtin_fabsf:
4318 case Builtin::BI__builtin_fabsl:
4319 if (!EvaluateFloat(E->getArg(0), Result, Info))
4320 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004321
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004322 if (Result.isNegative())
4323 Result.changeSign();
4324 return true;
4325
Mike Stump1eb44332009-09-09 15:08:12 +00004326 case Builtin::BI__builtin_copysign:
4327 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004328 case Builtin::BI__builtin_copysignl: {
4329 APFloat RHS(0.);
4330 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4331 !EvaluateFloat(E->getArg(1), RHS, Info))
4332 return false;
4333 Result.copySign(RHS);
4334 return true;
4335 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004336 }
4337}
4338
John McCallabd3a852010-05-07 22:08:54 +00004339bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00004340 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4341 ComplexValue CV;
4342 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4343 return false;
4344 Result = CV.FloatReal;
4345 return true;
4346 }
4347
4348 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00004349}
4350
4351bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00004352 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4353 ComplexValue CV;
4354 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4355 return false;
4356 Result = CV.FloatImag;
4357 return true;
4358 }
4359
Richard Smith8327fad2011-10-24 18:44:57 +00004360 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00004361 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4362 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00004363 return true;
4364}
4365
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004366bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004367 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004368 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004369 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00004370 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00004371 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00004372 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
4373 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004374 Result.changeSign();
4375 return true;
4376 }
4377}
Chris Lattner019f4e82008-10-06 05:28:25 +00004378
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004379bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004380 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
4381 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00004382
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004383 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004384 if (!EvaluateFloat(E->getLHS(), Result, Info))
4385 return false;
4386 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4387 return false;
4388
4389 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004390 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004391 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004392 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
4393 return true;
John McCall2de56d12010-08-25 11:45:40 +00004394 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004395 Result.add(RHS, APFloat::rmNearestTiesToEven);
4396 return true;
John McCall2de56d12010-08-25 11:45:40 +00004397 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004398 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
4399 return true;
John McCall2de56d12010-08-25 11:45:40 +00004400 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004401 Result.divide(RHS, APFloat::rmNearestTiesToEven);
4402 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004403 }
4404}
4405
4406bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
4407 Result = E->getValue();
4408 return true;
4409}
4410
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004411bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4412 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00004413
Eli Friedman2a523ee2011-03-25 00:54:52 +00004414 switch (E->getCastKind()) {
4415 default:
Richard Smithc49bd112011-10-28 17:51:58 +00004416 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00004417
4418 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004419 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00004420 return EvaluateInteger(SubExpr, IntResult, Info) &&
4421 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
4422 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00004423 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00004424
4425 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004426 if (!Visit(SubExpr))
4427 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00004428 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
4429 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00004430 }
John McCallf3ea8cf2010-11-14 08:17:51 +00004431
Eli Friedman2a523ee2011-03-25 00:54:52 +00004432 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00004433 ComplexValue V;
4434 if (!EvaluateComplex(SubExpr, V, Info))
4435 return false;
4436 Result = V.getComplexFloatReal();
4437 return true;
4438 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00004439 }
Eli Friedman4efaa272008-11-12 09:44:48 +00004440
Richard Smithf48fdb02011-12-09 22:58:01 +00004441 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004442}
4443
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004444//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004445// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004446//===----------------------------------------------------------------------===//
4447
4448namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004449class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004450 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00004451 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00004452
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004453public:
John McCallf4cf1a12010-05-07 17:22:02 +00004454 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004455 : ExprEvaluatorBaseTy(info), Result(Result) {}
4456
Richard Smith47a1eed2011-10-29 20:57:55 +00004457 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004458 Result.setFrom(V);
4459 return true;
4460 }
Mike Stump1eb44332009-09-09 15:08:12 +00004461
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004462 //===--------------------------------------------------------------------===//
4463 // Visitor Methods
4464 //===--------------------------------------------------------------------===//
4465
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004466 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump1eb44332009-09-09 15:08:12 +00004467
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004468 bool VisitCastExpr(const CastExpr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00004469
John McCallf4cf1a12010-05-07 17:22:02 +00004470 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004471 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004472 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004473};
4474} // end anonymous namespace
4475
John McCallf4cf1a12010-05-07 17:22:02 +00004476static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
4477 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004478 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004479 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004480}
4481
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004482bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
4483 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004484
4485 if (SubExpr->getType()->isRealFloatingType()) {
4486 Result.makeComplexFloat();
4487 APFloat &Imag = Result.FloatImag;
4488 if (!EvaluateFloat(SubExpr, Imag, Info))
4489 return false;
4490
4491 Result.FloatReal = APFloat(Imag.getSemantics());
4492 return true;
4493 } else {
4494 assert(SubExpr->getType()->isIntegerType() &&
4495 "Unexpected imaginary literal.");
4496
4497 Result.makeComplexInt();
4498 APSInt &Imag = Result.IntImag;
4499 if (!EvaluateInteger(SubExpr, Imag, Info))
4500 return false;
4501
4502 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
4503 return true;
4504 }
4505}
4506
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004507bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004508
John McCall8786da72010-12-14 17:51:41 +00004509 switch (E->getCastKind()) {
4510 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00004511 case CK_BaseToDerived:
4512 case CK_DerivedToBase:
4513 case CK_UncheckedDerivedToBase:
4514 case CK_Dynamic:
4515 case CK_ToUnion:
4516 case CK_ArrayToPointerDecay:
4517 case CK_FunctionToPointerDecay:
4518 case CK_NullToPointer:
4519 case CK_NullToMemberPointer:
4520 case CK_BaseToDerivedMemberPointer:
4521 case CK_DerivedToBaseMemberPointer:
4522 case CK_MemberPointerToBoolean:
4523 case CK_ConstructorConversion:
4524 case CK_IntegralToPointer:
4525 case CK_PointerToIntegral:
4526 case CK_PointerToBoolean:
4527 case CK_ToVoid:
4528 case CK_VectorSplat:
4529 case CK_IntegralCast:
4530 case CK_IntegralToBoolean:
4531 case CK_IntegralToFloating:
4532 case CK_FloatingToIntegral:
4533 case CK_FloatingToBoolean:
4534 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00004535 case CK_CPointerToObjCPointerCast:
4536 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00004537 case CK_AnyPointerToBlockPointerCast:
4538 case CK_ObjCObjectLValueCast:
4539 case CK_FloatingComplexToReal:
4540 case CK_FloatingComplexToBoolean:
4541 case CK_IntegralComplexToReal:
4542 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00004543 case CK_ARCProduceObject:
4544 case CK_ARCConsumeObject:
4545 case CK_ARCReclaimReturnedObject:
4546 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00004547 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00004548
John McCall8786da72010-12-14 17:51:41 +00004549 case CK_LValueToRValue:
4550 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00004551 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00004552
4553 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00004554 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00004555 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00004556 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00004557
4558 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004559 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00004560 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004561 return false;
4562
John McCall8786da72010-12-14 17:51:41 +00004563 Result.makeComplexFloat();
4564 Result.FloatImag = APFloat(Real.getSemantics());
4565 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004566 }
4567
John McCall8786da72010-12-14 17:51:41 +00004568 case CK_FloatingComplexCast: {
4569 if (!Visit(E->getSubExpr()))
4570 return false;
4571
4572 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4573 QualType From
4574 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4575
Richard Smithc1c5f272011-12-13 06:39:58 +00004576 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
4577 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00004578 }
4579
4580 case CK_FloatingComplexToIntegralComplex: {
4581 if (!Visit(E->getSubExpr()))
4582 return false;
4583
4584 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4585 QualType From
4586 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4587 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00004588 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
4589 To, Result.IntReal) &&
4590 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
4591 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00004592 }
4593
4594 case CK_IntegralRealToComplex: {
4595 APSInt &Real = Result.IntReal;
4596 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
4597 return false;
4598
4599 Result.makeComplexInt();
4600 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
4601 return true;
4602 }
4603
4604 case CK_IntegralComplexCast: {
4605 if (!Visit(E->getSubExpr()))
4606 return false;
4607
4608 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4609 QualType From
4610 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4611
4612 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
4613 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
4614 return true;
4615 }
4616
4617 case CK_IntegralComplexToFloatingComplex: {
4618 if (!Visit(E->getSubExpr()))
4619 return false;
4620
4621 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4622 QualType From
4623 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4624 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00004625 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
4626 To, Result.FloatReal) &&
4627 HandleIntToFloatCast(Info, E, From, Result.IntImag,
4628 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00004629 }
4630 }
4631
4632 llvm_unreachable("unknown cast resulting in complex value");
Richard Smithf48fdb02011-12-09 22:58:01 +00004633 return Error(E);
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004634}
4635
John McCallf4cf1a12010-05-07 17:22:02 +00004636bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004637 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00004638 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4639
John McCallf4cf1a12010-05-07 17:22:02 +00004640 if (!Visit(E->getLHS()))
4641 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004642
John McCallf4cf1a12010-05-07 17:22:02 +00004643 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004644 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00004645 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004646
Daniel Dunbar3f279872009-01-29 01:32:56 +00004647 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
4648 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00004649 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004650 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004651 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004652 if (Result.isComplexFloat()) {
4653 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
4654 APFloat::rmNearestTiesToEven);
4655 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
4656 APFloat::rmNearestTiesToEven);
4657 } else {
4658 Result.getComplexIntReal() += RHS.getComplexIntReal();
4659 Result.getComplexIntImag() += RHS.getComplexIntImag();
4660 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00004661 break;
John McCall2de56d12010-08-25 11:45:40 +00004662 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004663 if (Result.isComplexFloat()) {
4664 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
4665 APFloat::rmNearestTiesToEven);
4666 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
4667 APFloat::rmNearestTiesToEven);
4668 } else {
4669 Result.getComplexIntReal() -= RHS.getComplexIntReal();
4670 Result.getComplexIntImag() -= RHS.getComplexIntImag();
4671 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00004672 break;
John McCall2de56d12010-08-25 11:45:40 +00004673 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00004674 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004675 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00004676 APFloat &LHS_r = LHS.getComplexFloatReal();
4677 APFloat &LHS_i = LHS.getComplexFloatImag();
4678 APFloat &RHS_r = RHS.getComplexFloatReal();
4679 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00004680
Daniel Dunbar3f279872009-01-29 01:32:56 +00004681 APFloat Tmp = LHS_r;
4682 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4683 Result.getComplexFloatReal() = Tmp;
4684 Tmp = LHS_i;
4685 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4686 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
4687
4688 Tmp = LHS_r;
4689 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4690 Result.getComplexFloatImag() = Tmp;
4691 Tmp = LHS_i;
4692 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4693 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
4694 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00004695 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00004696 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00004697 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
4698 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00004699 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00004700 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
4701 LHS.getComplexIntImag() * RHS.getComplexIntReal());
4702 }
4703 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004704 case BO_Div:
4705 if (Result.isComplexFloat()) {
4706 ComplexValue LHS = Result;
4707 APFloat &LHS_r = LHS.getComplexFloatReal();
4708 APFloat &LHS_i = LHS.getComplexFloatImag();
4709 APFloat &RHS_r = RHS.getComplexFloatReal();
4710 APFloat &RHS_i = RHS.getComplexFloatImag();
4711 APFloat &Res_r = Result.getComplexFloatReal();
4712 APFloat &Res_i = Result.getComplexFloatImag();
4713
4714 APFloat Den = RHS_r;
4715 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4716 APFloat Tmp = RHS_i;
4717 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4718 Den.add(Tmp, APFloat::rmNearestTiesToEven);
4719
4720 Res_r = LHS_r;
4721 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4722 Tmp = LHS_i;
4723 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4724 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
4725 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
4726
4727 Res_i = LHS_i;
4728 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4729 Tmp = LHS_r;
4730 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4731 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
4732 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
4733 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00004734 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
4735 return Error(E, diag::note_expr_divide_by_zero);
4736
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004737 ComplexValue LHS = Result;
4738 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
4739 RHS.getComplexIntImag() * RHS.getComplexIntImag();
4740 Result.getComplexIntReal() =
4741 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
4742 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
4743 Result.getComplexIntImag() =
4744 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
4745 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
4746 }
4747 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00004748 }
4749
John McCallf4cf1a12010-05-07 17:22:02 +00004750 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00004751}
4752
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004753bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
4754 // Get the operand value into 'Result'.
4755 if (!Visit(E->getSubExpr()))
4756 return false;
4757
4758 switch (E->getOpcode()) {
4759 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004760 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004761 case UO_Extension:
4762 return true;
4763 case UO_Plus:
4764 // The result is always just the subexpr.
4765 return true;
4766 case UO_Minus:
4767 if (Result.isComplexFloat()) {
4768 Result.getComplexFloatReal().changeSign();
4769 Result.getComplexFloatImag().changeSign();
4770 }
4771 else {
4772 Result.getComplexIntReal() = -Result.getComplexIntReal();
4773 Result.getComplexIntImag() = -Result.getComplexIntImag();
4774 }
4775 return true;
4776 case UO_Not:
4777 if (Result.isComplexFloat())
4778 Result.getComplexFloatImag().changeSign();
4779 else
4780 Result.getComplexIntImag() = -Result.getComplexIntImag();
4781 return true;
4782 }
4783}
4784
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004785//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00004786// Void expression evaluation, primarily for a cast to void on the LHS of a
4787// comma operator
4788//===----------------------------------------------------------------------===//
4789
4790namespace {
4791class VoidExprEvaluator
4792 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
4793public:
4794 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
4795
4796 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00004797
4798 bool VisitCastExpr(const CastExpr *E) {
4799 switch (E->getCastKind()) {
4800 default:
4801 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4802 case CK_ToVoid:
4803 VisitIgnoredValue(E->getSubExpr());
4804 return true;
4805 }
4806 }
4807};
4808} // end anonymous namespace
4809
4810static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
4811 assert(E->isRValue() && E->getType()->isVoidType());
4812 return VoidExprEvaluator(Info).Visit(E);
4813}
4814
4815//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00004816// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004817//===----------------------------------------------------------------------===//
4818
Richard Smith47a1eed2011-10-29 20:57:55 +00004819static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004820 // In C, function designators are not lvalues, but we evaluate them as if they
4821 // are.
4822 if (E->isGLValue() || E->getType()->isFunctionType()) {
4823 LValue LV;
4824 if (!EvaluateLValue(E, LV, Info))
4825 return false;
4826 LV.moveInto(Result);
4827 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00004828 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00004829 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00004830 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00004831 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00004832 return false;
John McCallefdb83e2010-05-07 21:00:08 +00004833 } else if (E->getType()->hasPointerRepresentation()) {
4834 LValue LV;
4835 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00004836 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00004837 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00004838 } else if (E->getType()->isRealFloatingType()) {
4839 llvm::APFloat F(0.0);
4840 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00004841 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00004842 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00004843 } else if (E->getType()->isAnyComplexType()) {
4844 ComplexValue C;
4845 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00004846 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00004847 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00004848 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004849 MemberPtr P;
4850 if (!EvaluateMemberPointer(E, P, Info))
4851 return false;
4852 P.moveInto(Result);
4853 return true;
Richard Smith69c2c502011-11-04 05:33:44 +00004854 } else if (E->getType()->isArrayType() && E->getType()->isLiteralType()) {
Richard Smith180f4792011-11-10 06:34:14 +00004855 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004856 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00004857 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00004858 return false;
Richard Smith180f4792011-11-10 06:34:14 +00004859 Result = Info.CurrentCall->Temporaries[E];
Richard Smith69c2c502011-11-04 05:33:44 +00004860 } else if (E->getType()->isRecordType() && E->getType()->isLiteralType()) {
Richard Smith180f4792011-11-10 06:34:14 +00004861 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004862 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00004863 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
4864 return false;
4865 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00004866 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00004867 if (Info.getLangOpts().CPlusPlus0x)
4868 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
4869 << E->getType();
4870 else
4871 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00004872 if (!EvaluateVoid(E, Info))
4873 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00004874 } else if (Info.getLangOpts().CPlusPlus0x) {
4875 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
4876 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004877 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00004878 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00004879 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004880 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00004881
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00004882 return true;
4883}
4884
Richard Smith69c2c502011-11-04 05:33:44 +00004885/// EvaluateConstantExpression - Evaluate an expression as a constant expression
4886/// in-place in an APValue. In some cases, the in-place evaluation is essential,
4887/// since later initializers for an object can indirectly refer to subobjects
4888/// which were initialized earlier.
4889static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +00004890 const LValue &This, const Expr *E,
4891 CheckConstantExpressionKind CCEK) {
Richard Smith69c2c502011-11-04 05:33:44 +00004892 if (E->isRValue() && E->getType()->isLiteralType()) {
4893 // Evaluate arrays and record types in-place, so that later initializers can
4894 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00004895 if (E->getType()->isArrayType())
4896 return EvaluateArray(E, This, Result, Info);
4897 else if (E->getType()->isRecordType())
4898 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00004899 }
4900
4901 // For any other type, in-place evaluation is unimportant.
4902 CCValue CoreConstResult;
4903 return Evaluate(CoreConstResult, Info, E) &&
Richard Smithc1c5f272011-12-13 06:39:58 +00004904 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smith69c2c502011-11-04 05:33:44 +00004905}
4906
Richard Smithf48fdb02011-12-09 22:58:01 +00004907/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
4908/// lvalue-to-rvalue cast if it is an lvalue.
4909static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
4910 CCValue Value;
4911 if (!::Evaluate(Value, Info, E))
4912 return false;
4913
4914 if (E->isGLValue()) {
4915 LValue LV;
4916 LV.setFrom(Value);
4917 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
4918 return false;
4919 }
4920
4921 // Check this core constant expression is a constant expression, and if so,
4922 // convert it to one.
4923 return CheckConstantExpression(Info, E, Value, Result);
4924}
Richard Smithc49bd112011-10-28 17:51:58 +00004925
Richard Smith51f47082011-10-29 00:50:52 +00004926/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00004927/// any crazy technique (that has nothing to do with language standards) that
4928/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00004929/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
4930/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00004931bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00004932 // Fast-path evaluations of integer literals, since we sometimes see files
4933 // containing vast quantities of these.
4934 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
4935 Result.Val = APValue(APSInt(L->getValue(),
4936 L->getType()->isUnsignedIntegerType()));
4937 return true;
4938 }
4939
Richard Smith1445bba2011-11-10 03:30:42 +00004940 // FIXME: Evaluating initializers for large arrays can cause performance
4941 // problems, and we don't use such values yet. Once we have a more efficient
4942 // array representation, this should be reinstated, and used by CodeGen.
Richard Smithe24f5fc2011-11-17 22:56:20 +00004943 // The same problem affects large records.
4944 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
4945 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00004946 return false;
4947
Richard Smith180f4792011-11-10 06:34:14 +00004948 // FIXME: If this is the initializer for an lvalue, pass that in.
Richard Smithf48fdb02011-12-09 22:58:01 +00004949 EvalInfo Info(Ctx, Result);
4950 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00004951}
4952
Jay Foad4ba2a172011-01-12 09:06:06 +00004953bool Expr::EvaluateAsBooleanCondition(bool &Result,
4954 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00004955 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00004956 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith177dce72011-11-01 16:57:24 +00004957 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00004958 Result);
John McCallcd7a4452010-01-05 23:42:56 +00004959}
4960
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004961bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00004962 EvalResult ExprResult;
Richard Smith51f47082011-10-29 00:50:52 +00004963 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smithf48fdb02011-12-09 22:58:01 +00004964 !ExprResult.Val.isInt())
Richard Smithc49bd112011-10-28 17:51:58 +00004965 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004966
Richard Smithc49bd112011-10-28 17:51:58 +00004967 Result = ExprResult.Val.getInt();
4968 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004969}
4970
Jay Foad4ba2a172011-01-12 09:06:06 +00004971bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00004972 EvalInfo Info(Ctx, Result);
4973
John McCallefdb83e2010-05-07 21:00:08 +00004974 LValue LV;
Richard Smith9a17a682011-11-07 05:07:52 +00004975 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smithc1c5f272011-12-13 06:39:58 +00004976 CheckLValueConstantExpression(Info, this, LV, Result.Val,
4977 CCEK_Constant);
Eli Friedmanb2f295c2009-09-13 10:17:44 +00004978}
4979
Richard Smith099e7f62011-12-19 06:19:21 +00004980bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
4981 const VarDecl *VD,
4982 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
4983 Expr::EvalStatus EStatus;
4984 EStatus.Diag = &Notes;
4985
4986 EvalInfo InitInfo(Ctx, EStatus);
4987 InitInfo.setEvaluatingDecl(VD, Value);
4988
4989 LValue LVal;
4990 LVal.set(VD);
4991
4992 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
4993 !EStatus.HasSideEffects;
4994}
4995
Richard Smith51f47082011-10-29 00:50:52 +00004996/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
4997/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00004998bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00004999 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00005000 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00005001}
Anders Carlsson51fe9962008-11-22 21:04:56 +00005002
Jay Foad4ba2a172011-01-12 09:06:06 +00005003bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00005004 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00005005}
5006
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005007APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005008 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00005009 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00005010 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00005011 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005012 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00005013
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005014 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00005015}
John McCalld905f5a2010-05-07 05:32:02 +00005016
Abramo Bagnarae17a6432010-05-14 17:07:14 +00005017 bool Expr::EvalResult::isGlobalLValue() const {
5018 assert(Val.isLValue());
5019 return IsGlobalLValue(Val.getLValueBase());
5020 }
5021
5022
John McCalld905f5a2010-05-07 05:32:02 +00005023/// isIntegerConstantExpr - this recursive routine will test if an expression is
5024/// an integer constant expression.
5025
5026/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
5027/// comma, etc
5028///
5029/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
5030/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
5031/// cast+dereference.
5032
5033// CheckICE - This function does the fundamental ICE checking: the returned
5034// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
5035// Note that to reduce code duplication, this helper does no evaluation
5036// itself; the caller checks whether the expression is evaluatable, and
5037// in the rare cases where CheckICE actually cares about the evaluated
5038// value, it calls into Evalute.
5039//
5040// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00005041// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00005042// 1: This expression is not an ICE, but if it isn't evaluated, it's
5043// a legal subexpression for an ICE. This return value is used to handle
5044// the comma operator in C99 mode.
5045// 2: This expression is not an ICE, and is not a legal subexpression for one.
5046
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005047namespace {
5048
John McCalld905f5a2010-05-07 05:32:02 +00005049struct ICEDiag {
5050 unsigned Val;
5051 SourceLocation Loc;
5052
5053 public:
5054 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
5055 ICEDiag() : Val(0) {}
5056};
5057
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005058}
5059
5060static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00005061
5062static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
5063 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00005064 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00005065 !EVResult.Val.isInt()) {
5066 return ICEDiag(2, E->getLocStart());
5067 }
5068 return NoDiag();
5069}
5070
5071static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
5072 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00005073 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00005074 return ICEDiag(2, E->getLocStart());
5075 }
5076
5077 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00005078#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00005079#define STMT(Node, Base) case Expr::Node##Class:
5080#define EXPR(Node, Base)
5081#include "clang/AST/StmtNodes.inc"
5082 case Expr::PredefinedExprClass:
5083 case Expr::FloatingLiteralClass:
5084 case Expr::ImaginaryLiteralClass:
5085 case Expr::StringLiteralClass:
5086 case Expr::ArraySubscriptExprClass:
5087 case Expr::MemberExprClass:
5088 case Expr::CompoundAssignOperatorClass:
5089 case Expr::CompoundLiteralExprClass:
5090 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005091 case Expr::DesignatedInitExprClass:
5092 case Expr::ImplicitValueInitExprClass:
5093 case Expr::ParenListExprClass:
5094 case Expr::VAArgExprClass:
5095 case Expr::AddrLabelExprClass:
5096 case Expr::StmtExprClass:
5097 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00005098 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005099 case Expr::CXXDynamicCastExprClass:
5100 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00005101 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005102 case Expr::CXXNullPtrLiteralExprClass:
5103 case Expr::CXXThisExprClass:
5104 case Expr::CXXThrowExprClass:
5105 case Expr::CXXNewExprClass:
5106 case Expr::CXXDeleteExprClass:
5107 case Expr::CXXPseudoDestructorExprClass:
5108 case Expr::UnresolvedLookupExprClass:
5109 case Expr::DependentScopeDeclRefExprClass:
5110 case Expr::CXXConstructExprClass:
5111 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00005112 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00005113 case Expr::CXXTemporaryObjectExprClass:
5114 case Expr::CXXUnresolvedConstructExprClass:
5115 case Expr::CXXDependentScopeMemberExprClass:
5116 case Expr::UnresolvedMemberExprClass:
5117 case Expr::ObjCStringLiteralClass:
5118 case Expr::ObjCEncodeExprClass:
5119 case Expr::ObjCMessageExprClass:
5120 case Expr::ObjCSelectorExprClass:
5121 case Expr::ObjCProtocolExprClass:
5122 case Expr::ObjCIvarRefExprClass:
5123 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005124 case Expr::ObjCIsaExprClass:
5125 case Expr::ShuffleVectorExprClass:
5126 case Expr::BlockExprClass:
5127 case Expr::BlockDeclRefExprClass:
5128 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00005129 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00005130 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00005131 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00005132 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005133 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00005134 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00005135 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00005136 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005137 case Expr::InitListExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005138 return ICEDiag(2, E->getLocStart());
5139
Douglas Gregoree8aff02011-01-04 17:33:58 +00005140 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005141 case Expr::GNUNullExprClass:
5142 // GCC considers the GNU __null value to be an integral constant expression.
5143 return NoDiag();
5144
John McCall91a57552011-07-15 05:09:51 +00005145 case Expr::SubstNonTypeTemplateParmExprClass:
5146 return
5147 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
5148
John McCalld905f5a2010-05-07 05:32:02 +00005149 case Expr::ParenExprClass:
5150 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00005151 case Expr::GenericSelectionExprClass:
5152 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005153 case Expr::IntegerLiteralClass:
5154 case Expr::CharacterLiteralClass:
5155 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00005156 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005157 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00005158 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00005159 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00005160 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00005161 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005162 return NoDiag();
5163 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00005164 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00005165 // C99 6.6/3 allows function calls within unevaluated subexpressions of
5166 // constant expressions, but they can never be ICEs because an ICE cannot
5167 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00005168 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00005169 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00005170 return CheckEvalInICE(E, Ctx);
5171 return ICEDiag(2, E->getLocStart());
5172 }
5173 case Expr::DeclRefExprClass:
5174 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
5175 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00005176 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00005177 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
5178
5179 // Parameter variables are never constants. Without this check,
5180 // getAnyInitializer() can find a default argument, which leads
5181 // to chaos.
5182 if (isa<ParmVarDecl>(D))
5183 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5184
5185 // C++ 7.1.5.1p2
5186 // A variable of non-volatile const-qualified integral or enumeration
5187 // type initialized by an ICE can be used in ICEs.
5188 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00005189 if (!Dcl->getType()->isIntegralOrEnumerationType())
5190 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5191
Richard Smith099e7f62011-12-19 06:19:21 +00005192 const VarDecl *VD;
5193 // Look for a declaration of this variable that has an initializer, and
5194 // check whether it is an ICE.
5195 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
5196 return NoDiag();
5197 else
5198 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00005199 }
5200 }
5201 return ICEDiag(2, E->getLocStart());
5202 case Expr::UnaryOperatorClass: {
5203 const UnaryOperator *Exp = cast<UnaryOperator>(E);
5204 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005205 case UO_PostInc:
5206 case UO_PostDec:
5207 case UO_PreInc:
5208 case UO_PreDec:
5209 case UO_AddrOf:
5210 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00005211 // C99 6.6/3 allows increment and decrement within unevaluated
5212 // subexpressions of constant expressions, but they can never be ICEs
5213 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00005214 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00005215 case UO_Extension:
5216 case UO_LNot:
5217 case UO_Plus:
5218 case UO_Minus:
5219 case UO_Not:
5220 case UO_Real:
5221 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00005222 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005223 }
5224
5225 // OffsetOf falls through here.
5226 }
5227 case Expr::OffsetOfExprClass: {
5228 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00005229 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00005230 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00005231 // compliance: we should warn earlier for offsetof expressions with
5232 // array subscripts that aren't ICEs, and if the array subscripts
5233 // are ICEs, the value of the offsetof must be an integer constant.
5234 return CheckEvalInICE(E, Ctx);
5235 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005236 case Expr::UnaryExprOrTypeTraitExprClass: {
5237 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
5238 if ((Exp->getKind() == UETT_SizeOf) &&
5239 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00005240 return ICEDiag(2, E->getLocStart());
5241 return NoDiag();
5242 }
5243 case Expr::BinaryOperatorClass: {
5244 const BinaryOperator *Exp = cast<BinaryOperator>(E);
5245 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005246 case BO_PtrMemD:
5247 case BO_PtrMemI:
5248 case BO_Assign:
5249 case BO_MulAssign:
5250 case BO_DivAssign:
5251 case BO_RemAssign:
5252 case BO_AddAssign:
5253 case BO_SubAssign:
5254 case BO_ShlAssign:
5255 case BO_ShrAssign:
5256 case BO_AndAssign:
5257 case BO_XorAssign:
5258 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00005259 // C99 6.6/3 allows assignments within unevaluated subexpressions of
5260 // constant expressions, but they can never be ICEs because an ICE cannot
5261 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00005262 return ICEDiag(2, E->getLocStart());
5263
John McCall2de56d12010-08-25 11:45:40 +00005264 case BO_Mul:
5265 case BO_Div:
5266 case BO_Rem:
5267 case BO_Add:
5268 case BO_Sub:
5269 case BO_Shl:
5270 case BO_Shr:
5271 case BO_LT:
5272 case BO_GT:
5273 case BO_LE:
5274 case BO_GE:
5275 case BO_EQ:
5276 case BO_NE:
5277 case BO_And:
5278 case BO_Xor:
5279 case BO_Or:
5280 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00005281 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5282 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00005283 if (Exp->getOpcode() == BO_Div ||
5284 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00005285 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00005286 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00005287 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005288 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005289 if (REval == 0)
5290 return ICEDiag(1, E->getLocStart());
5291 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005292 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005293 if (LEval.isMinSignedValue())
5294 return ICEDiag(1, E->getLocStart());
5295 }
5296 }
5297 }
John McCall2de56d12010-08-25 11:45:40 +00005298 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00005299 if (Ctx.getLangOptions().C99) {
5300 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
5301 // if it isn't evaluated.
5302 if (LHSResult.Val == 0 && RHSResult.Val == 0)
5303 return ICEDiag(1, E->getLocStart());
5304 } else {
5305 // In both C89 and C++, commas in ICEs are illegal.
5306 return ICEDiag(2, E->getLocStart());
5307 }
5308 }
5309 if (LHSResult.Val >= RHSResult.Val)
5310 return LHSResult;
5311 return RHSResult;
5312 }
John McCall2de56d12010-08-25 11:45:40 +00005313 case BO_LAnd:
5314 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00005315 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5316 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
5317 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
5318 // Rare case where the RHS has a comma "side-effect"; we need
5319 // to actually check the condition to see whether the side
5320 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00005321 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005322 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00005323 return RHSResult;
5324 return NoDiag();
5325 }
5326
5327 if (LHSResult.Val >= RHSResult.Val)
5328 return LHSResult;
5329 return RHSResult;
5330 }
5331 }
5332 }
5333 case Expr::ImplicitCastExprClass:
5334 case Expr::CStyleCastExprClass:
5335 case Expr::CXXFunctionalCastExprClass:
5336 case Expr::CXXStaticCastExprClass:
5337 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00005338 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005339 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00005340 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00005341 if (isa<ExplicitCastExpr>(E)) {
5342 if (const FloatingLiteral *FL
5343 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
5344 unsigned DestWidth = Ctx.getIntWidth(E->getType());
5345 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
5346 APSInt IgnoredVal(DestWidth, !DestSigned);
5347 bool Ignored;
5348 // If the value does not fit in the destination type, the behavior is
5349 // undefined, so we are not required to treat it as a constant
5350 // expression.
5351 if (FL->getValue().convertToInteger(IgnoredVal,
5352 llvm::APFloat::rmTowardZero,
5353 &Ignored) & APFloat::opInvalidOp)
5354 return ICEDiag(2, E->getLocStart());
5355 return NoDiag();
5356 }
5357 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00005358 switch (cast<CastExpr>(E)->getCastKind()) {
5359 case CK_LValueToRValue:
5360 case CK_NoOp:
5361 case CK_IntegralToBoolean:
5362 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00005363 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00005364 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00005365 return ICEDiag(2, E->getLocStart());
5366 }
John McCalld905f5a2010-05-07 05:32:02 +00005367 }
John McCall56ca35d2011-02-17 10:25:35 +00005368 case Expr::BinaryConditionalOperatorClass: {
5369 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
5370 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
5371 if (CommonResult.Val == 2) return CommonResult;
5372 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
5373 if (FalseResult.Val == 2) return FalseResult;
5374 if (CommonResult.Val == 1) return CommonResult;
5375 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005376 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00005377 return FalseResult;
5378 }
John McCalld905f5a2010-05-07 05:32:02 +00005379 case Expr::ConditionalOperatorClass: {
5380 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
5381 // If the condition (ignoring parens) is a __builtin_constant_p call,
5382 // then only the true side is actually considered in an integer constant
5383 // expression, and it is fully evaluated. This is an important GNU
5384 // extension. See GCC PR38377 for discussion.
5385 if (const CallExpr *CallCE
5386 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith180f4792011-11-10 06:34:14 +00005387 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p) {
John McCalld905f5a2010-05-07 05:32:02 +00005388 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00005389 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00005390 !EVResult.Val.isInt()) {
5391 return ICEDiag(2, E->getLocStart());
5392 }
5393 return NoDiag();
5394 }
5395 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005396 if (CondResult.Val == 2)
5397 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00005398
Richard Smithf48fdb02011-12-09 22:58:01 +00005399 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
5400 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00005401
John McCalld905f5a2010-05-07 05:32:02 +00005402 if (TrueResult.Val == 2)
5403 return TrueResult;
5404 if (FalseResult.Val == 2)
5405 return FalseResult;
5406 if (CondResult.Val == 1)
5407 return CondResult;
5408 if (TrueResult.Val == 0 && FalseResult.Val == 0)
5409 return NoDiag();
5410 // Rare case where the diagnostics depend on which side is evaluated
5411 // Note that if we get here, CondResult is 0, and at least one of
5412 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005413 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00005414 return FalseResult;
5415 }
5416 return TrueResult;
5417 }
5418 case Expr::CXXDefaultArgExprClass:
5419 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
5420 case Expr::ChooseExprClass: {
5421 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
5422 }
5423 }
5424
5425 // Silence a GCC warning
5426 return ICEDiag(2, E->getLocStart());
5427}
5428
Richard Smithf48fdb02011-12-09 22:58:01 +00005429/// Evaluate an expression as a C++11 integral constant expression.
5430static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
5431 const Expr *E,
5432 llvm::APSInt *Value,
5433 SourceLocation *Loc) {
5434 if (!E->getType()->isIntegralOrEnumerationType()) {
5435 if (Loc) *Loc = E->getExprLoc();
5436 return false;
5437 }
5438
5439 Expr::EvalResult Result;
Richard Smithdd1f29b2011-12-12 09:28:41 +00005440 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
5441 Result.Diag = &Diags;
5442 EvalInfo Info(Ctx, Result);
5443
5444 bool IsICE = EvaluateAsRValue(Info, E, Result.Val);
5445 if (!Diags.empty()) {
5446 IsICE = false;
5447 if (Loc) *Loc = Diags[0].first;
5448 } else if (!IsICE && Loc) {
5449 *Loc = E->getExprLoc();
Richard Smithf48fdb02011-12-09 22:58:01 +00005450 }
Richard Smithdd1f29b2011-12-12 09:28:41 +00005451
5452 if (!IsICE)
5453 return false;
5454
5455 assert(Result.Val.isInt() && "pointer cast to int is not an ICE");
5456 if (Value) *Value = Result.Val.getInt();
5457 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00005458}
5459
Richard Smithdd1f29b2011-12-12 09:28:41 +00005460bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00005461 if (Ctx.getLangOptions().CPlusPlus0x)
5462 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
5463
John McCalld905f5a2010-05-07 05:32:02 +00005464 ICEDiag d = CheckICE(this, Ctx);
5465 if (d.Val != 0) {
5466 if (Loc) *Loc = d.Loc;
5467 return false;
5468 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005469 return true;
5470}
5471
5472bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
5473 SourceLocation *Loc, bool isEvaluated) const {
5474 if (Ctx.getLangOptions().CPlusPlus0x)
5475 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
5476
5477 if (!isIntegerConstantExpr(Ctx, Loc))
5478 return false;
5479 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00005480 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00005481 return true;
5482}