blob: 31b211eff6cedb6d6c29dbe26586d5fc2d856777 [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 Smithc1c5f272011-12-13 06:39:58 +0000347 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
348 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000349 // If we have a prior diagnostic, it will be noting that the expression
350 // isn't a constant expression. This diagnostic is more important.
351 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000352 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000353 unsigned CallStackNotes = CallStackDepth - 1;
354 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
355 if (Limit)
356 CallStackNotes = std::min(CallStackNotes, Limit + 1);
357
Richard Smithc1c5f272011-12-13 06:39:58 +0000358 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000359 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000360 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
361 addDiag(Loc, DiagId);
362 addCallStack(Limit);
363 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000364 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000365 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000366 return OptionalDiagnostic();
367 }
368
369 /// Diagnose that the evaluation does not produce a C++11 core constant
370 /// expression.
Richard Smithc1c5f272011-12-13 06:39:58 +0000371 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId,
372 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000373 // Don't override a previous diagnostic.
374 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
375 return OptionalDiagnostic();
Richard Smithc1c5f272011-12-13 06:39:58 +0000376 return Diag(Loc, DiagId, ExtraNotes);
377 }
378
379 /// Add a note to a prior diagnostic.
380 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
381 if (!HasActiveDiagnostic)
382 return OptionalDiagnostic();
383 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000384 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000385 };
Richard Smith08d6e032011-12-16 19:06:07 +0000386}
Richard Smithbd552ef2011-10-31 05:52:43 +0000387
Richard Smith08d6e032011-12-16 19:06:07 +0000388CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
389 const FunctionDecl *Callee, const LValue *This,
390 const CCValue *Arguments)
391 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
392 This(This), Arguments(Arguments) {
393 Info.CurrentCall = this;
394 ++Info.CallStackDepth;
395}
396
397CallStackFrame::~CallStackFrame() {
398 assert(Info.CurrentCall == this && "calls retired out of order");
399 --Info.CallStackDepth;
400 Info.CurrentCall = Caller;
401}
402
403/// Produce a string describing the given constexpr call.
404static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
405 unsigned ArgIndex = 0;
406 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
407 !isa<CXXConstructorDecl>(Frame->Callee);
408
409 if (!IsMemberCall)
410 Out << *Frame->Callee << '(';
411
412 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
413 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
414 if (ArgIndex > IsMemberCall)
415 Out << ", ";
416
417 const ParmVarDecl *Param = *I;
418 const CCValue &Arg = Frame->Arguments[ArgIndex];
419 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
420 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
421 else {
422 // Deliberately slice off the frame to form an APValue we can print.
423 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
424 Arg.getLValueDesignator().Entries,
425 Arg.getLValueDesignator().OnePastTheEnd);
426 Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
427 }
428
429 if (ArgIndex == 0 && IsMemberCall)
430 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000431 }
432
Richard Smith08d6e032011-12-16 19:06:07 +0000433 Out << ')';
434}
435
436void EvalInfo::addCallStack(unsigned Limit) {
437 // Determine which calls to skip, if any.
438 unsigned ActiveCalls = CallStackDepth - 1;
439 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
440 if (Limit && Limit < ActiveCalls) {
441 SkipStart = Limit / 2 + Limit % 2;
442 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000443 }
444
Richard Smith08d6e032011-12-16 19:06:07 +0000445 // Walk the call stack and add the diagnostics.
446 unsigned CallIdx = 0;
447 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
448 Frame = Frame->Caller, ++CallIdx) {
449 // Skip this call?
450 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
451 if (CallIdx == SkipStart) {
452 // Note that we're skipping calls.
453 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
454 << unsigned(ActiveCalls - Limit);
455 }
456 continue;
457 }
458
459 llvm::SmallVector<char, 128> Buffer;
460 llvm::raw_svector_ostream Out(Buffer);
461 describeCall(Frame, Out);
462 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
463 }
464}
465
466namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000467 struct ComplexValue {
468 private:
469 bool IsInt;
470
471 public:
472 APSInt IntReal, IntImag;
473 APFloat FloatReal, FloatImag;
474
475 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
476
477 void makeComplexFloat() { IsInt = false; }
478 bool isComplexFloat() const { return !IsInt; }
479 APFloat &getComplexFloatReal() { return FloatReal; }
480 APFloat &getComplexFloatImag() { return FloatImag; }
481
482 void makeComplexInt() { IsInt = true; }
483 bool isComplexInt() const { return IsInt; }
484 APSInt &getComplexIntReal() { return IntReal; }
485 APSInt &getComplexIntImag() { return IntImag; }
486
Richard Smith47a1eed2011-10-29 20:57:55 +0000487 void moveInto(CCValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000488 if (isComplexFloat())
Richard Smith47a1eed2011-10-29 20:57:55 +0000489 v = CCValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000490 else
Richard Smith47a1eed2011-10-29 20:57:55 +0000491 v = CCValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000492 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000493 void setFrom(const CCValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000494 assert(v.isComplexFloat() || v.isComplexInt());
495 if (v.isComplexFloat()) {
496 makeComplexFloat();
497 FloatReal = v.getComplexFloatReal();
498 FloatImag = v.getComplexFloatImag();
499 } else {
500 makeComplexInt();
501 IntReal = v.getComplexIntReal();
502 IntImag = v.getComplexIntImag();
503 }
504 }
John McCallf4cf1a12010-05-07 17:22:02 +0000505 };
John McCallefdb83e2010-05-07 21:00:08 +0000506
507 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000508 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000509 CharUnits Offset;
Richard Smith177dce72011-11-01 16:57:24 +0000510 CallStackFrame *Frame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000511 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000512
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000513 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000514 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000515 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith177dce72011-11-01 16:57:24 +0000516 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000517 SubobjectDesignator &getLValueDesignator() { return Designator; }
518 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000519
Richard Smith47a1eed2011-10-29 20:57:55 +0000520 void moveInto(CCValue &V) const {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000521 V = CCValue(Base, Offset, Frame, Designator);
John McCallefdb83e2010-05-07 21:00:08 +0000522 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000523 void setFrom(const CCValue &V) {
524 assert(V.isLValue());
525 Base = V.getLValueBase();
526 Offset = V.getLValueOffset();
Richard Smith177dce72011-11-01 16:57:24 +0000527 Frame = V.getLValueFrame();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000528 Designator = V.getLValueDesignator();
529 }
530
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000531 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
532 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000533 Offset = CharUnits::Zero();
534 Frame = F;
535 Designator = SubobjectDesignator();
John McCall56ca35d2011-02-17 10:25:35 +0000536 }
John McCallefdb83e2010-05-07 21:00:08 +0000537 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000538
539 struct MemberPtr {
540 MemberPtr() {}
541 explicit MemberPtr(const ValueDecl *Decl) :
542 DeclAndIsDerivedMember(Decl, false), Path() {}
543
544 /// The member or (direct or indirect) field referred to by this member
545 /// pointer, or 0 if this is a null member pointer.
546 const ValueDecl *getDecl() const {
547 return DeclAndIsDerivedMember.getPointer();
548 }
549 /// Is this actually a member of some type derived from the relevant class?
550 bool isDerivedMember() const {
551 return DeclAndIsDerivedMember.getInt();
552 }
553 /// Get the class which the declaration actually lives in.
554 const CXXRecordDecl *getContainingRecord() const {
555 return cast<CXXRecordDecl>(
556 DeclAndIsDerivedMember.getPointer()->getDeclContext());
557 }
558
559 void moveInto(CCValue &V) const {
560 V = CCValue(getDecl(), isDerivedMember(), Path);
561 }
562 void setFrom(const CCValue &V) {
563 assert(V.isMemberPointer());
564 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
565 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
566 Path.clear();
567 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
568 Path.insert(Path.end(), P.begin(), P.end());
569 }
570
571 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
572 /// whether the member is a member of some class derived from the class type
573 /// of the member pointer.
574 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
575 /// Path - The path of base/derived classes from the member declaration's
576 /// class (exclusive) to the class type of the member pointer (inclusive).
577 SmallVector<const CXXRecordDecl*, 4> Path;
578
579 /// Perform a cast towards the class of the Decl (either up or down the
580 /// hierarchy).
581 bool castBack(const CXXRecordDecl *Class) {
582 assert(!Path.empty());
583 const CXXRecordDecl *Expected;
584 if (Path.size() >= 2)
585 Expected = Path[Path.size() - 2];
586 else
587 Expected = getContainingRecord();
588 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
589 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
590 // if B does not contain the original member and is not a base or
591 // derived class of the class containing the original member, the result
592 // of the cast is undefined.
593 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
594 // (D::*). We consider that to be a language defect.
595 return false;
596 }
597 Path.pop_back();
598 return true;
599 }
600 /// Perform a base-to-derived member pointer cast.
601 bool castToDerived(const CXXRecordDecl *Derived) {
602 if (!getDecl())
603 return true;
604 if (!isDerivedMember()) {
605 Path.push_back(Derived);
606 return true;
607 }
608 if (!castBack(Derived))
609 return false;
610 if (Path.empty())
611 DeclAndIsDerivedMember.setInt(false);
612 return true;
613 }
614 /// Perform a derived-to-base member pointer cast.
615 bool castToBase(const CXXRecordDecl *Base) {
616 if (!getDecl())
617 return true;
618 if (Path.empty())
619 DeclAndIsDerivedMember.setInt(true);
620 if (isDerivedMember()) {
621 Path.push_back(Base);
622 return true;
623 }
624 return castBack(Base);
625 }
626 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000627
628 /// Kinds of constant expression checking, for diagnostics.
629 enum CheckConstantExpressionKind {
630 CCEK_Constant, ///< A normal constant.
631 CCEK_ReturnValue, ///< A constexpr function return value.
632 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
633 };
John McCallf4cf1a12010-05-07 17:22:02 +0000634}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000635
Richard Smith47a1eed2011-10-29 20:57:55 +0000636static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith69c2c502011-11-04 05:33:44 +0000637static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +0000638 const LValue &This, const Expr *E,
639 CheckConstantExpressionKind CCEK
640 = CCEK_Constant);
John McCallefdb83e2010-05-07 21:00:08 +0000641static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
642static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000643static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
644 EvalInfo &Info);
645static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000646static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith47a1eed2011-10-29 20:57:55 +0000647static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000648 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000649static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000650static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000651
652//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000653// Misc utilities
654//===----------------------------------------------------------------------===//
655
Richard Smith180f4792011-11-10 06:34:14 +0000656/// Should this call expression be treated as a string literal?
657static bool IsStringLiteralCall(const CallExpr *E) {
658 unsigned Builtin = E->isBuiltinCall();
659 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
660 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
661}
662
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000663static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000664 // C++11 [expr.const]p3 An address constant expression is a prvalue core
665 // constant expression of pointer type that evaluates to...
666
667 // ... a null pointer value, or a prvalue core constant expression of type
668 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000669 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000670
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000671 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
672 // ... the address of an object with static storage duration,
673 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
674 return VD->hasGlobalStorage();
675 // ... the address of a function,
676 return isa<FunctionDecl>(D);
677 }
678
679 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000680 switch (E->getStmtClass()) {
681 default:
682 return false;
Richard Smith180f4792011-11-10 06:34:14 +0000683 case Expr::CompoundLiteralExprClass:
684 return cast<CompoundLiteralExpr>(E)->isFileScope();
685 // A string literal has static storage duration.
686 case Expr::StringLiteralClass:
687 case Expr::PredefinedExprClass:
688 case Expr::ObjCStringLiteralClass:
689 case Expr::ObjCEncodeExprClass:
690 return true;
691 case Expr::CallExprClass:
692 return IsStringLiteralCall(cast<CallExpr>(E));
693 // For GCC compatibility, &&label has static storage duration.
694 case Expr::AddrLabelExprClass:
695 return true;
696 // A Block literal expression may be used as the initialization value for
697 // Block variables at global or local static scope.
698 case Expr::BlockExprClass:
699 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
700 }
John McCall42c8f872010-05-10 23:27:23 +0000701}
702
Richard Smith9a17a682011-11-07 05:07:52 +0000703/// Check that this reference or pointer core constant expression is a valid
704/// value for a constant expression. Type T should be either LValue or CCValue.
705template<typename T>
Richard Smithf48fdb02011-12-09 22:58:01 +0000706static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000707 const T &LVal, APValue &Value,
708 CheckConstantExpressionKind CCEK) {
709 APValue::LValueBase Base = LVal.getLValueBase();
710 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
711
712 if (!IsGlobalLValue(Base)) {
713 if (Info.getLangOpts().CPlusPlus0x) {
714 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
715 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
716 << E->isGLValue() << !Designator.Entries.empty()
717 << !!VD << CCEK << VD;
718 if (VD)
719 Info.Note(VD->getLocation(), diag::note_declared_at);
720 else
721 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
722 diag::note_constexpr_temporary_here);
723 } else {
724 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
725 }
Richard Smith9a17a682011-11-07 05:07:52 +0000726 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000727 }
Richard Smith9a17a682011-11-07 05:07:52 +0000728
Richard Smith9a17a682011-11-07 05:07:52 +0000729 // A constant expression must refer to an object or be a null pointer.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000730 if (Designator.Invalid ||
Richard Smith9a17a682011-11-07 05:07:52 +0000731 (!LVal.getLValueBase() && !Designator.Entries.empty())) {
Richard Smithc1c5f272011-12-13 06:39:58 +0000732 // FIXME: This is not a core constant expression. We should have already
733 // produced a CCE diagnostic.
Richard Smith9a17a682011-11-07 05:07:52 +0000734 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
735 APValue::NoLValuePath());
736 return true;
737 }
738
Richard Smithc1c5f272011-12-13 06:39:58 +0000739 // Does this refer one past the end of some object?
740 // This is technically not an address constant expression nor a reference
741 // constant expression, but we allow it for address constant expressions.
742 if (E->isGLValue() && Base && Designator.OnePastTheEnd) {
743 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
744 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
745 << !Designator.Entries.empty() << !!VD << VD;
746 if (VD)
747 Info.Note(VD->getLocation(), diag::note_declared_at);
748 else
749 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
750 diag::note_constexpr_temporary_here);
751 return false;
752 }
753
Richard Smith9a17a682011-11-07 05:07:52 +0000754 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
Richard Smithe24f5fc2011-11-17 22:56:20 +0000755 Designator.Entries, Designator.OnePastTheEnd);
Richard Smith9a17a682011-11-07 05:07:52 +0000756 return true;
757}
758
Richard Smith47a1eed2011-10-29 20:57:55 +0000759/// Check that this core constant expression value is a valid value for a
Richard Smith69c2c502011-11-04 05:33:44 +0000760/// constant expression, and if it is, produce the corresponding constant value.
Richard Smithf48fdb02011-12-09 22:58:01 +0000761/// If not, report an appropriate diagnostic.
762static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000763 const CCValue &CCValue, APValue &Value,
764 CheckConstantExpressionKind CCEK
765 = CCEK_Constant) {
Richard Smith9a17a682011-11-07 05:07:52 +0000766 if (!CCValue.isLValue()) {
767 Value = CCValue;
768 return true;
769 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000770 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith47a1eed2011-10-29 20:57:55 +0000771}
772
Richard Smith9e36b532011-10-31 05:11:32 +0000773const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000774 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +0000775}
776
777static bool IsLiteralLValue(const LValue &Value) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000778 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith9e36b532011-10-31 05:11:32 +0000779}
780
Richard Smith65ac5982011-11-01 21:06:14 +0000781static bool IsWeakLValue(const LValue &Value) {
782 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +0000783 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +0000784}
785
Richard Smithe24f5fc2011-11-17 22:56:20 +0000786static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +0000787 // A null base expression indicates a null pointer. These are always
788 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000789 if (!Value.getLValueBase()) {
790 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +0000791 return true;
792 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000793
John McCall42c8f872010-05-10 23:27:23 +0000794 // Require the base expression to be a global l-value.
Richard Smith47a1eed2011-10-29 20:57:55 +0000795 // FIXME: C++11 requires such conversions. Remove this check.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000796 if (!IsGlobalLValue(Value.getLValueBase())) return false;
John McCall42c8f872010-05-10 23:27:23 +0000797
Richard Smithe24f5fc2011-11-17 22:56:20 +0000798 // We have a non-null base. These are generally known to be true, but if it's
799 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +0000800 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +0000801 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +0000802 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +0000803}
804
Richard Smith47a1eed2011-10-29 20:57:55 +0000805static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +0000806 switch (Val.getKind()) {
807 case APValue::Uninitialized:
808 return false;
809 case APValue::Int:
810 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +0000811 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000812 case APValue::Float:
813 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +0000814 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000815 case APValue::ComplexInt:
816 Result = Val.getComplexIntReal().getBoolValue() ||
817 Val.getComplexIntImag().getBoolValue();
818 return true;
819 case APValue::ComplexFloat:
820 Result = !Val.getComplexFloatReal().isZero() ||
821 !Val.getComplexFloatImag().isZero();
822 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +0000823 case APValue::LValue:
824 return EvalPointerValueAsBool(Val, Result);
825 case APValue::MemberPointer:
826 Result = Val.getMemberPointerDecl();
827 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000828 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +0000829 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +0000830 case APValue::Struct:
831 case APValue::Union:
Richard Smithc49bd112011-10-28 17:51:58 +0000832 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000833 }
834
Richard Smithc49bd112011-10-28 17:51:58 +0000835 llvm_unreachable("unknown APValue kind");
836}
837
838static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
839 EvalInfo &Info) {
840 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith47a1eed2011-10-29 20:57:55 +0000841 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +0000842 if (!Evaluate(Val, Info, E))
843 return false;
844 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +0000845}
846
Richard Smithc1c5f272011-12-13 06:39:58 +0000847template<typename T>
848static bool HandleOverflow(EvalInfo &Info, const Expr *E,
849 const T &SrcValue, QualType DestType) {
850 llvm::SmallVector<char, 32> Buffer;
851 SrcValue.toString(Buffer);
852 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
853 << StringRef(Buffer.data(), Buffer.size()) << DestType;
854 return false;
855}
856
857static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
858 QualType SrcType, const APFloat &Value,
859 QualType DestType, APSInt &Result) {
860 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000861 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000862 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000863
Richard Smithc1c5f272011-12-13 06:39:58 +0000864 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000865 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +0000866 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
867 & APFloat::opInvalidOp)
868 return HandleOverflow(Info, E, Value, DestType);
869 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000870}
871
Richard Smithc1c5f272011-12-13 06:39:58 +0000872static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
873 QualType SrcType, QualType DestType,
874 APFloat &Result) {
875 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000876 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +0000877 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
878 APFloat::rmNearestTiesToEven, &ignored)
879 & APFloat::opOverflow)
880 return HandleOverflow(Info, E, Value, DestType);
881 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000882}
883
Mike Stump1eb44332009-09-09 15:08:12 +0000884static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000885 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000886 unsigned DestWidth = Ctx.getIntWidth(DestType);
887 APSInt Result = Value;
888 // Figure out if this is a truncate, extend or noop cast.
889 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000890 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +0000891 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000892 return Result;
893}
894
Richard Smithc1c5f272011-12-13 06:39:58 +0000895static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
896 QualType SrcType, const APSInt &Value,
897 QualType DestType, APFloat &Result) {
898 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
899 if (Result.convertFromAPInt(Value, Value.isSigned(),
900 APFloat::rmNearestTiesToEven)
901 & APFloat::opOverflow)
902 return HandleOverflow(Info, E, Value, DestType);
903 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000904}
905
Richard Smithe24f5fc2011-11-17 22:56:20 +0000906static bool FindMostDerivedObject(EvalInfo &Info, const LValue &LVal,
907 const CXXRecordDecl *&MostDerivedType,
908 unsigned &MostDerivedPathLength,
909 bool &MostDerivedIsArrayElement) {
910 const SubobjectDesignator &D = LVal.Designator;
911 if (D.Invalid || !LVal.Base)
Richard Smith180f4792011-11-10 06:34:14 +0000912 return false;
913
Richard Smithe24f5fc2011-11-17 22:56:20 +0000914 const Type *T = getType(LVal.Base).getTypePtr();
Richard Smith180f4792011-11-10 06:34:14 +0000915
916 // Find path prefix which leads to the most-derived subobject.
Richard Smith180f4792011-11-10 06:34:14 +0000917 MostDerivedType = T->getAsCXXRecordDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +0000918 MostDerivedPathLength = 0;
919 MostDerivedIsArrayElement = false;
Richard Smith180f4792011-11-10 06:34:14 +0000920
921 for (unsigned I = 0, N = D.Entries.size(); I != N; ++I) {
922 bool IsArray = T && T->isArrayType();
923 if (IsArray)
924 T = T->getBaseElementTypeUnsafe();
925 else if (const FieldDecl *FD = getAsField(D.Entries[I]))
926 T = FD->getType().getTypePtr();
927 else
928 T = 0;
929
930 if (T) {
931 MostDerivedType = T->getAsCXXRecordDecl();
932 MostDerivedPathLength = I + 1;
933 MostDerivedIsArrayElement = IsArray;
934 }
935 }
936
Richard Smith180f4792011-11-10 06:34:14 +0000937 // (B*)&d + 1 has no most-derived object.
938 if (D.OnePastTheEnd && MostDerivedPathLength != D.Entries.size())
939 return false;
940
Richard Smithe24f5fc2011-11-17 22:56:20 +0000941 return MostDerivedType != 0;
942}
943
944static void TruncateLValueBasePath(EvalInfo &Info, LValue &Result,
945 const RecordDecl *TruncatedType,
946 unsigned TruncatedElements,
947 bool IsArrayElement) {
948 SubobjectDesignator &D = Result.Designator;
949 const RecordDecl *RD = TruncatedType;
950 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +0000951 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
952 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000953 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +0000954 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000955 else
Richard Smith180f4792011-11-10 06:34:14 +0000956 Result.Offset -= Layout.getBaseClassOffset(Base);
957 RD = Base;
958 }
Richard Smithe24f5fc2011-11-17 22:56:20 +0000959 D.Entries.resize(TruncatedElements);
960 D.ArrayElement = IsArrayElement;
961}
962
963/// If the given LValue refers to a base subobject of some object, find the most
964/// derived object and the corresponding complete record type. This is necessary
965/// in order to find the offset of a virtual base class.
966static bool ExtractMostDerivedObject(EvalInfo &Info, LValue &Result,
967 const CXXRecordDecl *&MostDerivedType) {
968 unsigned MostDerivedPathLength;
969 bool MostDerivedIsArrayElement;
970 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
971 MostDerivedPathLength, MostDerivedIsArrayElement))
972 return false;
973
974 // Remove the trailing base class path entries and their offsets.
975 TruncateLValueBasePath(Info, Result, MostDerivedType, MostDerivedPathLength,
976 MostDerivedIsArrayElement);
Richard Smith180f4792011-11-10 06:34:14 +0000977 return true;
978}
979
980static void HandleLValueDirectBase(EvalInfo &Info, LValue &Obj,
981 const CXXRecordDecl *Derived,
982 const CXXRecordDecl *Base,
983 const ASTRecordLayout *RL = 0) {
984 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
985 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
986 Obj.Designator.addDecl(Base, /*Virtual*/ false);
987}
988
989static bool HandleLValueBase(EvalInfo &Info, LValue &Obj,
990 const CXXRecordDecl *DerivedDecl,
991 const CXXBaseSpecifier *Base) {
992 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
993
994 if (!Base->isVirtual()) {
995 HandleLValueDirectBase(Info, Obj, DerivedDecl, BaseDecl);
996 return true;
997 }
998
999 // Extract most-derived object and corresponding type.
1000 if (!ExtractMostDerivedObject(Info, Obj, DerivedDecl))
1001 return false;
1002
1003 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1004 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1005 Obj.Designator.addDecl(BaseDecl, /*Virtual*/ true);
1006 return true;
1007}
1008
1009/// Update LVal to refer to the given field, which must be a member of the type
1010/// currently described by LVal.
1011static void HandleLValueMember(EvalInfo &Info, LValue &LVal,
1012 const FieldDecl *FD,
1013 const ASTRecordLayout *RL = 0) {
1014 if (!RL)
1015 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1016
1017 unsigned I = FD->getFieldIndex();
1018 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
1019 LVal.Designator.addDecl(FD);
1020}
1021
1022/// Get the size of the given type in char units.
1023static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1024 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1025 // extension.
1026 if (Type->isVoidType() || Type->isFunctionType()) {
1027 Size = CharUnits::One();
1028 return true;
1029 }
1030
1031 if (!Type->isConstantSizeType()) {
1032 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1033 return false;
1034 }
1035
1036 Size = Info.Ctx.getTypeSizeInChars(Type);
1037 return true;
1038}
1039
1040/// Update a pointer value to model pointer arithmetic.
1041/// \param Info - Information about the ongoing evaluation.
1042/// \param LVal - The pointer value to be updated.
1043/// \param EltTy - The pointee type represented by LVal.
1044/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
1045static bool HandleLValueArrayAdjustment(EvalInfo &Info, LValue &LVal,
1046 QualType EltTy, int64_t Adjustment) {
1047 CharUnits SizeOfPointee;
1048 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1049 return false;
1050
1051 // Compute the new offset in the appropriate width.
1052 LVal.Offset += Adjustment * SizeOfPointee;
1053 LVal.Designator.adjustIndex(Adjustment);
1054 return true;
1055}
1056
Richard Smith03f96112011-10-24 17:54:18 +00001057/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001058static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1059 const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +00001060 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001061 // If this is a parameter to an active constexpr function call, perform
1062 // argument substitution.
1063 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00001064 if (!Frame || !Frame->Arguments) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001065 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001066 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001067 }
Richard Smith177dce72011-11-01 16:57:24 +00001068 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1069 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001070 }
Richard Smith03f96112011-10-24 17:54:18 +00001071
Richard Smith180f4792011-11-10 06:34:14 +00001072 // If we're currently evaluating the initializer of this declaration, use that
1073 // in-flight value.
1074 if (Info.EvaluatingDecl == VD) {
1075 Result = CCValue(*Info.EvaluatingDeclValue, CCValue::GlobalValue());
1076 return !Result.isUninit();
1077 }
1078
Richard Smith65ac5982011-11-01 21:06:14 +00001079 // Never evaluate the initializer of a weak variable. We can't be sure that
1080 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001081 if (VD->isWeak()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001082 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001083 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001084 }
Richard Smith65ac5982011-11-01 21:06:14 +00001085
Richard Smith03f96112011-10-24 17:54:18 +00001086 const Expr *Init = VD->getAnyInitializer();
Richard Smithf48fdb02011-12-09 22:58:01 +00001087 if (!Init || Init->isValueDependent()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001088 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith47a1eed2011-10-29 20:57:55 +00001089 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001090 }
Richard Smith03f96112011-10-24 17:54:18 +00001091
Richard Smith47a1eed2011-10-29 20:57:55 +00001092 if (APValue *V = VD->getEvaluatedValue()) {
Richard Smith177dce72011-11-01 16:57:24 +00001093 Result = CCValue(*V, CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +00001094 return !Result.isUninit();
1095 }
Richard Smith03f96112011-10-24 17:54:18 +00001096
Richard Smithf48fdb02011-12-09 22:58:01 +00001097 if (VD->isEvaluatingValue()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001098 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith47a1eed2011-10-29 20:57:55 +00001099 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001100 }
Richard Smith03f96112011-10-24 17:54:18 +00001101
1102 VD->setEvaluatingValue();
1103
Richard Smith47a1eed2011-10-29 20:57:55 +00001104 Expr::EvalStatus EStatus;
1105 EvalInfo InitInfo(Info.Ctx, EStatus);
Richard Smith180f4792011-11-10 06:34:14 +00001106 APValue EvalResult;
1107 InitInfo.setEvaluatingDecl(VD, EvalResult);
1108 LValue LVal;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001109 LVal.set(VD);
Richard Smithc49bd112011-10-28 17:51:58 +00001110 // FIXME: The caller will need to know whether the value was a constant
1111 // expression. If not, we should propagate up a diagnostic.
Richard Smith180f4792011-11-10 06:34:14 +00001112 if (!EvaluateConstantExpression(EvalResult, InitInfo, LVal, Init)) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001113 // FIXME: If the evaluation failure was not permanent (for instance, if we
1114 // hit a variable with no declaration yet, or a constexpr function with no
1115 // definition yet), the standard is unclear as to how we should behave.
1116 //
1117 // Either the initializer should be evaluated when the variable is defined,
1118 // or a failed evaluation of the initializer should be reattempted each time
1119 // it is used.
Richard Smith03f96112011-10-24 17:54:18 +00001120 VD->setEvaluatedValue(APValue());
Richard Smithdd1f29b2011-12-12 09:28:41 +00001121 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith47a1eed2011-10-29 20:57:55 +00001122 return false;
1123 }
Richard Smith03f96112011-10-24 17:54:18 +00001124
Richard Smith69c2c502011-11-04 05:33:44 +00001125 VD->setEvaluatedValue(EvalResult);
1126 Result = CCValue(EvalResult, CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +00001127 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001128}
1129
Richard Smithc49bd112011-10-28 17:51:58 +00001130static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001131 Qualifiers Quals = T.getQualifiers();
1132 return Quals.hasConst() && !Quals.hasVolatile();
1133}
1134
Richard Smith59efe262011-11-11 04:05:33 +00001135/// Get the base index of the given base class within an APValue representing
1136/// the given derived class.
1137static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1138 const CXXRecordDecl *Base) {
1139 Base = Base->getCanonicalDecl();
1140 unsigned Index = 0;
1141 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1142 E = Derived->bases_end(); I != E; ++I, ++Index) {
1143 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1144 return Index;
1145 }
1146
1147 llvm_unreachable("base class missing from derived class's bases list");
1148}
1149
Richard Smithcc5d4f62011-11-07 09:22:26 +00001150/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001151static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1152 CCValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001153 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithf48fdb02011-12-09 22:58:01 +00001154 if (Sub.Invalid || Sub.OnePastTheEnd) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001155 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001156 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001157 }
Richard Smithf64699e2011-11-11 08:28:03 +00001158 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001159 return true;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001160
1161 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1162 const APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001163 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001164 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001165 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001166 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001167 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001168 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001169 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001170 if (CAT->getSize().ule(Index)) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001171 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001172 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001173 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001174 if (O->getArrayInitializedElts() > Index)
1175 O = &O->getArrayInitializedElt(Index);
1176 else
1177 O = &O->getArrayFiller();
1178 ObjType = CAT->getElementType();
Richard Smith180f4792011-11-10 06:34:14 +00001179 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1180 // Next subobject is a class, struct or union field.
1181 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1182 if (RD->isUnion()) {
1183 const FieldDecl *UnionField = O->getUnionField();
1184 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001185 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001186 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith180f4792011-11-10 06:34:14 +00001187 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001188 }
Richard Smith180f4792011-11-10 06:34:14 +00001189 O = &O->getUnionValue();
1190 } else
1191 O = &O->getStructField(Field->getFieldIndex());
1192 ObjType = Field->getType();
Richard Smithcc5d4f62011-11-07 09:22:26 +00001193 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001194 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001195 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1196 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1197 O = &O->getStructBase(getBaseIndex(Derived, Base));
1198 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001199 }
Richard Smith180f4792011-11-10 06:34:14 +00001200
Richard Smithf48fdb02011-12-09 22:58:01 +00001201 if (O->isUninit()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001202 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith180f4792011-11-10 06:34:14 +00001203 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001204 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001205 }
1206
Richard Smithcc5d4f62011-11-07 09:22:26 +00001207 Obj = CCValue(*O, CCValue::GlobalValue());
1208 return true;
1209}
1210
Richard Smith180f4792011-11-10 06:34:14 +00001211/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1212/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1213/// for looking up the glvalue referred to by an entity of reference type.
1214///
1215/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001216/// \param Conv - The expression for which we are performing the conversion.
1217/// Used for diagnostics.
Richard Smith180f4792011-11-10 06:34:14 +00001218/// \param Type - The type we expect this conversion to produce.
1219/// \param LVal - The glvalue on which we are attempting to perform this action.
1220/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001221static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1222 QualType Type,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001223 const LValue &LVal, CCValue &RVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001224 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001225 CallStackFrame *Frame = LVal.Frame;
Richard Smithc49bd112011-10-28 17:51:58 +00001226
Richard Smithf48fdb02011-12-09 22:58:01 +00001227 if (!LVal.Base) {
1228 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smithdd1f29b2011-12-12 09:28:41 +00001229 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithc49bd112011-10-28 17:51:58 +00001230 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001231 }
Richard Smithc49bd112011-10-28 17:51:58 +00001232
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001233 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001234 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1235 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001236 // expressions are constant expressions too. Inside constexpr functions,
1237 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001238 // In C, such things can also be folded, although they are not ICEs.
1239 //
Richard Smithd0dccea2011-10-28 22:34:42 +00001240 // FIXME: volatile-qualified ParmVarDecls need special handling. A literal
1241 // interpretation of C++11 suggests that volatile parameters are OK if
1242 // they're never read (there's no prohibition against constructing volatile
1243 // objects in constant expressions), but lvalue-to-rvalue conversions on
1244 // them are not permitted.
Richard Smithc49bd112011-10-28 17:51:58 +00001245 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf48fdb02011-12-09 22:58:01 +00001246 if (!VD || VD->isInvalidDecl()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001247 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001248 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001249 }
1250
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001251 QualType VT = VD->getType();
Richard Smith0a3bdb62011-11-04 02:25:55 +00001252 if (!isa<ParmVarDecl>(VD)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00001253 if (!IsConstNonVolatile(VT)) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001254 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001255 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001256 }
Richard Smithcd689922011-11-07 03:22:51 +00001257 // FIXME: Allow folding of values of any literal type in all languages.
1258 if (!VT->isIntegralOrEnumerationType() && !VT->isRealFloatingType() &&
Richard Smithf48fdb02011-12-09 22:58:01 +00001259 !VD->isConstexpr()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001260 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001261 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001262 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001263 }
Richard Smithf48fdb02011-12-09 22:58:01 +00001264 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001265 return false;
1266
Richard Smith47a1eed2011-10-29 20:57:55 +00001267 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001268 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001269
1270 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1271 // conversion. This happens when the declaration and the lvalue should be
1272 // considered synonymous, for instance when initializing an array of char
1273 // from a string literal. Continue as if the initializer lvalue was the
1274 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001275 assert(RVal.getLValueOffset().isZero() &&
1276 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001277 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001278 Frame = RVal.getLValueFrame();
Richard Smithc49bd112011-10-28 17:51:58 +00001279 }
1280
Richard Smith0a3bdb62011-11-04 02:25:55 +00001281 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1282 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1283 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf48fdb02011-12-09 22:58:01 +00001284 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001285 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001286 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001287 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001288
1289 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith9a17a682011-11-07 05:07:52 +00001290 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001291 if (Index > S->getLength()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001292 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001293 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001294 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001295 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1296 Type->isUnsignedIntegerType());
1297 if (Index < S->getLength())
1298 Value = S->getCodeUnit(Index);
1299 RVal = CCValue(Value);
1300 return true;
1301 }
1302
Richard Smithcc5d4f62011-11-07 09:22:26 +00001303 if (Frame) {
1304 // If this is a temporary expression with a nontrivial initializer, grab the
1305 // value from the relevant stack frame.
1306 RVal = Frame->Temporaries[Base];
1307 } else if (const CompoundLiteralExpr *CLE
1308 = dyn_cast<CompoundLiteralExpr>(Base)) {
1309 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1310 // initializer until now for such expressions. Such an expression can't be
1311 // an ICE in C, so this only matters for fold.
1312 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1313 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1314 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001315 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001316 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001317 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001318 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001319
Richard Smithf48fdb02011-12-09 22:58:01 +00001320 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1321 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001322}
1323
Richard Smith59efe262011-11-11 04:05:33 +00001324/// Build an lvalue for the object argument of a member function call.
1325static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1326 LValue &This) {
1327 if (Object->getType()->isPointerType())
1328 return EvaluatePointer(Object, This, Info);
1329
1330 if (Object->isGLValue())
1331 return EvaluateLValue(Object, This, Info);
1332
Richard Smithe24f5fc2011-11-17 22:56:20 +00001333 if (Object->getType()->isLiteralType())
1334 return EvaluateTemporary(Object, This, Info);
1335
1336 return false;
1337}
1338
1339/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1340/// lvalue referring to the result.
1341///
1342/// \param Info - Information about the ongoing evaluation.
1343/// \param BO - The member pointer access operation.
1344/// \param LV - Filled in with a reference to the resulting object.
1345/// \param IncludeMember - Specifies whether the member itself is included in
1346/// the resulting LValue subobject designator. This is not possible when
1347/// creating a bound member function.
1348/// \return The field or method declaration to which the member pointer refers,
1349/// or 0 if evaluation fails.
1350static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1351 const BinaryOperator *BO,
1352 LValue &LV,
1353 bool IncludeMember = true) {
1354 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1355
1356 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV))
1357 return 0;
1358
1359 MemberPtr MemPtr;
1360 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1361 return 0;
1362
1363 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1364 // member value, the behavior is undefined.
1365 if (!MemPtr.getDecl())
1366 return 0;
1367
1368 if (MemPtr.isDerivedMember()) {
1369 // This is a member of some derived class. Truncate LV appropriately.
1370 const CXXRecordDecl *MostDerivedType;
1371 unsigned MostDerivedPathLength;
1372 bool MostDerivedIsArrayElement;
1373 if (!FindMostDerivedObject(Info, LV, MostDerivedType, MostDerivedPathLength,
1374 MostDerivedIsArrayElement))
1375 return 0;
1376
1377 // The end of the derived-to-base path for the base object must match the
1378 // derived-to-base path for the member pointer.
1379 if (MostDerivedPathLength + MemPtr.Path.size() >
1380 LV.Designator.Entries.size())
1381 return 0;
1382 unsigned PathLengthToMember =
1383 LV.Designator.Entries.size() - MemPtr.Path.size();
1384 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1385 const CXXRecordDecl *LVDecl = getAsBaseClass(
1386 LV.Designator.Entries[PathLengthToMember + I]);
1387 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1388 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1389 return 0;
1390 }
1391
1392 // Truncate the lvalue to the appropriate derived class.
1393 bool ResultIsArray = false;
1394 if (PathLengthToMember == MostDerivedPathLength)
1395 ResultIsArray = MostDerivedIsArrayElement;
1396 TruncateLValueBasePath(Info, LV, MemPtr.getContainingRecord(),
1397 PathLengthToMember, ResultIsArray);
1398 } else if (!MemPtr.Path.empty()) {
1399 // Extend the LValue path with the member pointer's path.
1400 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1401 MemPtr.Path.size() + IncludeMember);
1402
1403 // Walk down to the appropriate base class.
1404 QualType LVType = BO->getLHS()->getType();
1405 if (const PointerType *PT = LVType->getAs<PointerType>())
1406 LVType = PT->getPointeeType();
1407 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1408 assert(RD && "member pointer access on non-class-type expression");
1409 // The first class in the path is that of the lvalue.
1410 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1411 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
1412 HandleLValueDirectBase(Info, LV, RD, Base);
1413 RD = Base;
1414 }
1415 // Finally cast to the class containing the member.
1416 HandleLValueDirectBase(Info, LV, RD, MemPtr.getContainingRecord());
1417 }
1418
1419 // Add the member. Note that we cannot build bound member functions here.
1420 if (IncludeMember) {
1421 // FIXME: Deal with IndirectFieldDecls.
1422 const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl());
1423 if (!FD) return 0;
1424 HandleLValueMember(Info, LV, FD);
1425 }
1426
1427 return MemPtr.getDecl();
1428}
1429
1430/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1431/// the provided lvalue, which currently refers to the base object.
1432static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1433 LValue &Result) {
1434 const CXXRecordDecl *MostDerivedType;
1435 unsigned MostDerivedPathLength;
1436 bool MostDerivedIsArrayElement;
1437
1438 // Check this cast doesn't take us outside the object.
1439 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
1440 MostDerivedPathLength,
1441 MostDerivedIsArrayElement))
1442 return false;
1443 SubobjectDesignator &D = Result.Designator;
1444 if (MostDerivedPathLength + E->path_size() > D.Entries.size())
1445 return false;
1446
1447 // Check the type of the final cast. We don't need to check the path,
1448 // since a cast can only be formed if the path is unique.
1449 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
1450 bool ResultIsArray = false;
1451 QualType TargetQT = E->getType();
1452 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1453 TargetQT = PT->getPointeeType();
1454 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1455 const CXXRecordDecl *FinalType;
1456 if (NewEntriesSize == MostDerivedPathLength) {
1457 ResultIsArray = MostDerivedIsArrayElement;
1458 FinalType = MostDerivedType;
1459 } else
1460 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
1461 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
1462 return false;
1463
1464 // Truncate the lvalue to the appropriate derived class.
1465 TruncateLValueBasePath(Info, Result, TargetType, NewEntriesSize,
1466 ResultIsArray);
1467 return true;
Richard Smith59efe262011-11-11 04:05:33 +00001468}
1469
Mike Stumpc4c90452009-10-27 22:09:17 +00001470namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00001471enum EvalStmtResult {
1472 /// Evaluation failed.
1473 ESR_Failed,
1474 /// Hit a 'return' statement.
1475 ESR_Returned,
1476 /// Evaluation succeeded.
1477 ESR_Succeeded
1478};
1479}
1480
1481// Evaluate a statement.
Richard Smithc1c5f272011-12-13 06:39:58 +00001482static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00001483 const Stmt *S) {
1484 switch (S->getStmtClass()) {
1485 default:
1486 return ESR_Failed;
1487
1488 case Stmt::NullStmtClass:
1489 case Stmt::DeclStmtClass:
1490 return ESR_Succeeded;
1491
Richard Smithc1c5f272011-12-13 06:39:58 +00001492 case Stmt::ReturnStmtClass: {
1493 CCValue CCResult;
1494 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1495 if (!Evaluate(CCResult, Info, RetExpr) ||
1496 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1497 CCEK_ReturnValue))
1498 return ESR_Failed;
1499 return ESR_Returned;
1500 }
Richard Smithd0dccea2011-10-28 22:34:42 +00001501
1502 case Stmt::CompoundStmtClass: {
1503 const CompoundStmt *CS = cast<CompoundStmt>(S);
1504 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1505 BE = CS->body_end(); BI != BE; ++BI) {
1506 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1507 if (ESR != ESR_Succeeded)
1508 return ESR;
1509 }
1510 return ESR_Succeeded;
1511 }
1512 }
1513}
1514
Richard Smithc1c5f272011-12-13 06:39:58 +00001515/// CheckConstexprFunction - Check that a function can be called in a constant
1516/// expression.
1517static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1518 const FunctionDecl *Declaration,
1519 const FunctionDecl *Definition) {
1520 // Can we evaluate this function call?
1521 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1522 return true;
1523
1524 if (Info.getLangOpts().CPlusPlus0x) {
1525 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
1526 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1527 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1528 << DiagDecl;
1529 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1530 } else {
1531 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1532 }
1533 return false;
1534}
1535
Richard Smith180f4792011-11-10 06:34:14 +00001536namespace {
Richard Smithcd99b072011-11-11 05:48:57 +00001537typedef SmallVector<CCValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00001538}
1539
1540/// EvaluateArgs - Evaluate the arguments to a function call.
1541static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1542 EvalInfo &Info) {
1543 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1544 I != E; ++I)
1545 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1546 return false;
1547 return true;
1548}
1549
Richard Smithd0dccea2011-10-28 22:34:42 +00001550/// Evaluate a function call.
Richard Smith08d6e032011-12-16 19:06:07 +00001551static bool HandleFunctionCall(const Expr *CallExpr, const FunctionDecl *Callee,
1552 const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00001553 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smithc1c5f272011-12-13 06:39:58 +00001554 EvalInfo &Info, APValue &Result) {
1555 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smithd0dccea2011-10-28 22:34:42 +00001556 return false;
1557
Richard Smith180f4792011-11-10 06:34:14 +00001558 ArgVector ArgValues(Args.size());
1559 if (!EvaluateArgs(Args, ArgValues, Info))
1560 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00001561
Richard Smith08d6e032011-12-16 19:06:07 +00001562 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Callee, This,
1563 ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00001564 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1565}
1566
Richard Smith180f4792011-11-10 06:34:14 +00001567/// Evaluate a constructor call.
Richard Smithf48fdb02011-12-09 22:58:01 +00001568static bool HandleConstructorCall(const Expr *CallExpr, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00001569 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00001570 const CXXConstructorDecl *Definition,
Richard Smith59efe262011-11-11 04:05:33 +00001571 EvalInfo &Info,
Richard Smith180f4792011-11-10 06:34:14 +00001572 APValue &Result) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001573 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smith180f4792011-11-10 06:34:14 +00001574 return false;
1575
1576 ArgVector ArgValues(Args.size());
1577 if (!EvaluateArgs(Args, ArgValues, Info))
1578 return false;
1579
Richard Smith08d6e032011-12-16 19:06:07 +00001580 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Definition,
1581 &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00001582
1583 // If it's a delegating constructor, just delegate.
1584 if (Definition->isDelegatingConstructor()) {
1585 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1586 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1587 }
1588
1589 // Reserve space for the struct members.
1590 const CXXRecordDecl *RD = Definition->getParent();
1591 if (!RD->isUnion())
1592 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1593 std::distance(RD->field_begin(), RD->field_end()));
1594
1595 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1596
1597 unsigned BasesSeen = 0;
1598#ifndef NDEBUG
1599 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1600#endif
1601 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1602 E = Definition->init_end(); I != E; ++I) {
1603 if ((*I)->isBaseInitializer()) {
1604 QualType BaseType((*I)->getBaseClass(), 0);
1605#ifndef NDEBUG
1606 // Non-virtual base classes are initialized in the order in the class
1607 // definition. We cannot have a virtual base class for a literal type.
1608 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1609 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1610 "base class initializers not in expected order");
1611 ++BaseIt;
1612#endif
1613 LValue Subobject = This;
1614 HandleLValueDirectBase(Info, Subobject, RD,
1615 BaseType->getAsCXXRecordDecl(), &Layout);
1616 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1617 Subobject, (*I)->getInit()))
1618 return false;
1619 } else if (FieldDecl *FD = (*I)->getMember()) {
1620 LValue Subobject = This;
1621 HandleLValueMember(Info, Subobject, FD, &Layout);
1622 if (RD->isUnion()) {
1623 Result = APValue(FD);
Richard Smithc1c5f272011-12-13 06:39:58 +00001624 if (!EvaluateConstantExpression(Result.getUnionValue(), Info, Subobject,
1625 (*I)->getInit(), CCEK_MemberInit))
Richard Smith180f4792011-11-10 06:34:14 +00001626 return false;
1627 } else if (!EvaluateConstantExpression(
1628 Result.getStructField(FD->getFieldIndex()),
Richard Smithc1c5f272011-12-13 06:39:58 +00001629 Info, Subobject, (*I)->getInit(), CCEK_MemberInit))
Richard Smith180f4792011-11-10 06:34:14 +00001630 return false;
1631 } else {
1632 // FIXME: handle indirect field initializers
Richard Smithdd1f29b2011-12-12 09:28:41 +00001633 Info.Diag((*I)->getInit()->getExprLoc(),
Richard Smithf48fdb02011-12-09 22:58:01 +00001634 diag::note_invalid_subexpr_in_const_expr);
Richard Smith180f4792011-11-10 06:34:14 +00001635 return false;
1636 }
1637 }
1638
1639 return true;
1640}
1641
Richard Smithd0dccea2011-10-28 22:34:42 +00001642namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001643class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001644 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00001645 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00001646public:
1647
Richard Smith1e12c592011-10-16 21:26:27 +00001648 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00001649
1650 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001651 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00001652 return true;
1653 }
1654
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001655 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1656 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00001657 return Visit(E->getResultExpr());
1658 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001659 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001660 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00001661 return true;
1662 return false;
1663 }
John McCallf85e1932011-06-15 23:02:42 +00001664 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001665 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00001666 return true;
1667 return false;
1668 }
1669 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001670 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00001671 return true;
1672 return false;
1673 }
1674
Mike Stumpc4c90452009-10-27 22:09:17 +00001675 // We don't want to evaluate BlockExprs multiple times, as they generate
1676 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001677 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1678 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1679 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00001680 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001681 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1682 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1683 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1684 bool VisitStringLiteral(const StringLiteral *E) { return false; }
1685 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1686 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001687 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001688 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00001689 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001690 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00001691 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001692 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
1693 bool VisitBinAssign(const BinaryOperator *E) { return true; }
1694 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
1695 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00001696 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001697 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
1698 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
1699 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
1700 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
1701 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001702 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00001703 return true;
Mike Stump980ca222009-10-29 20:48:09 +00001704 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00001705 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001706 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00001707
1708 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001709 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00001710 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
1711 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001712 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00001713 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00001714 return false;
1715 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00001716
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001717 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00001718};
1719
John McCall56ca35d2011-02-17 10:25:35 +00001720class OpaqueValueEvaluation {
1721 EvalInfo &info;
1722 OpaqueValueExpr *opaqueValue;
1723
1724public:
1725 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
1726 Expr *value)
1727 : info(info), opaqueValue(opaqueValue) {
1728
1729 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00001730 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00001731 this->opaqueValue = 0;
1732 return;
1733 }
John McCall56ca35d2011-02-17 10:25:35 +00001734 }
1735
1736 bool hasError() const { return opaqueValue == 0; }
1737
1738 ~OpaqueValueEvaluation() {
Richard Smith1e12c592011-10-16 21:26:27 +00001739 // FIXME: This will not work for recursive constexpr functions using opaque
1740 // values. Restore the former value.
John McCall56ca35d2011-02-17 10:25:35 +00001741 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
1742 }
1743};
1744
Mike Stumpc4c90452009-10-27 22:09:17 +00001745} // end anonymous namespace
1746
Eli Friedman4efaa272008-11-12 09:44:48 +00001747//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001748// Generic Evaluation
1749//===----------------------------------------------------------------------===//
1750namespace {
1751
Richard Smithf48fdb02011-12-09 22:58:01 +00001752// FIXME: RetTy is always bool. Remove it.
1753template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001754class ExprEvaluatorBase
1755 : public ConstStmtVisitor<Derived, RetTy> {
1756private:
Richard Smith47a1eed2011-10-29 20:57:55 +00001757 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001758 return static_cast<Derived*>(this)->Success(V, E);
1759 }
Richard Smithf10d9172011-10-11 21:43:33 +00001760 RetTy DerivedValueInitialization(const Expr *E) {
1761 return static_cast<Derived*>(this)->ValueInitialization(E);
1762 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001763
1764protected:
1765 EvalInfo &Info;
1766 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
1767 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
1768
Richard Smithdd1f29b2011-12-12 09:28:41 +00001769 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd5093422011-12-12 09:41:58 +00001770 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00001771 }
1772
1773 /// Report an evaluation error. This should only be called when an error is
1774 /// first discovered. When propagating an error, just return false.
1775 bool Error(const Expr *E, diag::kind D) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001776 Info.Diag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00001777 return false;
1778 }
1779 bool Error(const Expr *E) {
1780 return Error(E, diag::note_invalid_subexpr_in_const_expr);
1781 }
1782
1783 RetTy ValueInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00001784
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001785public:
1786 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
1787
1788 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001789 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001790 }
1791 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00001792 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001793 }
1794
1795 RetTy VisitParenExpr(const ParenExpr *E)
1796 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1797 RetTy VisitUnaryExtension(const UnaryOperator *E)
1798 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1799 RetTy VisitUnaryPlus(const UnaryOperator *E)
1800 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1801 RetTy VisitChooseExpr(const ChooseExpr *E)
1802 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
1803 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
1804 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00001805 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
1806 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00001807 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
1808 { return StmtVisitorTy::Visit(E->getExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001809
Richard Smithc216a012011-12-12 12:46:16 +00001810 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
1811 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
1812 return static_cast<Derived*>(this)->VisitCastExpr(E);
1813 }
1814 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
1815 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
1816 return static_cast<Derived*>(this)->VisitCastExpr(E);
1817 }
1818
Richard Smithe24f5fc2011-11-17 22:56:20 +00001819 RetTy VisitBinaryOperator(const BinaryOperator *E) {
1820 switch (E->getOpcode()) {
1821 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00001822 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001823
1824 case BO_Comma:
1825 VisitIgnoredValue(E->getLHS());
1826 return StmtVisitorTy::Visit(E->getRHS());
1827
1828 case BO_PtrMemD:
1829 case BO_PtrMemI: {
1830 LValue Obj;
1831 if (!HandleMemberPointerAccess(Info, E, Obj))
1832 return false;
1833 CCValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00001834 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001835 return false;
1836 return DerivedSuccess(Result, E);
1837 }
1838 }
1839 }
1840
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001841 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
1842 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
1843 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00001844 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001845
1846 bool cond;
Richard Smithc49bd112011-10-28 17:51:58 +00001847 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00001848 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001849
1850 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
1851 }
1852
1853 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
1854 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00001855 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00001856 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001857
Richard Smithc49bd112011-10-28 17:51:58 +00001858 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001859 return StmtVisitorTy::Visit(EvalExpr);
1860 }
1861
1862 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00001863 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00001864 if (!Value) {
1865 const Expr *Source = E->getSourceExpr();
1866 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00001867 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00001868 if (Source == E) { // sanity checking.
1869 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00001870 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00001871 }
1872 return StmtVisitorTy::Visit(Source);
1873 }
Richard Smith47a1eed2011-10-29 20:57:55 +00001874 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001875 }
Richard Smithf10d9172011-10-11 21:43:33 +00001876
Richard Smithd0dccea2011-10-28 22:34:42 +00001877 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001878 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00001879 QualType CalleeType = Callee->getType();
1880
Richard Smithd0dccea2011-10-28 22:34:42 +00001881 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00001882 LValue *This = 0, ThisVal;
1883 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith6c957872011-11-10 09:31:24 +00001884
Richard Smith59efe262011-11-11 04:05:33 +00001885 // Extract function decl and 'this' pointer from the callee.
1886 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00001887 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001888 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
1889 // Explicit bound member calls, such as x.f() or p->g();
1890 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00001891 return false;
1892 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001893 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001894 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
1895 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00001896 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
1897 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001898 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001899 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00001900 return Error(Callee);
1901
1902 FD = dyn_cast<FunctionDecl>(Member);
1903 if (!FD)
1904 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00001905 } else if (CalleeType->isFunctionPointerType()) {
1906 CCValue Call;
Richard Smithf48fdb02011-12-09 22:58:01 +00001907 if (!Evaluate(Call, Info, Callee))
1908 return false;
Richard Smith59efe262011-11-11 04:05:33 +00001909
Richard Smithf48fdb02011-12-09 22:58:01 +00001910 if (!Call.isLValue() || !Call.getLValueOffset().isZero())
1911 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001912 FD = dyn_cast_or_null<FunctionDecl>(
1913 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00001914 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00001915 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00001916
1917 // Overloaded operator calls to member functions are represented as normal
1918 // calls with '*this' as the first argument.
1919 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1920 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00001921 // FIXME: When selecting an implicit conversion for an overloaded
1922 // operator delete, we sometimes try to evaluate calls to conversion
1923 // operators without a 'this' parameter!
1924 if (Args.empty())
1925 return Error(E);
1926
Richard Smith59efe262011-11-11 04:05:33 +00001927 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
1928 return false;
1929 This = &ThisVal;
1930 Args = Args.slice(1);
1931 }
1932
1933 // Don't call function pointers which have been cast to some other type.
1934 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00001935 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00001936 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00001937 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00001938
Richard Smithc1c5f272011-12-13 06:39:58 +00001939 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00001940 Stmt *Body = FD->getBody(Definition);
Richard Smith69c2c502011-11-04 05:33:44 +00001941 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00001942
Richard Smithc1c5f272011-12-13 06:39:58 +00001943 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith08d6e032011-12-16 19:06:07 +00001944 !HandleFunctionCall(E, Definition, This, Args, Body, Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00001945 return false;
1946
1947 return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
Richard Smithd0dccea2011-10-28 22:34:42 +00001948 }
1949
Richard Smithc49bd112011-10-28 17:51:58 +00001950 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1951 return StmtVisitorTy::Visit(E->getInitializer());
1952 }
Richard Smithf10d9172011-10-11 21:43:33 +00001953 RetTy VisitInitListExpr(const InitListExpr *E) {
1954 if (Info.getLangOpts().CPlusPlus0x) {
1955 if (E->getNumInits() == 0)
1956 return DerivedValueInitialization(E);
1957 if (E->getNumInits() == 1)
1958 return StmtVisitorTy::Visit(E->getInit(0));
1959 }
Richard Smithf48fdb02011-12-09 22:58:01 +00001960 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00001961 }
1962 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1963 return DerivedValueInitialization(E);
1964 }
1965 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
1966 return DerivedValueInitialization(E);
1967 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001968 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
1969 return DerivedValueInitialization(E);
1970 }
Richard Smithf10d9172011-10-11 21:43:33 +00001971
Richard Smith180f4792011-11-10 06:34:14 +00001972 /// A member expression where the object is a prvalue is itself a prvalue.
1973 RetTy VisitMemberExpr(const MemberExpr *E) {
1974 assert(!E->isArrow() && "missing call to bound member function?");
1975
1976 CCValue Val;
1977 if (!Evaluate(Val, Info, E->getBase()))
1978 return false;
1979
1980 QualType BaseTy = E->getBase()->getType();
1981
1982 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00001983 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00001984 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
1985 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
1986 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
1987
1988 SubobjectDesignator Designator;
1989 Designator.addDecl(FD);
1990
Richard Smithf48fdb02011-12-09 22:58:01 +00001991 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00001992 DerivedSuccess(Val, E);
1993 }
1994
Richard Smithc49bd112011-10-28 17:51:58 +00001995 RetTy VisitCastExpr(const CastExpr *E) {
1996 switch (E->getCastKind()) {
1997 default:
1998 break;
1999
2000 case CK_NoOp:
2001 return StmtVisitorTy::Visit(E->getSubExpr());
2002
2003 case CK_LValueToRValue: {
2004 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002005 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2006 return false;
2007 CCValue RVal;
2008 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2009 return false;
2010 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002011 }
2012 }
2013
Richard Smithf48fdb02011-12-09 22:58:01 +00002014 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002015 }
2016
Richard Smith8327fad2011-10-24 18:44:57 +00002017 /// Visit a value which is evaluated, but whose value is ignored.
2018 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002019 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002020 if (!Evaluate(Scratch, Info, E))
2021 Info.EvalStatus.HasSideEffects = true;
2022 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002023};
2024
2025}
2026
2027//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002028// Common base class for lvalue and temporary evaluation.
2029//===----------------------------------------------------------------------===//
2030namespace {
2031template<class Derived>
2032class LValueExprEvaluatorBase
2033 : public ExprEvaluatorBase<Derived, bool> {
2034protected:
2035 LValue &Result;
2036 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2037 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2038
2039 bool Success(APValue::LValueBase B) {
2040 Result.set(B);
2041 return true;
2042 }
2043
2044public:
2045 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2046 ExprEvaluatorBaseTy(Info), Result(Result) {}
2047
2048 bool Success(const CCValue &V, const Expr *E) {
2049 Result.setFrom(V);
2050 return true;
2051 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002052
2053 bool CheckValidLValue() {
2054 // C++11 [basic.lval]p1: An lvalue designates a function or an object. Hence
2055 // there are no null references, nor once-past-the-end references.
2056 // FIXME: Check for one-past-the-end array indices
2057 return Result.Base && !Result.Designator.Invalid &&
2058 !Result.Designator.OnePastTheEnd;
2059 }
2060
2061 bool VisitMemberExpr(const MemberExpr *E) {
2062 // Handle non-static data members.
2063 QualType BaseTy;
2064 if (E->isArrow()) {
2065 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2066 return false;
2067 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002068 } else if (E->getBase()->isRValue()) {
2069 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2070 return false;
2071 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002072 } else {
2073 if (!this->Visit(E->getBase()))
2074 return false;
2075 BaseTy = E->getBase()->getType();
2076 }
2077 // FIXME: In C++11, require the result to be a valid lvalue.
2078
2079 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2080 // FIXME: Handle IndirectFieldDecls
Richard Smithf48fdb02011-12-09 22:58:01 +00002081 if (!FD) return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002082 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2083 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2084 (void)BaseTy;
2085
2086 HandleLValueMember(this->Info, Result, FD);
2087
2088 if (FD->getType()->isReferenceType()) {
2089 CCValue RefValue;
Richard Smithf48fdb02011-12-09 22:58:01 +00002090 if (!HandleLValueToRValueConversion(this->Info, E, FD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002091 RefValue))
2092 return false;
2093 return Success(RefValue, E);
2094 }
2095 return true;
2096 }
2097
2098 bool VisitBinaryOperator(const BinaryOperator *E) {
2099 switch (E->getOpcode()) {
2100 default:
2101 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2102
2103 case BO_PtrMemD:
2104 case BO_PtrMemI:
2105 return HandleMemberPointerAccess(this->Info, E, Result);
2106 }
2107 }
2108
2109 bool VisitCastExpr(const CastExpr *E) {
2110 switch (E->getCastKind()) {
2111 default:
2112 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2113
2114 case CK_DerivedToBase:
2115 case CK_UncheckedDerivedToBase: {
2116 if (!this->Visit(E->getSubExpr()))
2117 return false;
2118 if (!CheckValidLValue())
2119 return false;
2120
2121 // Now figure out the necessary offset to add to the base LV to get from
2122 // the derived class to the base class.
2123 QualType Type = E->getSubExpr()->getType();
2124
2125 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2126 PathE = E->path_end(); PathI != PathE; ++PathI) {
2127 if (!HandleLValueBase(this->Info, Result, Type->getAsCXXRecordDecl(),
2128 *PathI))
2129 return false;
2130 Type = (*PathI)->getType();
2131 }
2132
2133 return true;
2134 }
2135 }
2136 }
2137};
2138}
2139
2140//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002141// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002142//
2143// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2144// function designators (in C), decl references to void objects (in C), and
2145// temporaries (if building with -Wno-address-of-temporary).
2146//
2147// LValue evaluation produces values comprising a base expression of one of the
2148// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002149// - Declarations
2150// * VarDecl
2151// * FunctionDecl
2152// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002153// * CompoundLiteralExpr in C
2154// * StringLiteral
2155// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002156// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002157// * ObjCEncodeExpr
2158// * AddrLabelExpr
2159// * BlockExpr
2160// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002161// - Locals and temporaries
2162// * Any Expr, with a Frame indicating the function in which the temporary was
2163// evaluated.
2164// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002165//===----------------------------------------------------------------------===//
2166namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002167class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002168 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002169public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002170 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2171 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002172
Richard Smithc49bd112011-10-28 17:51:58 +00002173 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2174
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002175 bool VisitDeclRefExpr(const DeclRefExpr *E);
2176 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002177 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002178 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2179 bool VisitMemberExpr(const MemberExpr *E);
2180 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2181 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
2182 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2183 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002184
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002185 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002186 switch (E->getCastKind()) {
2187 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002188 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002189
Eli Friedmandb924222011-10-11 00:13:24 +00002190 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002191 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002192 if (!Visit(E->getSubExpr()))
2193 return false;
2194 Result.Designator.setInvalid();
2195 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002196
Richard Smithe24f5fc2011-11-17 22:56:20 +00002197 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002198 if (!Visit(E->getSubExpr()))
2199 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002200 if (!CheckValidLValue())
2201 return false;
2202 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002203 }
2204 }
Sebastian Redlcea8d962011-09-24 17:48:14 +00002205
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002206 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002207
Eli Friedman4efaa272008-11-12 09:44:48 +00002208};
2209} // end anonymous namespace
2210
Richard Smithc49bd112011-10-28 17:51:58 +00002211/// Evaluate an expression as an lvalue. This can be legitimately called on
2212/// expressions which are not glvalues, in a few cases:
2213/// * function designators in C,
2214/// * "extern void" objects,
2215/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002216static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002217 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2218 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2219 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002220 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002221}
2222
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002223bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002224 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2225 return Success(FD);
2226 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002227 return VisitVarDecl(E, VD);
2228 return Error(E);
2229}
Richard Smith436c8892011-10-24 23:14:33 +00002230
Richard Smithc49bd112011-10-28 17:51:58 +00002231bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002232 if (!VD->getType()->isReferenceType()) {
2233 if (isa<ParmVarDecl>(VD)) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002234 Result.set(VD, Info.CurrentCall);
Richard Smith177dce72011-11-01 16:57:24 +00002235 return true;
2236 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002237 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002238 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002239
Richard Smith47a1eed2011-10-29 20:57:55 +00002240 CCValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002241 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2242 return false;
2243 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002244}
2245
Richard Smithbd552ef2011-10-31 05:52:43 +00002246bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2247 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002248 if (E->GetTemporaryExpr()->isRValue()) {
2249 if (E->getType()->isRecordType() && E->getType()->isLiteralType())
2250 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2251
2252 Result.set(E, Info.CurrentCall);
2253 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2254 Result, E->GetTemporaryExpr());
2255 }
2256
2257 // Materialization of an lvalue temporary occurs when we need to force a copy
2258 // (for instance, if it's a bitfield).
2259 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2260 if (!Visit(E->GetTemporaryExpr()))
2261 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002262 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002263 Info.CurrentCall->Temporaries[E]))
2264 return false;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002265 Result.set(E, Info.CurrentCall);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002266 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002267}
2268
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002269bool
2270LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002271 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2272 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2273 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002274 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002275}
2276
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002277bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002278 // Handle static data members.
2279 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2280 VisitIgnoredValue(E->getBase());
2281 return VisitVarDecl(E, VD);
2282 }
2283
Richard Smithd0dccea2011-10-28 22:34:42 +00002284 // Handle static member functions.
2285 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2286 if (MD->isStatic()) {
2287 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002288 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002289 }
2290 }
2291
Richard Smith180f4792011-11-10 06:34:14 +00002292 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002293 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002294}
2295
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002296bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002297 // FIXME: Deal with vectors as array subscript bases.
2298 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002299 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002300
Anders Carlsson3068d112008-11-16 19:01:22 +00002301 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002302 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002303
Anders Carlsson3068d112008-11-16 19:01:22 +00002304 APSInt Index;
2305 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002306 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002307 int64_t IndexValue
2308 = Index.isSigned() ? Index.getSExtValue()
2309 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00002310
Richard Smithe24f5fc2011-11-17 22:56:20 +00002311 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smith180f4792011-11-10 06:34:14 +00002312 return HandleLValueArrayAdjustment(Info, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00002313}
Eli Friedman4efaa272008-11-12 09:44:48 +00002314
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002315bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002316 // FIXME: In C++11, require the result to be a valid lvalue.
John McCallefdb83e2010-05-07 21:00:08 +00002317 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00002318}
2319
Eli Friedman4efaa272008-11-12 09:44:48 +00002320//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002321// Pointer Evaluation
2322//===----------------------------------------------------------------------===//
2323
Anders Carlssonc754aa62008-07-08 05:13:58 +00002324namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002325class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002326 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00002327 LValue &Result;
2328
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002329 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002330 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00002331 return true;
2332 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002333public:
Mike Stump1eb44332009-09-09 15:08:12 +00002334
John McCallefdb83e2010-05-07 21:00:08 +00002335 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002336 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002337
Richard Smith47a1eed2011-10-29 20:57:55 +00002338 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002339 Result.setFrom(V);
2340 return true;
2341 }
Richard Smithf10d9172011-10-11 21:43:33 +00002342 bool ValueInitialization(const Expr *E) {
2343 return Success((Expr*)0);
2344 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002345
John McCallefdb83e2010-05-07 21:00:08 +00002346 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002347 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00002348 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002349 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00002350 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002351 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00002352 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002353 bool VisitCallExpr(const CallExpr *E);
2354 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00002355 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00002356 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00002357 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00002358 }
Richard Smith180f4792011-11-10 06:34:14 +00002359 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2360 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00002361 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002362 Result = *Info.CurrentCall->This;
2363 return true;
2364 }
John McCall56ca35d2011-02-17 10:25:35 +00002365
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002366 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00002367};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002368} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00002369
John McCallefdb83e2010-05-07 21:00:08 +00002370static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002371 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002372 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002373}
2374
John McCallefdb83e2010-05-07 21:00:08 +00002375bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002376 if (E->getOpcode() != BO_Add &&
2377 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00002378 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002379
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002380 const Expr *PExp = E->getLHS();
2381 const Expr *IExp = E->getRHS();
2382 if (IExp->getType()->isPointerType())
2383 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002384
John McCallefdb83e2010-05-07 21:00:08 +00002385 if (!EvaluatePointer(PExp, Result, Info))
2386 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002387
John McCallefdb83e2010-05-07 21:00:08 +00002388 llvm::APSInt Offset;
2389 if (!EvaluateInteger(IExp, Offset, Info))
2390 return false;
2391 int64_t AdditionalOffset
2392 = Offset.isSigned() ? Offset.getSExtValue()
2393 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00002394 if (E->getOpcode() == BO_Sub)
2395 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002396
Richard Smith180f4792011-11-10 06:34:14 +00002397 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002398 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smith180f4792011-11-10 06:34:14 +00002399 return HandleLValueArrayAdjustment(Info, Result, Pointee, AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002400}
Eli Friedman4efaa272008-11-12 09:44:48 +00002401
John McCallefdb83e2010-05-07 21:00:08 +00002402bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2403 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002404}
Mike Stump1eb44332009-09-09 15:08:12 +00002405
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002406bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2407 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002408
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002409 switch (E->getCastKind()) {
2410 default:
2411 break;
2412
John McCall2de56d12010-08-25 11:45:40 +00002413 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002414 case CK_CPointerToObjCPointerCast:
2415 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00002416 case CK_AnyPointerToBlockPointerCast:
Richard Smithc216a012011-12-12 12:46:16 +00002417 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2418 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2419 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002420 if (!E->getType()->isVoidPointerType()) {
2421 if (SubExpr->getType()->isVoidPointerType())
2422 CCEDiag(E, diag::note_constexpr_invalid_cast)
2423 << 3 << SubExpr->getType();
2424 else
2425 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2426 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002427 if (!Visit(SubExpr))
2428 return false;
2429 Result.Designator.setInvalid();
2430 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002431
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002432 case CK_DerivedToBase:
2433 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00002434 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002435 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002436 if (!Result.Base && Result.Offset.isZero())
2437 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002438
Richard Smith180f4792011-11-10 06:34:14 +00002439 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002440 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00002441 QualType Type =
2442 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002443
Richard Smith180f4792011-11-10 06:34:14 +00002444 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002445 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smith180f4792011-11-10 06:34:14 +00002446 if (!HandleLValueBase(Info, Result, Type->getAsCXXRecordDecl(), *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002447 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002448 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002449 }
2450
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002451 return true;
2452 }
2453
Richard Smithe24f5fc2011-11-17 22:56:20 +00002454 case CK_BaseToDerived:
2455 if (!Visit(E->getSubExpr()))
2456 return false;
2457 if (!Result.Base && Result.Offset.isZero())
2458 return true;
2459 return HandleBaseToDerivedCast(Info, E, Result);
2460
Richard Smith47a1eed2011-10-29 20:57:55 +00002461 case CK_NullToPointer:
2462 return ValueInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00002463
John McCall2de56d12010-08-25 11:45:40 +00002464 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00002465 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2466
Richard Smith47a1eed2011-10-29 20:57:55 +00002467 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00002468 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002469 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00002470
John McCallefdb83e2010-05-07 21:00:08 +00002471 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002472 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2473 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002474 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00002475 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith177dce72011-11-01 16:57:24 +00002476 Result.Frame = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002477 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00002478 return true;
2479 } else {
2480 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00002481 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00002482 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002483 }
2484 }
John McCall2de56d12010-08-25 11:45:40 +00002485 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002486 if (SubExpr->isGLValue()) {
2487 if (!EvaluateLValue(SubExpr, Result, Info))
2488 return false;
2489 } else {
2490 Result.set(SubExpr, Info.CurrentCall);
2491 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2492 Info, Result, SubExpr))
2493 return false;
2494 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002495 // The result is a pointer to the first element of the array.
2496 Result.Designator.addIndex(0);
2497 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00002498
John McCall2de56d12010-08-25 11:45:40 +00002499 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00002500 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002501 }
2502
Richard Smithc49bd112011-10-28 17:51:58 +00002503 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002504}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002505
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002506bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00002507 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00002508 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00002509
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002510 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002511}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002512
2513//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002514// Member Pointer Evaluation
2515//===----------------------------------------------------------------------===//
2516
2517namespace {
2518class MemberPointerExprEvaluator
2519 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2520 MemberPtr &Result;
2521
2522 bool Success(const ValueDecl *D) {
2523 Result = MemberPtr(D);
2524 return true;
2525 }
2526public:
2527
2528 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2529 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2530
2531 bool Success(const CCValue &V, const Expr *E) {
2532 Result.setFrom(V);
2533 return true;
2534 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002535 bool ValueInitialization(const Expr *E) {
2536 return Success((const ValueDecl*)0);
2537 }
2538
2539 bool VisitCastExpr(const CastExpr *E);
2540 bool VisitUnaryAddrOf(const UnaryOperator *E);
2541};
2542} // end anonymous namespace
2543
2544static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2545 EvalInfo &Info) {
2546 assert(E->isRValue() && E->getType()->isMemberPointerType());
2547 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2548}
2549
2550bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2551 switch (E->getCastKind()) {
2552 default:
2553 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2554
2555 case CK_NullToMemberPointer:
2556 return ValueInitialization(E);
2557
2558 case CK_BaseToDerivedMemberPointer: {
2559 if (!Visit(E->getSubExpr()))
2560 return false;
2561 if (E->path_empty())
2562 return true;
2563 // Base-to-derived member pointer casts store the path in derived-to-base
2564 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2565 // the wrong end of the derived->base arc, so stagger the path by one class.
2566 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2567 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2568 PathI != PathE; ++PathI) {
2569 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2570 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2571 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00002572 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002573 }
2574 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2575 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002576 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002577 return true;
2578 }
2579
2580 case CK_DerivedToBaseMemberPointer:
2581 if (!Visit(E->getSubExpr()))
2582 return false;
2583 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2584 PathE = E->path_end(); PathI != PathE; ++PathI) {
2585 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2586 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2587 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00002588 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002589 }
2590 return true;
2591 }
2592}
2593
2594bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2595 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
2596 // member can be formed.
2597 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
2598}
2599
2600//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00002601// Record Evaluation
2602//===----------------------------------------------------------------------===//
2603
2604namespace {
2605 class RecordExprEvaluator
2606 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
2607 const LValue &This;
2608 APValue &Result;
2609 public:
2610
2611 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
2612 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
2613
2614 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002615 return CheckConstantExpression(Info, E, V, Result);
Richard Smith180f4792011-11-10 06:34:14 +00002616 }
Richard Smith180f4792011-11-10 06:34:14 +00002617
Richard Smith59efe262011-11-11 04:05:33 +00002618 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00002619 bool VisitInitListExpr(const InitListExpr *E);
2620 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
2621 };
2622}
2623
Richard Smith59efe262011-11-11 04:05:33 +00002624bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
2625 switch (E->getCastKind()) {
2626 default:
2627 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2628
2629 case CK_ConstructorConversion:
2630 return Visit(E->getSubExpr());
2631
2632 case CK_DerivedToBase:
2633 case CK_UncheckedDerivedToBase: {
2634 CCValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00002635 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00002636 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002637 if (!DerivedObject.isStruct())
2638 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00002639
2640 // Derived-to-base rvalue conversion: just slice off the derived part.
2641 APValue *Value = &DerivedObject;
2642 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
2643 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2644 PathE = E->path_end(); PathI != PathE; ++PathI) {
2645 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
2646 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2647 Value = &Value->getStructBase(getBaseIndex(RD, Base));
2648 RD = Base;
2649 }
2650 Result = *Value;
2651 return true;
2652 }
2653 }
2654}
2655
Richard Smith180f4792011-11-10 06:34:14 +00002656bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2657 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2658 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2659
2660 if (RD->isUnion()) {
2661 Result = APValue(E->getInitializedFieldInUnion());
2662 if (!E->getNumInits())
2663 return true;
2664 LValue Subobject = This;
2665 HandleLValueMember(Info, Subobject, E->getInitializedFieldInUnion(),
2666 &Layout);
2667 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2668 Subobject, E->getInit(0));
2669 }
2670
2671 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
2672 "initializer list for class with base classes");
2673 Result = APValue(APValue::UninitStruct(), 0,
2674 std::distance(RD->field_begin(), RD->field_end()));
2675 unsigned ElementNo = 0;
2676 for (RecordDecl::field_iterator Field = RD->field_begin(),
2677 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
2678 // Anonymous bit-fields are not considered members of the class for
2679 // purposes of aggregate initialization.
2680 if (Field->isUnnamedBitfield())
2681 continue;
2682
2683 LValue Subobject = This;
2684 HandleLValueMember(Info, Subobject, *Field, &Layout);
2685
2686 if (ElementNo < E->getNumInits()) {
2687 if (!EvaluateConstantExpression(
2688 Result.getStructField((*Field)->getFieldIndex()),
2689 Info, Subobject, E->getInit(ElementNo++)))
2690 return false;
2691 } else {
2692 // Perform an implicit value-initialization for members beyond the end of
2693 // the initializer list.
2694 ImplicitValueInitExpr VIE(Field->getType());
2695 if (!EvaluateConstantExpression(
2696 Result.getStructField((*Field)->getFieldIndex()),
2697 Info, Subobject, &VIE))
2698 return false;
2699 }
2700 }
2701
2702 return true;
2703}
2704
2705bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
2706 const CXXConstructorDecl *FD = E->getConstructor();
2707 const FunctionDecl *Definition = 0;
2708 FD->getBody(Definition);
2709
Richard Smithc1c5f272011-12-13 06:39:58 +00002710 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
2711 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002712
2713 // FIXME: Elide the copy/move construction wherever we can.
2714 if (E->isElidable())
2715 if (const MaterializeTemporaryExpr *ME
2716 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
2717 return Visit(ME->GetTemporaryExpr());
2718
2719 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf48fdb02011-12-09 22:58:01 +00002720 return HandleConstructorCall(E, This, Args,
2721 cast<CXXConstructorDecl>(Definition), Info,
2722 Result);
Richard Smith180f4792011-11-10 06:34:14 +00002723}
2724
2725static bool EvaluateRecord(const Expr *E, const LValue &This,
2726 APValue &Result, EvalInfo &Info) {
2727 assert(E->isRValue() && E->getType()->isRecordType() &&
2728 E->getType()->isLiteralType() &&
2729 "can't evaluate expression as a record rvalue");
2730 return RecordExprEvaluator(Info, This, Result).Visit(E);
2731}
2732
2733//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002734// Temporary Evaluation
2735//
2736// Temporaries are represented in the AST as rvalues, but generally behave like
2737// lvalues. The full-object of which the temporary is a subobject is implicitly
2738// materialized so that a reference can bind to it.
2739//===----------------------------------------------------------------------===//
2740namespace {
2741class TemporaryExprEvaluator
2742 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
2743public:
2744 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
2745 LValueExprEvaluatorBaseTy(Info, Result) {}
2746
2747 /// Visit an expression which constructs the value of this temporary.
2748 bool VisitConstructExpr(const Expr *E) {
2749 Result.set(E, Info.CurrentCall);
2750 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2751 Result, E);
2752 }
2753
2754 bool VisitCastExpr(const CastExpr *E) {
2755 switch (E->getCastKind()) {
2756 default:
2757 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
2758
2759 case CK_ConstructorConversion:
2760 return VisitConstructExpr(E->getSubExpr());
2761 }
2762 }
2763 bool VisitInitListExpr(const InitListExpr *E) {
2764 return VisitConstructExpr(E);
2765 }
2766 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
2767 return VisitConstructExpr(E);
2768 }
2769 bool VisitCallExpr(const CallExpr *E) {
2770 return VisitConstructExpr(E);
2771 }
2772};
2773} // end anonymous namespace
2774
2775/// Evaluate an expression of record type as a temporary.
2776static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
2777 assert(E->isRValue() && E->getType()->isRecordType() &&
2778 E->getType()->isLiteralType());
2779 return TemporaryExprEvaluator(Info, Result).Visit(E);
2780}
2781
2782//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00002783// Vector Evaluation
2784//===----------------------------------------------------------------------===//
2785
2786namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002787 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00002788 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
2789 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00002790 public:
Mike Stump1eb44332009-09-09 15:08:12 +00002791
Richard Smith07fc6572011-10-22 21:10:00 +00002792 VectorExprEvaluator(EvalInfo &info, APValue &Result)
2793 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002794
Richard Smith07fc6572011-10-22 21:10:00 +00002795 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
2796 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
2797 // FIXME: remove this APValue copy.
2798 Result = APValue(V.data(), V.size());
2799 return true;
2800 }
Richard Smith69c2c502011-11-04 05:33:44 +00002801 bool Success(const CCValue &V, const Expr *E) {
2802 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00002803 Result = V;
2804 return true;
2805 }
Richard Smith07fc6572011-10-22 21:10:00 +00002806 bool ValueInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002807
Richard Smith07fc6572011-10-22 21:10:00 +00002808 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00002809 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00002810 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00002811 bool VisitInitListExpr(const InitListExpr *E);
2812 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00002813 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00002814 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00002815 // shufflevector, ExtVectorElementExpr
2816 // (Note that these require implementing conversions
2817 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +00002818 };
2819} // end anonymous namespace
2820
2821static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002822 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00002823 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00002824}
2825
Richard Smith07fc6572011-10-22 21:10:00 +00002826bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
2827 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00002828 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00002829
Richard Smithd62ca372011-12-06 22:44:34 +00002830 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00002831 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00002832
Eli Friedman46a52322011-03-25 00:43:55 +00002833 switch (E->getCastKind()) {
2834 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00002835 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00002836 if (SETy->isIntegerType()) {
2837 APSInt IntResult;
2838 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002839 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00002840 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00002841 } else if (SETy->isRealFloatingType()) {
2842 APFloat F(0.0);
2843 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002844 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00002845 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00002846 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00002847 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00002848 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00002849
2850 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00002851 SmallVector<APValue, 4> Elts(NElts, Val);
2852 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00002853 }
Eli Friedman46a52322011-03-25 00:43:55 +00002854 default:
Richard Smithc49bd112011-10-28 17:51:58 +00002855 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00002856 }
Nate Begeman59b5da62009-01-18 03:20:47 +00002857}
2858
Richard Smith07fc6572011-10-22 21:10:00 +00002859bool
Nate Begeman59b5da62009-01-18 03:20:47 +00002860VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00002861 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00002862 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00002863 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00002864
Nate Begeman59b5da62009-01-18 03:20:47 +00002865 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002866 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00002867
John McCalla7d6c222010-06-11 17:54:15 +00002868 // If a vector is initialized with a single element, that value
2869 // becomes every element of the vector, not just the first.
2870 // This is the behavior described in the IBM AltiVec documentation.
2871 if (NumInits == 1) {
Richard Smith07fc6572011-10-22 21:10:00 +00002872
2873 // Handle the case where the vector is initialized by another
Tanya Lattnerb92ae0e2011-04-15 22:42:59 +00002874 // vector (OpenCL 6.1.6).
2875 if (E->getInit(0)->getType()->isVectorType())
Richard Smith07fc6572011-10-22 21:10:00 +00002876 return Visit(E->getInit(0));
2877
John McCalla7d6c222010-06-11 17:54:15 +00002878 APValue InitValue;
Nate Begeman59b5da62009-01-18 03:20:47 +00002879 if (EltTy->isIntegerType()) {
2880 llvm::APSInt sInt(32);
John McCalla7d6c222010-06-11 17:54:15 +00002881 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002882 return false;
John McCalla7d6c222010-06-11 17:54:15 +00002883 InitValue = APValue(sInt);
Nate Begeman59b5da62009-01-18 03:20:47 +00002884 } else {
2885 llvm::APFloat f(0.0);
John McCalla7d6c222010-06-11 17:54:15 +00002886 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002887 return false;
John McCalla7d6c222010-06-11 17:54:15 +00002888 InitValue = APValue(f);
2889 }
2890 for (unsigned i = 0; i < NumElements; i++) {
2891 Elements.push_back(InitValue);
2892 }
2893 } else {
2894 for (unsigned i = 0; i < NumElements; i++) {
2895 if (EltTy->isIntegerType()) {
2896 llvm::APSInt sInt(32);
2897 if (i < NumInits) {
2898 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002899 return false;
John McCalla7d6c222010-06-11 17:54:15 +00002900 } else {
2901 sInt = Info.Ctx.MakeIntValue(0, EltTy);
2902 }
2903 Elements.push_back(APValue(sInt));
Eli Friedman91110ee2009-02-23 04:23:56 +00002904 } else {
John McCalla7d6c222010-06-11 17:54:15 +00002905 llvm::APFloat f(0.0);
2906 if (i < NumInits) {
2907 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002908 return false;
John McCalla7d6c222010-06-11 17:54:15 +00002909 } else {
2910 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
2911 }
2912 Elements.push_back(APValue(f));
Eli Friedman91110ee2009-02-23 04:23:56 +00002913 }
Nate Begeman59b5da62009-01-18 03:20:47 +00002914 }
2915 }
Richard Smith07fc6572011-10-22 21:10:00 +00002916 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00002917}
2918
Richard Smith07fc6572011-10-22 21:10:00 +00002919bool
2920VectorExprEvaluator::ValueInitialization(const Expr *E) {
2921 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00002922 QualType EltTy = VT->getElementType();
2923 APValue ZeroElement;
2924 if (EltTy->isIntegerType())
2925 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
2926 else
2927 ZeroElement =
2928 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
2929
Chris Lattner5f9e2722011-07-23 10:55:15 +00002930 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00002931 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00002932}
2933
Richard Smith07fc6572011-10-22 21:10:00 +00002934bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00002935 VisitIgnoredValue(E->getSubExpr());
Richard Smith07fc6572011-10-22 21:10:00 +00002936 return ValueInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00002937}
2938
Nate Begeman59b5da62009-01-18 03:20:47 +00002939//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00002940// Array Evaluation
2941//===----------------------------------------------------------------------===//
2942
2943namespace {
2944 class ArrayExprEvaluator
2945 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00002946 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00002947 APValue &Result;
2948 public:
2949
Richard Smith180f4792011-11-10 06:34:14 +00002950 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
2951 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00002952
2953 bool Success(const APValue &V, const Expr *E) {
2954 assert(V.isArray() && "Expected array type");
2955 Result = V;
2956 return true;
2957 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00002958
Richard Smith180f4792011-11-10 06:34:14 +00002959 bool ValueInitialization(const Expr *E) {
2960 const ConstantArrayType *CAT =
2961 Info.Ctx.getAsConstantArrayType(E->getType());
2962 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00002963 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002964
2965 Result = APValue(APValue::UninitArray(), 0,
2966 CAT->getSize().getZExtValue());
2967 if (!Result.hasArrayFiller()) return true;
2968
2969 // Value-initialize all elements.
2970 LValue Subobject = This;
2971 Subobject.Designator.addIndex(0);
2972 ImplicitValueInitExpr VIE(CAT->getElementType());
2973 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
2974 Subobject, &VIE);
2975 }
2976
Richard Smithcc5d4f62011-11-07 09:22:26 +00002977 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002978 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00002979 };
2980} // end anonymous namespace
2981
Richard Smith180f4792011-11-10 06:34:14 +00002982static bool EvaluateArray(const Expr *E, const LValue &This,
2983 APValue &Result, EvalInfo &Info) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00002984 assert(E->isRValue() && E->getType()->isArrayType() &&
2985 E->getType()->isLiteralType() && "not a literal array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00002986 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00002987}
2988
2989bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2990 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
2991 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00002992 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00002993
2994 Result = APValue(APValue::UninitArray(), E->getNumInits(),
2995 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00002996 LValue Subobject = This;
2997 Subobject.Designator.addIndex(0);
2998 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00002999 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003000 I != End; ++I, ++Index) {
3001 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
3002 Info, Subobject, cast<Expr>(*I)))
Richard Smithcc5d4f62011-11-07 09:22:26 +00003003 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003004 if (!HandleLValueArrayAdjustment(Info, Subobject, CAT->getElementType(), 1))
3005 return false;
3006 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003007
3008 if (!Result.hasArrayFiller()) return true;
3009 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003010 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3011 // but sometimes does:
3012 // struct S { constexpr S() : p(&p) {} void *p; };
3013 // S s[10] = {};
Richard Smithcc5d4f62011-11-07 09:22:26 +00003014 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smith180f4792011-11-10 06:34:14 +00003015 Subobject, E->getArrayFiller());
Richard Smithcc5d4f62011-11-07 09:22:26 +00003016}
3017
Richard Smithe24f5fc2011-11-17 22:56:20 +00003018bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3019 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3020 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003021 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003022
3023 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3024 if (!Result.hasArrayFiller())
3025 return true;
3026
3027 const CXXConstructorDecl *FD = E->getConstructor();
3028 const FunctionDecl *Definition = 0;
3029 FD->getBody(Definition);
3030
Richard Smithc1c5f272011-12-13 06:39:58 +00003031 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3032 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003033
3034 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3035 // but sometimes does:
3036 // struct S { constexpr S() : p(&p) {} void *p; };
3037 // S s[10];
3038 LValue Subobject = This;
3039 Subobject.Designator.addIndex(0);
3040 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf48fdb02011-12-09 22:58:01 +00003041 return HandleConstructorCall(E, Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003042 cast<CXXConstructorDecl>(Definition),
3043 Info, Result.getArrayFiller());
3044}
3045
Richard Smithcc5d4f62011-11-07 09:22:26 +00003046//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003047// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003048//
3049// As a GNU extension, we support casting pointers to sufficiently-wide integer
3050// types and back in constant folding. Integer values are thus represented
3051// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003052//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003053
3054namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003055class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003056 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00003057 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003058public:
Richard Smith47a1eed2011-10-29 20:57:55 +00003059 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003060 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003061
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003062 bool Success(const llvm::APSInt &SI, const Expr *E) {
3063 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003064 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003065 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003066 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003067 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003068 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003069 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003070 return true;
3071 }
3072
Daniel Dunbar131eb432009-02-19 09:06:44 +00003073 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003074 assert(E->getType()->isIntegralOrEnumerationType() &&
3075 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003076 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003077 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003078 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003079 Result.getInt().setIsUnsigned(
3080 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003081 return true;
3082 }
3083
3084 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003085 assert(E->getType()->isIntegralOrEnumerationType() &&
3086 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003087 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003088 return true;
3089 }
3090
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003091 bool Success(CharUnits Size, const Expr *E) {
3092 return Success(Size.getQuantity(), E);
3093 }
3094
Richard Smith47a1eed2011-10-29 20:57:55 +00003095 bool Success(const CCValue &V, const Expr *E) {
Richard Smith342f1f82011-10-29 22:55:55 +00003096 if (V.isLValue()) {
3097 Result = V;
3098 return true;
3099 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003100 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003101 }
Mike Stump1eb44332009-09-09 15:08:12 +00003102
Richard Smithf10d9172011-10-11 21:43:33 +00003103 bool ValueInitialization(const Expr *E) { return Success(0, E); }
3104
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003105 //===--------------------------------------------------------------------===//
3106 // Visitor Methods
3107 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003108
Chris Lattner4c4867e2008-07-12 00:38:25 +00003109 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003110 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003111 }
3112 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003113 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003114 }
Eli Friedman04309752009-11-24 05:28:59 +00003115
3116 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3117 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003118 if (CheckReferencedDecl(E, E->getDecl()))
3119 return true;
3120
3121 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003122 }
3123 bool VisitMemberExpr(const MemberExpr *E) {
3124 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00003125 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00003126 return true;
3127 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003128
3129 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003130 }
3131
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003132 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003133 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003134 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003135 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00003136
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003137 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003138 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00003139
Anders Carlsson3068d112008-11-16 19:01:22 +00003140 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003141 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00003142 }
Mike Stump1eb44332009-09-09 15:08:12 +00003143
Richard Smithf10d9172011-10-11 21:43:33 +00003144 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00003145 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00003146 return ValueInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00003147 }
3148
Sebastian Redl64b45f72009-01-05 20:52:13 +00003149 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003150 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003151 }
3152
Francois Pichet6ad6f282010-12-07 00:08:36 +00003153 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3154 return Success(E->getValue(), E);
3155 }
3156
John Wiegley21ff2e52011-04-28 00:16:57 +00003157 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3158 return Success(E->getValue(), E);
3159 }
3160
John Wiegley55262202011-04-25 06:54:41 +00003161 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3162 return Success(E->getValue(), E);
3163 }
3164
Eli Friedman722c7172009-02-28 03:59:05 +00003165 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003166 bool VisitUnaryImag(const UnaryOperator *E);
3167
Sebastian Redl295995c2010-09-10 20:55:47 +00003168 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00003169 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00003170
Chris Lattnerfcee0012008-07-11 21:24:13 +00003171private:
Ken Dyck8b752f12010-01-27 17:10:57 +00003172 CharUnits GetAlignOfExpr(const Expr *E);
3173 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003174 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003175 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003176 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003177};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003178} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003179
Richard Smithc49bd112011-10-28 17:51:58 +00003180/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3181/// produce either the integer value or a pointer.
3182///
3183/// GCC has a heinous extension which folds casts between pointer types and
3184/// pointer-sized integral types. We support this by allowing the evaluation of
3185/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3186/// Some simple arithmetic on such values is supported (they are treated much
3187/// like char*).
Richard Smithf48fdb02011-12-09 22:58:01 +00003188static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00003189 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003190 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003191 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003192}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003193
Richard Smithf48fdb02011-12-09 22:58:01 +00003194static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003195 CCValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00003196 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003197 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003198 if (!Val.isInt()) {
3199 // FIXME: It would be better to produce the diagnostic for casting
3200 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00003201 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00003202 return false;
3203 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003204 Result = Val.getInt();
3205 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00003206}
Anders Carlsson650c92f2008-07-08 15:34:11 +00003207
Richard Smithf48fdb02011-12-09 22:58:01 +00003208/// Check whether the given declaration can be directly converted to an integral
3209/// rvalue. If not, no diagnostic is produced; there are other things we can
3210/// try.
Eli Friedman04309752009-11-24 05:28:59 +00003211bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00003212 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003213 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003214 // Check for signedness/width mismatches between E type and ECD value.
3215 bool SameSign = (ECD->getInitVal().isSigned()
3216 == E->getType()->isSignedIntegerOrEnumerationType());
3217 bool SameWidth = (ECD->getInitVal().getBitWidth()
3218 == Info.Ctx.getIntWidth(E->getType()));
3219 if (SameSign && SameWidth)
3220 return Success(ECD->getInitVal(), E);
3221 else {
3222 // Get rid of mismatch (otherwise Success assertions will fail)
3223 // by computing a new value matching the type of E.
3224 llvm::APSInt Val = ECD->getInitVal();
3225 if (!SameSign)
3226 Val.setIsSigned(!ECD->getInitVal().isSigned());
3227 if (!SameWidth)
3228 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3229 return Success(Val, E);
3230 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003231 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003232 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00003233}
3234
Chris Lattnera4d55d82008-10-06 06:40:35 +00003235/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3236/// as GCC.
3237static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3238 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003239 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00003240 enum gcc_type_class {
3241 no_type_class = -1,
3242 void_type_class, integer_type_class, char_type_class,
3243 enumeral_type_class, boolean_type_class,
3244 pointer_type_class, reference_type_class, offset_type_class,
3245 real_type_class, complex_type_class,
3246 function_type_class, method_type_class,
3247 record_type_class, union_type_class,
3248 array_type_class, string_type_class,
3249 lang_type_class
3250 };
Mike Stump1eb44332009-09-09 15:08:12 +00003251
3252 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00003253 // ideal, however it is what gcc does.
3254 if (E->getNumArgs() == 0)
3255 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00003256
Chris Lattnera4d55d82008-10-06 06:40:35 +00003257 QualType ArgTy = E->getArg(0)->getType();
3258 if (ArgTy->isVoidType())
3259 return void_type_class;
3260 else if (ArgTy->isEnumeralType())
3261 return enumeral_type_class;
3262 else if (ArgTy->isBooleanType())
3263 return boolean_type_class;
3264 else if (ArgTy->isCharType())
3265 return string_type_class; // gcc doesn't appear to use char_type_class
3266 else if (ArgTy->isIntegerType())
3267 return integer_type_class;
3268 else if (ArgTy->isPointerType())
3269 return pointer_type_class;
3270 else if (ArgTy->isReferenceType())
3271 return reference_type_class;
3272 else if (ArgTy->isRealType())
3273 return real_type_class;
3274 else if (ArgTy->isComplexType())
3275 return complex_type_class;
3276 else if (ArgTy->isFunctionType())
3277 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00003278 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00003279 return record_type_class;
3280 else if (ArgTy->isUnionType())
3281 return union_type_class;
3282 else if (ArgTy->isArrayType())
3283 return array_type_class;
3284 else if (ArgTy->isUnionType())
3285 return union_type_class;
3286 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00003287 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00003288 return -1;
3289}
3290
John McCall42c8f872010-05-10 23:27:23 +00003291/// Retrieves the "underlying object type" of the given expression,
3292/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003293QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3294 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3295 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00003296 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003297 } else if (const Expr *E = B.get<const Expr*>()) {
3298 if (isa<CompoundLiteralExpr>(E))
3299 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00003300 }
3301
3302 return QualType();
3303}
3304
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003305bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00003306 // TODO: Perhaps we should let LLVM lower this?
3307 LValue Base;
3308 if (!EvaluatePointer(E->getArg(0), Base, Info))
3309 return false;
3310
3311 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003312 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00003313
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003314 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00003315 if (T.isNull() ||
3316 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00003317 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00003318 T->isVariablyModifiedType() ||
3319 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00003320 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00003321
3322 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3323 CharUnits Offset = Base.getLValueOffset();
3324
3325 if (!Offset.isNegative() && Offset <= Size)
3326 Size -= Offset;
3327 else
3328 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003329 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00003330}
3331
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003332bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003333 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00003334 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003335 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003336
3337 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00003338 if (TryEvaluateBuiltinObjectSize(E))
3339 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00003340
Eric Christopherb2aaf512010-01-19 22:58:35 +00003341 // If evaluating the argument has side-effects we can't determine
3342 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00003343 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003344 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00003345 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003346 return Success(0, E);
3347 }
Mike Stumpc4c90452009-10-27 22:09:17 +00003348
Richard Smithf48fdb02011-12-09 22:58:01 +00003349 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003350 }
3351
Chris Lattner019f4e82008-10-06 05:28:25 +00003352 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003353 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00003354
Richard Smithe052d462011-12-09 02:04:48 +00003355 case Builtin::BI__builtin_constant_p: {
3356 const Expr *Arg = E->getArg(0);
3357 QualType ArgType = Arg->getType();
3358 // __builtin_constant_p always has one operand. The rules which gcc follows
3359 // are not precisely documented, but are as follows:
3360 //
3361 // - If the operand is of integral, floating, complex or enumeration type,
3362 // and can be folded to a known value of that type, it returns 1.
3363 // - If the operand and can be folded to a pointer to the first character
3364 // of a string literal (or such a pointer cast to an integral type), it
3365 // returns 1.
3366 //
3367 // Otherwise, it returns 0.
3368 //
3369 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3370 // its support for this does not currently work.
3371 int IsConstant = 0;
3372 if (ArgType->isIntegralOrEnumerationType()) {
3373 // Note, a pointer cast to an integral type is only a constant if it is
3374 // a pointer to the first character of a string literal.
3375 Expr::EvalResult Result;
3376 if (Arg->EvaluateAsRValue(Result, Info.Ctx) && !Result.HasSideEffects) {
3377 APValue &V = Result.Val;
3378 if (V.getKind() == APValue::LValue) {
3379 if (const Expr *E = V.getLValueBase().dyn_cast<const Expr*>())
3380 IsConstant = isa<StringLiteral>(E) && V.getLValueOffset().isZero();
3381 } else {
3382 IsConstant = 1;
3383 }
3384 }
3385 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3386 IsConstant = Arg->isEvaluatable(Info.Ctx);
3387 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3388 LValue LV;
3389 // Use a separate EvalInfo: ignore constexpr parameter and 'this' bindings
3390 // during the check.
3391 Expr::EvalStatus Status;
3392 EvalInfo SubInfo(Info.Ctx, Status);
3393 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, SubInfo)
3394 : EvaluatePointer(Arg, LV, SubInfo)) &&
3395 !Status.HasSideEffects)
3396 if (const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>())
3397 IsConstant = isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3398 }
3399
3400 return Success(IsConstant, E);
3401 }
Chris Lattner21fb98e2009-09-23 06:06:36 +00003402 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003403 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003404 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00003405 return Success(Operand, E);
3406 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00003407
3408 case Builtin::BI__builtin_expect:
3409 return Visit(E->getArg(0));
Douglas Gregor5726d402010-09-10 06:27:15 +00003410
3411 case Builtin::BIstrlen:
3412 case Builtin::BI__builtin_strlen:
3413 // As an extension, we support strlen() and __builtin_strlen() as constant
3414 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003415 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00003416 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
3417 // The string literal may have embedded null characters. Find the first
3418 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003419 StringRef Str = S->getString();
3420 StringRef::size_type Pos = Str.find(0);
3421 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00003422 Str = Str.substr(0, Pos);
3423
3424 return Success(Str.size(), E);
3425 }
3426
Richard Smithf48fdb02011-12-09 22:58:01 +00003427 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00003428
3429 case Builtin::BI__atomic_is_lock_free: {
3430 APSInt SizeVal;
3431 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
3432 return false;
3433
3434 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
3435 // of two less than the maximum inline atomic width, we know it is
3436 // lock-free. If the size isn't a power of two, or greater than the
3437 // maximum alignment where we promote atomics, we know it is not lock-free
3438 // (at least not in the sense of atomic_is_lock_free). Otherwise,
3439 // the answer can only be determined at runtime; for example, 16-byte
3440 // atomics have lock-free implementations on some, but not all,
3441 // x86-64 processors.
3442
3443 // Check power-of-two.
3444 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
3445 if (!Size.isPowerOfTwo())
3446#if 0
3447 // FIXME: Suppress this folding until the ABI for the promotion width
3448 // settles.
3449 return Success(0, E);
3450#else
Richard Smithf48fdb02011-12-09 22:58:01 +00003451 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00003452#endif
3453
3454#if 0
3455 // Check against promotion width.
3456 // FIXME: Suppress this folding until the ABI for the promotion width
3457 // settles.
3458 unsigned PromoteWidthBits =
3459 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
3460 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
3461 return Success(0, E);
3462#endif
3463
3464 // Check against inlining width.
3465 unsigned InlineWidthBits =
3466 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
3467 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
3468 return Success(1, E);
3469
Richard Smithf48fdb02011-12-09 22:58:01 +00003470 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00003471 }
Chris Lattner019f4e82008-10-06 05:28:25 +00003472 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00003473}
Anders Carlsson650c92f2008-07-08 15:34:11 +00003474
Richard Smith625b8072011-10-31 01:37:14 +00003475static bool HasSameBase(const LValue &A, const LValue &B) {
3476 if (!A.getLValueBase())
3477 return !B.getLValueBase();
3478 if (!B.getLValueBase())
3479 return false;
3480
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003481 if (A.getLValueBase().getOpaqueValue() !=
3482 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00003483 const Decl *ADecl = GetLValueBaseDecl(A);
3484 if (!ADecl)
3485 return false;
3486 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00003487 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00003488 return false;
3489 }
3490
3491 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith177dce72011-11-01 16:57:24 +00003492 A.getLValueFrame() == B.getLValueFrame();
Richard Smith625b8072011-10-31 01:37:14 +00003493}
3494
Chris Lattnerb542afe2008-07-11 19:10:17 +00003495bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00003496 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00003497 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00003498
John McCall2de56d12010-08-25 11:45:40 +00003499 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00003500 VisitIgnoredValue(E->getLHS());
3501 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00003502 }
3503
3504 if (E->isLogicalOp()) {
3505 // These need to be handled specially because the operands aren't
3506 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00003507 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00003508
Richard Smithc49bd112011-10-28 17:51:58 +00003509 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00003510 // We were able to evaluate the LHS, see if we can get away with not
3511 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00003512 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003513 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003514
Richard Smithc49bd112011-10-28 17:51:58 +00003515 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00003516 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00003517 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003518 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00003519 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003520 }
3521 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00003522 // FIXME: If both evaluations fail, we should produce the diagnostic from
3523 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
3524 // less clear how to diagnose this.
Richard Smithc49bd112011-10-28 17:51:58 +00003525 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003526 // We can't evaluate the LHS; however, sometimes the result
3527 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf48fdb02011-12-09 22:58:01 +00003528 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003529 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00003530 // must have had side effects.
Richard Smith1e12c592011-10-16 21:26:27 +00003531 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00003532
3533 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003534 }
3535 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00003536 }
Eli Friedmana6afa762008-11-13 06:09:17 +00003537
Eli Friedmana6afa762008-11-13 06:09:17 +00003538 return false;
3539 }
3540
Anders Carlsson286f85e2008-11-16 07:17:21 +00003541 QualType LHSTy = E->getLHS()->getType();
3542 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00003543
3544 if (LHSTy->isAnyComplexType()) {
3545 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00003546 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00003547
3548 if (!EvaluateComplex(E->getLHS(), LHS, Info))
3549 return false;
3550
3551 if (!EvaluateComplex(E->getRHS(), RHS, Info))
3552 return false;
3553
3554 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003555 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00003556 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00003557 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00003558 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
3559
John McCall2de56d12010-08-25 11:45:40 +00003560 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00003561 return Success((CR_r == APFloat::cmpEqual &&
3562 CR_i == APFloat::cmpEqual), E);
3563 else {
John McCall2de56d12010-08-25 11:45:40 +00003564 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00003565 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00003566 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00003567 CR_r == APFloat::cmpLessThan ||
3568 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00003569 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00003570 CR_i == APFloat::cmpLessThan ||
3571 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00003572 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00003573 } else {
John McCall2de56d12010-08-25 11:45:40 +00003574 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00003575 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
3576 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
3577 else {
John McCall2de56d12010-08-25 11:45:40 +00003578 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00003579 "Invalid compex comparison.");
3580 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
3581 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
3582 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00003583 }
3584 }
Mike Stump1eb44332009-09-09 15:08:12 +00003585
Anders Carlsson286f85e2008-11-16 07:17:21 +00003586 if (LHSTy->isRealFloatingType() &&
3587 RHSTy->isRealFloatingType()) {
3588 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00003589
Anders Carlsson286f85e2008-11-16 07:17:21 +00003590 if (!EvaluateFloat(E->getRHS(), RHS, Info))
3591 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003592
Anders Carlsson286f85e2008-11-16 07:17:21 +00003593 if (!EvaluateFloat(E->getLHS(), LHS, Info))
3594 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003595
Anders Carlsson286f85e2008-11-16 07:17:21 +00003596 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00003597
Anders Carlsson286f85e2008-11-16 07:17:21 +00003598 switch (E->getOpcode()) {
3599 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00003600 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00003601 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003602 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00003603 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003604 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00003605 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003606 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00003607 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00003608 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00003609 E);
John McCall2de56d12010-08-25 11:45:40 +00003610 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003611 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00003612 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00003613 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00003614 || CR == APFloat::cmpLessThan
3615 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00003616 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00003617 }
Mike Stump1eb44332009-09-09 15:08:12 +00003618
Eli Friedmanad02d7d2009-04-28 19:17:36 +00003619 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00003620 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00003621 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00003622 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
3623 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00003624
John McCallefdb83e2010-05-07 21:00:08 +00003625 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00003626 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
3627 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00003628
Richard Smith625b8072011-10-31 01:37:14 +00003629 // Reject differing bases from the normal codepath; we special-case
3630 // comparisons to null.
3631 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith9e36b532011-10-31 05:11:32 +00003632 // Inequalities and subtractions between unrelated pointers have
3633 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00003634 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00003635 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00003636 // A constant address may compare equal to the address of a symbol.
3637 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00003638 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00003639 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
3640 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003641 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00003642 // It's implementation-defined whether distinct literals will have
Eli Friedmanc45061b2011-10-31 22:54:30 +00003643 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smith74f46342011-11-04 01:10:57 +00003644 // distinct. However, we do know that the address of a literal will be
3645 // non-null.
3646 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
3647 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00003648 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00003649 // We can't tell whether weak symbols will end up pointing to the same
3650 // object.
3651 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00003652 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00003653 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00003654 // (Note that clang defaults to -fmerge-all-constants, which can
3655 // lead to inconsistent results for comparisons involving the address
3656 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00003657 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00003658 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00003659
Richard Smithcc5d4f62011-11-07 09:22:26 +00003660 // FIXME: Implement the C++11 restrictions:
3661 // - Pointer subtractions must be on elements of the same array.
3662 // - Pointer comparisons must be between members with the same access.
3663
John McCall2de56d12010-08-25 11:45:40 +00003664 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00003665 QualType Type = E->getLHS()->getType();
3666 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00003667
Richard Smith180f4792011-11-10 06:34:14 +00003668 CharUnits ElementSize;
3669 if (!HandleSizeof(Info, ElementType, ElementSize))
3670 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00003671
Richard Smith180f4792011-11-10 06:34:14 +00003672 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dycka7305832010-01-15 12:37:54 +00003673 RHSValue.getLValueOffset();
3674 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00003675 }
Richard Smith625b8072011-10-31 01:37:14 +00003676
3677 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
3678 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
3679 switch (E->getOpcode()) {
3680 default: llvm_unreachable("missing comparison operator");
3681 case BO_LT: return Success(LHSOffset < RHSOffset, E);
3682 case BO_GT: return Success(LHSOffset > RHSOffset, E);
3683 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
3684 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
3685 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
3686 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00003687 }
Anders Carlsson3068d112008-11-16 19:01:22 +00003688 }
3689 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003690 if (!LHSTy->isIntegralOrEnumerationType() ||
3691 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003692 // We can't continue from here for non-integral types.
3693 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00003694 }
3695
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003696 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00003697 CCValue LHSVal;
Richard Smithc49bd112011-10-28 17:51:58 +00003698 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003699 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00003700
Richard Smithc49bd112011-10-28 17:51:58 +00003701 if (!Visit(E->getRHS()))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003702 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00003703 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00003704
3705 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00003706 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00003707 CharUnits AdditionalOffset = CharUnits::fromQuantity(
3708 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00003709 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00003710 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00003711 else
Richard Smith47a1eed2011-10-29 20:57:55 +00003712 LHSVal.getLValueOffset() -= AdditionalOffset;
3713 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00003714 return true;
3715 }
3716
3717 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00003718 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00003719 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003720 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
3721 LHSVal.getInt().getZExtValue());
3722 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00003723 return true;
3724 }
3725
3726 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00003727 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00003728 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00003729
Richard Smithc49bd112011-10-28 17:51:58 +00003730 APSInt &LHS = LHSVal.getInt();
3731 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00003732
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003733 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00003734 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00003735 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00003736 case BO_Mul: return Success(LHS * RHS, E);
3737 case BO_Add: return Success(LHS + RHS, E);
3738 case BO_Sub: return Success(LHS - RHS, E);
3739 case BO_And: return Success(LHS & RHS, E);
3740 case BO_Xor: return Success(LHS ^ RHS, E);
3741 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00003742 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00003743 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00003744 return Error(E, diag::note_expr_divide_by_zero);
Richard Smithc49bd112011-10-28 17:51:58 +00003745 return Success(LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00003746 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00003747 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00003748 return Error(E, diag::note_expr_divide_by_zero);
Richard Smithc49bd112011-10-28 17:51:58 +00003749 return Success(LHS % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00003750 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00003751 // During constant-folding, a negative shift is an opposite shift.
3752 if (RHS.isSigned() && RHS.isNegative()) {
3753 RHS = -RHS;
3754 goto shift_right;
3755 }
3756
3757 shift_left:
3758 unsigned SA
Richard Smithc49bd112011-10-28 17:51:58 +00003759 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3760 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003761 }
John McCall2de56d12010-08-25 11:45:40 +00003762 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00003763 // During constant-folding, a negative shift is an opposite shift.
3764 if (RHS.isSigned() && RHS.isNegative()) {
3765 RHS = -RHS;
3766 goto shift_left;
3767 }
3768
3769 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00003770 unsigned SA =
Richard Smithc49bd112011-10-28 17:51:58 +00003771 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3772 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003773 }
Mike Stump1eb44332009-09-09 15:08:12 +00003774
Richard Smithc49bd112011-10-28 17:51:58 +00003775 case BO_LT: return Success(LHS < RHS, E);
3776 case BO_GT: return Success(LHS > RHS, E);
3777 case BO_LE: return Success(LHS <= RHS, E);
3778 case BO_GE: return Success(LHS >= RHS, E);
3779 case BO_EQ: return Success(LHS == RHS, E);
3780 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00003781 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003782}
3783
Ken Dyck8b752f12010-01-27 17:10:57 +00003784CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00003785 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3786 // the result is the size of the referenced type."
3787 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3788 // result shall be the alignment of the referenced type."
3789 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
3790 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00003791
3792 // __alignof is defined to return the preferred alignment.
3793 return Info.Ctx.toCharUnitsFromBits(
3794 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00003795}
3796
Ken Dyck8b752f12010-01-27 17:10:57 +00003797CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00003798 E = E->IgnoreParens();
3799
3800 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00003801 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00003802 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00003803 return Info.Ctx.getDeclAlign(DRE->getDecl(),
3804 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00003805
Chris Lattneraf707ab2009-01-24 21:53:27 +00003806 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00003807 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
3808 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00003809
Chris Lattnere9feb472009-01-24 21:09:06 +00003810 return GetAlignOfType(E->getType());
3811}
3812
3813
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003814/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
3815/// a result as the expression's type.
3816bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
3817 const UnaryExprOrTypeTraitExpr *E) {
3818 switch(E->getKind()) {
3819 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00003820 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003821 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00003822 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003823 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00003824 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00003825
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003826 case UETT_VecStep: {
3827 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00003828
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003829 if (Ty->isVectorType()) {
3830 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00003831
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003832 // The vec_step built-in functions that take a 3-component
3833 // vector return 4. (OpenCL 1.1 spec 6.11.12)
3834 if (n == 3)
3835 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00003836
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003837 return Success(n, E);
3838 } else
3839 return Success(1, E);
3840 }
3841
3842 case UETT_SizeOf: {
3843 QualType SrcTy = E->getTypeOfArgument();
3844 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3845 // the result is the size of the referenced type."
3846 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3847 // result shall be the alignment of the referenced type."
3848 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
3849 SrcTy = Ref->getPointeeType();
3850
Richard Smith180f4792011-11-10 06:34:14 +00003851 CharUnits Sizeof;
3852 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003853 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003854 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003855 }
3856 }
3857
3858 llvm_unreachable("unknown expr/type trait");
Richard Smithf48fdb02011-12-09 22:58:01 +00003859 return Error(E);
Chris Lattnerfcee0012008-07-11 21:24:13 +00003860}
3861
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003862bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003863 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003864 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003865 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00003866 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003867 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003868 for (unsigned i = 0; i != n; ++i) {
3869 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
3870 switch (ON.getKind()) {
3871 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003872 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003873 APSInt IdxResult;
3874 if (!EvaluateInteger(Idx, IdxResult, Info))
3875 return false;
3876 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
3877 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003878 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003879 CurrentType = AT->getElementType();
3880 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
3881 Result += IdxResult.getSExtValue() * ElementSize;
3882 break;
3883 }
Richard Smithf48fdb02011-12-09 22:58:01 +00003884
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003885 case OffsetOfExpr::OffsetOfNode::Field: {
3886 FieldDecl *MemberDecl = ON.getField();
3887 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00003888 if (!RT)
3889 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003890 RecordDecl *RD = RT->getDecl();
3891 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00003892 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00003893 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00003894 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003895 CurrentType = MemberDecl->getType().getNonReferenceType();
3896 break;
3897 }
Richard Smithf48fdb02011-12-09 22:58:01 +00003898
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003899 case OffsetOfExpr::OffsetOfNode::Identifier:
3900 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00003901 return Error(OOE);
3902
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00003903 case OffsetOfExpr::OffsetOfNode::Base: {
3904 CXXBaseSpecifier *BaseSpec = ON.getBase();
3905 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00003906 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00003907
3908 // Find the layout of the class whose base we are looking into.
3909 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00003910 if (!RT)
3911 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00003912 RecordDecl *RD = RT->getDecl();
3913 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
3914
3915 // Find the base class itself.
3916 CurrentType = BaseSpec->getType();
3917 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
3918 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003919 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00003920
3921 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00003922 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00003923 break;
3924 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003925 }
3926 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003927 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003928}
3929
Chris Lattnerb542afe2008-07-11 19:10:17 +00003930bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00003931 switch (E->getOpcode()) {
3932 default:
3933 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
3934 // See C99 6.6p3.
3935 return Error(E);
3936 case UO_Extension:
3937 // FIXME: Should extension allow i-c-e extension expressions in its scope?
3938 // If so, we could clear the diagnostic ID.
3939 return Visit(E->getSubExpr());
3940 case UO_Plus:
3941 // The result is just the value.
3942 return Visit(E->getSubExpr());
3943 case UO_Minus: {
3944 if (!Visit(E->getSubExpr()))
3945 return false;
3946 if (!Result.isInt()) return Error(E);
3947 return Success(-Result.getInt(), E);
3948 }
3949 case UO_Not: {
3950 if (!Visit(E->getSubExpr()))
3951 return false;
3952 if (!Result.isInt()) return Error(E);
3953 return Success(~Result.getInt(), E);
3954 }
3955 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00003956 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00003957 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00003958 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00003959 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00003960 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003961 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003962}
Mike Stump1eb44332009-09-09 15:08:12 +00003963
Chris Lattner732b2232008-07-12 01:15:53 +00003964/// HandleCast - This is used to evaluate implicit or explicit casts where the
3965/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003966bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
3967 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00003968 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00003969 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00003970
Eli Friedman46a52322011-03-25 00:43:55 +00003971 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00003972 case CK_BaseToDerived:
3973 case CK_DerivedToBase:
3974 case CK_UncheckedDerivedToBase:
3975 case CK_Dynamic:
3976 case CK_ToUnion:
3977 case CK_ArrayToPointerDecay:
3978 case CK_FunctionToPointerDecay:
3979 case CK_NullToPointer:
3980 case CK_NullToMemberPointer:
3981 case CK_BaseToDerivedMemberPointer:
3982 case CK_DerivedToBaseMemberPointer:
3983 case CK_ConstructorConversion:
3984 case CK_IntegralToPointer:
3985 case CK_ToVoid:
3986 case CK_VectorSplat:
3987 case CK_IntegralToFloating:
3988 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003989 case CK_CPointerToObjCPointerCast:
3990 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00003991 case CK_AnyPointerToBlockPointerCast:
3992 case CK_ObjCObjectLValueCast:
3993 case CK_FloatingRealToComplex:
3994 case CK_FloatingComplexToReal:
3995 case CK_FloatingComplexCast:
3996 case CK_FloatingComplexToIntegralComplex:
3997 case CK_IntegralRealToComplex:
3998 case CK_IntegralComplexCast:
3999 case CK_IntegralComplexToFloatingComplex:
4000 llvm_unreachable("invalid cast kind for integral value");
4001
Eli Friedmane50c2972011-03-25 19:07:11 +00004002 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004003 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00004004 case CK_LValueBitCast:
4005 case CK_UserDefinedConversion:
John McCall33e56f32011-09-10 06:18:15 +00004006 case CK_ARCProduceObject:
4007 case CK_ARCConsumeObject:
4008 case CK_ARCReclaimReturnedObject:
4009 case CK_ARCExtendBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00004010 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004011
4012 case CK_LValueToRValue:
4013 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00004014 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004015
4016 case CK_MemberPointerToBoolean:
4017 case CK_PointerToBoolean:
4018 case CK_IntegralToBoolean:
4019 case CK_FloatingToBoolean:
4020 case CK_FloatingComplexToBoolean:
4021 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004022 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00004023 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00004024 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004025 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004026 }
4027
Eli Friedman46a52322011-03-25 00:43:55 +00004028 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00004029 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004030 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00004031
Eli Friedmanbe265702009-02-20 01:15:07 +00004032 if (!Result.isInt()) {
4033 // Only allow casts of lvalues if they are lossless.
4034 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
4035 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004036
Daniel Dunbardd211642009-02-19 22:24:01 +00004037 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004038 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00004039 }
Mike Stump1eb44332009-09-09 15:08:12 +00004040
Eli Friedman46a52322011-03-25 00:43:55 +00004041 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00004042 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4043
John McCallefdb83e2010-05-07 21:00:08 +00004044 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00004045 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004046 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00004047
Daniel Dunbardd211642009-02-19 22:24:01 +00004048 if (LV.getLValueBase()) {
4049 // Only allow based lvalue casts if they are lossless.
4050 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00004051 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004052
Richard Smithb755a9d2011-11-16 07:18:12 +00004053 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00004054 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00004055 return true;
4056 }
4057
Ken Dycka7305832010-01-15 12:37:54 +00004058 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
4059 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00004060 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00004061 }
Eli Friedman4efaa272008-11-12 09:44:48 +00004062
Eli Friedman46a52322011-03-25 00:43:55 +00004063 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00004064 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00004065 if (!EvaluateComplex(SubExpr, C, Info))
4066 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00004067 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00004068 }
Eli Friedman2217c872009-02-22 11:46:18 +00004069
Eli Friedman46a52322011-03-25 00:43:55 +00004070 case CK_FloatingToIntegral: {
4071 APFloat F(0.0);
4072 if (!EvaluateFloat(SubExpr, F, Info))
4073 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00004074
Richard Smithc1c5f272011-12-13 06:39:58 +00004075 APSInt Value;
4076 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
4077 return false;
4078 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00004079 }
4080 }
Mike Stump1eb44332009-09-09 15:08:12 +00004081
Eli Friedman46a52322011-03-25 00:43:55 +00004082 llvm_unreachable("unknown cast resulting in integral value");
Richard Smithf48fdb02011-12-09 22:58:01 +00004083 return Error(E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004084}
Anders Carlsson2bad1682008-07-08 14:30:00 +00004085
Eli Friedman722c7172009-02-28 03:59:05 +00004086bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4087 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004088 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004089 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4090 return false;
4091 if (!LV.isComplexInt())
4092 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004093 return Success(LV.getComplexIntReal(), E);
4094 }
4095
4096 return Visit(E->getSubExpr());
4097}
4098
Eli Friedman664a1042009-02-27 04:45:43 +00004099bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00004100 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004101 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004102 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4103 return false;
4104 if (!LV.isComplexInt())
4105 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004106 return Success(LV.getComplexIntImag(), E);
4107 }
4108
Richard Smith8327fad2011-10-24 18:44:57 +00004109 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00004110 return Success(0, E);
4111}
4112
Douglas Gregoree8aff02011-01-04 17:33:58 +00004113bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4114 return Success(E->getPackLength(), E);
4115}
4116
Sebastian Redl295995c2010-09-10 20:55:47 +00004117bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4118 return Success(E->getValue(), E);
4119}
4120
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004121//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004122// Float Evaluation
4123//===----------------------------------------------------------------------===//
4124
4125namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004126class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004127 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004128 APFloat &Result;
4129public:
4130 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004131 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004132
Richard Smith47a1eed2011-10-29 20:57:55 +00004133 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004134 Result = V.getFloat();
4135 return true;
4136 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004137
Richard Smithf10d9172011-10-11 21:43:33 +00004138 bool ValueInitialization(const Expr *E) {
4139 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4140 return true;
4141 }
4142
Chris Lattner019f4e82008-10-06 05:28:25 +00004143 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004144
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004145 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004146 bool VisitBinaryOperator(const BinaryOperator *E);
4147 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004148 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00004149
John McCallabd3a852010-05-07 22:08:54 +00004150 bool VisitUnaryReal(const UnaryOperator *E);
4151 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00004152
John McCallabd3a852010-05-07 22:08:54 +00004153 // FIXME: Missing: array subscript of vector, member of vector,
4154 // ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004155};
4156} // end anonymous namespace
4157
4158static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004159 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004160 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004161}
4162
Jay Foad4ba2a172011-01-12 09:06:06 +00004163static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00004164 QualType ResultTy,
4165 const Expr *Arg,
4166 bool SNaN,
4167 llvm::APFloat &Result) {
4168 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4169 if (!S) return false;
4170
4171 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4172
4173 llvm::APInt fill;
4174
4175 // Treat empty strings as if they were zero.
4176 if (S->getString().empty())
4177 fill = llvm::APInt(32, 0);
4178 else if (S->getString().getAsInteger(0, fill))
4179 return false;
4180
4181 if (SNaN)
4182 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
4183 else
4184 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
4185 return true;
4186}
4187
Chris Lattner019f4e82008-10-06 05:28:25 +00004188bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004189 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004190 default:
4191 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4192
Chris Lattner019f4e82008-10-06 05:28:25 +00004193 case Builtin::BI__builtin_huge_val:
4194 case Builtin::BI__builtin_huge_valf:
4195 case Builtin::BI__builtin_huge_vall:
4196 case Builtin::BI__builtin_inf:
4197 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004198 case Builtin::BI__builtin_infl: {
4199 const llvm::fltSemantics &Sem =
4200 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00004201 Result = llvm::APFloat::getInf(Sem);
4202 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004203 }
Mike Stump1eb44332009-09-09 15:08:12 +00004204
John McCalldb7b72a2010-02-28 13:00:19 +00004205 case Builtin::BI__builtin_nans:
4206 case Builtin::BI__builtin_nansf:
4207 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00004208 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4209 true, Result))
4210 return Error(E);
4211 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00004212
Chris Lattner9e621712008-10-06 06:31:58 +00004213 case Builtin::BI__builtin_nan:
4214 case Builtin::BI__builtin_nanf:
4215 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00004216 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00004217 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00004218 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4219 false, Result))
4220 return Error(E);
4221 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004222
4223 case Builtin::BI__builtin_fabs:
4224 case Builtin::BI__builtin_fabsf:
4225 case Builtin::BI__builtin_fabsl:
4226 if (!EvaluateFloat(E->getArg(0), Result, Info))
4227 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004228
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004229 if (Result.isNegative())
4230 Result.changeSign();
4231 return true;
4232
Mike Stump1eb44332009-09-09 15:08:12 +00004233 case Builtin::BI__builtin_copysign:
4234 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004235 case Builtin::BI__builtin_copysignl: {
4236 APFloat RHS(0.);
4237 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4238 !EvaluateFloat(E->getArg(1), RHS, Info))
4239 return false;
4240 Result.copySign(RHS);
4241 return true;
4242 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004243 }
4244}
4245
John McCallabd3a852010-05-07 22:08:54 +00004246bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00004247 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4248 ComplexValue CV;
4249 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4250 return false;
4251 Result = CV.FloatReal;
4252 return true;
4253 }
4254
4255 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00004256}
4257
4258bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00004259 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4260 ComplexValue CV;
4261 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4262 return false;
4263 Result = CV.FloatImag;
4264 return true;
4265 }
4266
Richard Smith8327fad2011-10-24 18:44:57 +00004267 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00004268 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4269 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00004270 return true;
4271}
4272
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004273bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004274 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004275 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004276 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00004277 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00004278 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00004279 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
4280 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004281 Result.changeSign();
4282 return true;
4283 }
4284}
Chris Lattner019f4e82008-10-06 05:28:25 +00004285
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004286bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004287 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
4288 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00004289
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004290 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004291 if (!EvaluateFloat(E->getLHS(), Result, Info))
4292 return false;
4293 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4294 return false;
4295
4296 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004297 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004298 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004299 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
4300 return true;
John McCall2de56d12010-08-25 11:45:40 +00004301 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004302 Result.add(RHS, APFloat::rmNearestTiesToEven);
4303 return true;
John McCall2de56d12010-08-25 11:45:40 +00004304 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004305 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
4306 return true;
John McCall2de56d12010-08-25 11:45:40 +00004307 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004308 Result.divide(RHS, APFloat::rmNearestTiesToEven);
4309 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004310 }
4311}
4312
4313bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
4314 Result = E->getValue();
4315 return true;
4316}
4317
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004318bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4319 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00004320
Eli Friedman2a523ee2011-03-25 00:54:52 +00004321 switch (E->getCastKind()) {
4322 default:
Richard Smithc49bd112011-10-28 17:51:58 +00004323 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00004324
4325 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004326 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00004327 return EvaluateInteger(SubExpr, IntResult, Info) &&
4328 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
4329 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00004330 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00004331
4332 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004333 if (!Visit(SubExpr))
4334 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00004335 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
4336 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00004337 }
John McCallf3ea8cf2010-11-14 08:17:51 +00004338
Eli Friedman2a523ee2011-03-25 00:54:52 +00004339 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00004340 ComplexValue V;
4341 if (!EvaluateComplex(SubExpr, V, Info))
4342 return false;
4343 Result = V.getComplexFloatReal();
4344 return true;
4345 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00004346 }
Eli Friedman4efaa272008-11-12 09:44:48 +00004347
Richard Smithf48fdb02011-12-09 22:58:01 +00004348 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004349}
4350
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004351//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004352// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004353//===----------------------------------------------------------------------===//
4354
4355namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004356class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004357 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00004358 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00004359
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004360public:
John McCallf4cf1a12010-05-07 17:22:02 +00004361 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004362 : ExprEvaluatorBaseTy(info), Result(Result) {}
4363
Richard Smith47a1eed2011-10-29 20:57:55 +00004364 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004365 Result.setFrom(V);
4366 return true;
4367 }
Mike Stump1eb44332009-09-09 15:08:12 +00004368
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004369 //===--------------------------------------------------------------------===//
4370 // Visitor Methods
4371 //===--------------------------------------------------------------------===//
4372
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004373 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump1eb44332009-09-09 15:08:12 +00004374
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004375 bool VisitCastExpr(const CastExpr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00004376
John McCallf4cf1a12010-05-07 17:22:02 +00004377 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004378 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004379 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004380};
4381} // end anonymous namespace
4382
John McCallf4cf1a12010-05-07 17:22:02 +00004383static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
4384 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004385 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004386 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004387}
4388
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004389bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
4390 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004391
4392 if (SubExpr->getType()->isRealFloatingType()) {
4393 Result.makeComplexFloat();
4394 APFloat &Imag = Result.FloatImag;
4395 if (!EvaluateFloat(SubExpr, Imag, Info))
4396 return false;
4397
4398 Result.FloatReal = APFloat(Imag.getSemantics());
4399 return true;
4400 } else {
4401 assert(SubExpr->getType()->isIntegerType() &&
4402 "Unexpected imaginary literal.");
4403
4404 Result.makeComplexInt();
4405 APSInt &Imag = Result.IntImag;
4406 if (!EvaluateInteger(SubExpr, Imag, Info))
4407 return false;
4408
4409 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
4410 return true;
4411 }
4412}
4413
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004414bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004415
John McCall8786da72010-12-14 17:51:41 +00004416 switch (E->getCastKind()) {
4417 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00004418 case CK_BaseToDerived:
4419 case CK_DerivedToBase:
4420 case CK_UncheckedDerivedToBase:
4421 case CK_Dynamic:
4422 case CK_ToUnion:
4423 case CK_ArrayToPointerDecay:
4424 case CK_FunctionToPointerDecay:
4425 case CK_NullToPointer:
4426 case CK_NullToMemberPointer:
4427 case CK_BaseToDerivedMemberPointer:
4428 case CK_DerivedToBaseMemberPointer:
4429 case CK_MemberPointerToBoolean:
4430 case CK_ConstructorConversion:
4431 case CK_IntegralToPointer:
4432 case CK_PointerToIntegral:
4433 case CK_PointerToBoolean:
4434 case CK_ToVoid:
4435 case CK_VectorSplat:
4436 case CK_IntegralCast:
4437 case CK_IntegralToBoolean:
4438 case CK_IntegralToFloating:
4439 case CK_FloatingToIntegral:
4440 case CK_FloatingToBoolean:
4441 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00004442 case CK_CPointerToObjCPointerCast:
4443 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00004444 case CK_AnyPointerToBlockPointerCast:
4445 case CK_ObjCObjectLValueCast:
4446 case CK_FloatingComplexToReal:
4447 case CK_FloatingComplexToBoolean:
4448 case CK_IntegralComplexToReal:
4449 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00004450 case CK_ARCProduceObject:
4451 case CK_ARCConsumeObject:
4452 case CK_ARCReclaimReturnedObject:
4453 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00004454 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00004455
John McCall8786da72010-12-14 17:51:41 +00004456 case CK_LValueToRValue:
4457 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00004458 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00004459
4460 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00004461 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00004462 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00004463 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00004464
4465 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004466 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00004467 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004468 return false;
4469
John McCall8786da72010-12-14 17:51:41 +00004470 Result.makeComplexFloat();
4471 Result.FloatImag = APFloat(Real.getSemantics());
4472 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004473 }
4474
John McCall8786da72010-12-14 17:51:41 +00004475 case CK_FloatingComplexCast: {
4476 if (!Visit(E->getSubExpr()))
4477 return false;
4478
4479 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4480 QualType From
4481 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4482
Richard Smithc1c5f272011-12-13 06:39:58 +00004483 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
4484 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00004485 }
4486
4487 case CK_FloatingComplexToIntegralComplex: {
4488 if (!Visit(E->getSubExpr()))
4489 return false;
4490
4491 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4492 QualType From
4493 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4494 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00004495 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
4496 To, Result.IntReal) &&
4497 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
4498 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00004499 }
4500
4501 case CK_IntegralRealToComplex: {
4502 APSInt &Real = Result.IntReal;
4503 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
4504 return false;
4505
4506 Result.makeComplexInt();
4507 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
4508 return true;
4509 }
4510
4511 case CK_IntegralComplexCast: {
4512 if (!Visit(E->getSubExpr()))
4513 return false;
4514
4515 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4516 QualType From
4517 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4518
4519 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
4520 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
4521 return true;
4522 }
4523
4524 case CK_IntegralComplexToFloatingComplex: {
4525 if (!Visit(E->getSubExpr()))
4526 return false;
4527
4528 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4529 QualType From
4530 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4531 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00004532 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
4533 To, Result.FloatReal) &&
4534 HandleIntToFloatCast(Info, E, From, Result.IntImag,
4535 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00004536 }
4537 }
4538
4539 llvm_unreachable("unknown cast resulting in complex value");
Richard Smithf48fdb02011-12-09 22:58:01 +00004540 return Error(E);
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004541}
4542
John McCallf4cf1a12010-05-07 17:22:02 +00004543bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004544 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00004545 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4546
John McCallf4cf1a12010-05-07 17:22:02 +00004547 if (!Visit(E->getLHS()))
4548 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004549
John McCallf4cf1a12010-05-07 17:22:02 +00004550 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004551 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00004552 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004553
Daniel Dunbar3f279872009-01-29 01:32:56 +00004554 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
4555 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00004556 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004557 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004558 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004559 if (Result.isComplexFloat()) {
4560 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
4561 APFloat::rmNearestTiesToEven);
4562 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
4563 APFloat::rmNearestTiesToEven);
4564 } else {
4565 Result.getComplexIntReal() += RHS.getComplexIntReal();
4566 Result.getComplexIntImag() += RHS.getComplexIntImag();
4567 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00004568 break;
John McCall2de56d12010-08-25 11:45:40 +00004569 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004570 if (Result.isComplexFloat()) {
4571 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
4572 APFloat::rmNearestTiesToEven);
4573 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
4574 APFloat::rmNearestTiesToEven);
4575 } else {
4576 Result.getComplexIntReal() -= RHS.getComplexIntReal();
4577 Result.getComplexIntImag() -= RHS.getComplexIntImag();
4578 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00004579 break;
John McCall2de56d12010-08-25 11:45:40 +00004580 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00004581 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004582 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00004583 APFloat &LHS_r = LHS.getComplexFloatReal();
4584 APFloat &LHS_i = LHS.getComplexFloatImag();
4585 APFloat &RHS_r = RHS.getComplexFloatReal();
4586 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00004587
Daniel Dunbar3f279872009-01-29 01:32:56 +00004588 APFloat Tmp = LHS_r;
4589 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4590 Result.getComplexFloatReal() = Tmp;
4591 Tmp = LHS_i;
4592 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4593 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
4594
4595 Tmp = LHS_r;
4596 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4597 Result.getComplexFloatImag() = Tmp;
4598 Tmp = LHS_i;
4599 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4600 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
4601 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00004602 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00004603 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00004604 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
4605 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00004606 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00004607 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
4608 LHS.getComplexIntImag() * RHS.getComplexIntReal());
4609 }
4610 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004611 case BO_Div:
4612 if (Result.isComplexFloat()) {
4613 ComplexValue LHS = Result;
4614 APFloat &LHS_r = LHS.getComplexFloatReal();
4615 APFloat &LHS_i = LHS.getComplexFloatImag();
4616 APFloat &RHS_r = RHS.getComplexFloatReal();
4617 APFloat &RHS_i = RHS.getComplexFloatImag();
4618 APFloat &Res_r = Result.getComplexFloatReal();
4619 APFloat &Res_i = Result.getComplexFloatImag();
4620
4621 APFloat Den = RHS_r;
4622 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4623 APFloat Tmp = RHS_i;
4624 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4625 Den.add(Tmp, APFloat::rmNearestTiesToEven);
4626
4627 Res_r = LHS_r;
4628 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4629 Tmp = LHS_i;
4630 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4631 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
4632 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
4633
4634 Res_i = LHS_i;
4635 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4636 Tmp = LHS_r;
4637 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4638 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
4639 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
4640 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00004641 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
4642 return Error(E, diag::note_expr_divide_by_zero);
4643
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004644 ComplexValue LHS = Result;
4645 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
4646 RHS.getComplexIntImag() * RHS.getComplexIntImag();
4647 Result.getComplexIntReal() =
4648 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
4649 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
4650 Result.getComplexIntImag() =
4651 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
4652 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
4653 }
4654 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00004655 }
4656
John McCallf4cf1a12010-05-07 17:22:02 +00004657 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00004658}
4659
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004660bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
4661 // Get the operand value into 'Result'.
4662 if (!Visit(E->getSubExpr()))
4663 return false;
4664
4665 switch (E->getOpcode()) {
4666 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004667 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004668 case UO_Extension:
4669 return true;
4670 case UO_Plus:
4671 // The result is always just the subexpr.
4672 return true;
4673 case UO_Minus:
4674 if (Result.isComplexFloat()) {
4675 Result.getComplexFloatReal().changeSign();
4676 Result.getComplexFloatImag().changeSign();
4677 }
4678 else {
4679 Result.getComplexIntReal() = -Result.getComplexIntReal();
4680 Result.getComplexIntImag() = -Result.getComplexIntImag();
4681 }
4682 return true;
4683 case UO_Not:
4684 if (Result.isComplexFloat())
4685 Result.getComplexFloatImag().changeSign();
4686 else
4687 Result.getComplexIntImag() = -Result.getComplexIntImag();
4688 return true;
4689 }
4690}
4691
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004692//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00004693// Void expression evaluation, primarily for a cast to void on the LHS of a
4694// comma operator
4695//===----------------------------------------------------------------------===//
4696
4697namespace {
4698class VoidExprEvaluator
4699 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
4700public:
4701 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
4702
4703 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00004704
4705 bool VisitCastExpr(const CastExpr *E) {
4706 switch (E->getCastKind()) {
4707 default:
4708 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4709 case CK_ToVoid:
4710 VisitIgnoredValue(E->getSubExpr());
4711 return true;
4712 }
4713 }
4714};
4715} // end anonymous namespace
4716
4717static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
4718 assert(E->isRValue() && E->getType()->isVoidType());
4719 return VoidExprEvaluator(Info).Visit(E);
4720}
4721
4722//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00004723// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004724//===----------------------------------------------------------------------===//
4725
Richard Smith47a1eed2011-10-29 20:57:55 +00004726static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004727 // In C, function designators are not lvalues, but we evaluate them as if they
4728 // are.
4729 if (E->isGLValue() || E->getType()->isFunctionType()) {
4730 LValue LV;
4731 if (!EvaluateLValue(E, LV, Info))
4732 return false;
4733 LV.moveInto(Result);
4734 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00004735 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00004736 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00004737 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00004738 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00004739 return false;
John McCallefdb83e2010-05-07 21:00:08 +00004740 } else if (E->getType()->hasPointerRepresentation()) {
4741 LValue LV;
4742 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00004743 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00004744 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00004745 } else if (E->getType()->isRealFloatingType()) {
4746 llvm::APFloat F(0.0);
4747 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00004748 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00004749 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00004750 } else if (E->getType()->isAnyComplexType()) {
4751 ComplexValue C;
4752 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00004753 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00004754 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00004755 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004756 MemberPtr P;
4757 if (!EvaluateMemberPointer(E, P, Info))
4758 return false;
4759 P.moveInto(Result);
4760 return true;
Richard Smith69c2c502011-11-04 05:33:44 +00004761 } else if (E->getType()->isArrayType() && E->getType()->isLiteralType()) {
Richard Smith180f4792011-11-10 06:34:14 +00004762 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004763 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00004764 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00004765 return false;
Richard Smith180f4792011-11-10 06:34:14 +00004766 Result = Info.CurrentCall->Temporaries[E];
Richard Smith69c2c502011-11-04 05:33:44 +00004767 } else if (E->getType()->isRecordType() && E->getType()->isLiteralType()) {
Richard Smith180f4792011-11-10 06:34:14 +00004768 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004769 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00004770 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
4771 return false;
4772 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00004773 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00004774 if (Info.getLangOpts().CPlusPlus0x)
4775 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
4776 << E->getType();
4777 else
4778 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00004779 if (!EvaluateVoid(E, Info))
4780 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00004781 } else if (Info.getLangOpts().CPlusPlus0x) {
4782 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
4783 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004784 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00004785 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00004786 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004787 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00004788
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00004789 return true;
4790}
4791
Richard Smith69c2c502011-11-04 05:33:44 +00004792/// EvaluateConstantExpression - Evaluate an expression as a constant expression
4793/// in-place in an APValue. In some cases, the in-place evaluation is essential,
4794/// since later initializers for an object can indirectly refer to subobjects
4795/// which were initialized earlier.
4796static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +00004797 const LValue &This, const Expr *E,
4798 CheckConstantExpressionKind CCEK) {
Richard Smith69c2c502011-11-04 05:33:44 +00004799 if (E->isRValue() && E->getType()->isLiteralType()) {
4800 // Evaluate arrays and record types in-place, so that later initializers can
4801 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00004802 if (E->getType()->isArrayType())
4803 return EvaluateArray(E, This, Result, Info);
4804 else if (E->getType()->isRecordType())
4805 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00004806 }
4807
4808 // For any other type, in-place evaluation is unimportant.
4809 CCValue CoreConstResult;
4810 return Evaluate(CoreConstResult, Info, E) &&
Richard Smithc1c5f272011-12-13 06:39:58 +00004811 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smith69c2c502011-11-04 05:33:44 +00004812}
4813
Richard Smithf48fdb02011-12-09 22:58:01 +00004814/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
4815/// lvalue-to-rvalue cast if it is an lvalue.
4816static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
4817 CCValue Value;
4818 if (!::Evaluate(Value, Info, E))
4819 return false;
4820
4821 if (E->isGLValue()) {
4822 LValue LV;
4823 LV.setFrom(Value);
4824 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
4825 return false;
4826 }
4827
4828 // Check this core constant expression is a constant expression, and if so,
4829 // convert it to one.
4830 return CheckConstantExpression(Info, E, Value, Result);
4831}
Richard Smithc49bd112011-10-28 17:51:58 +00004832
Richard Smith51f47082011-10-29 00:50:52 +00004833/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00004834/// any crazy technique (that has nothing to do with language standards) that
4835/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00004836/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
4837/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00004838bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00004839 // Fast-path evaluations of integer literals, since we sometimes see files
4840 // containing vast quantities of these.
4841 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
4842 Result.Val = APValue(APSInt(L->getValue(),
4843 L->getType()->isUnsignedIntegerType()));
4844 return true;
4845 }
4846
Richard Smith1445bba2011-11-10 03:30:42 +00004847 // FIXME: Evaluating initializers for large arrays can cause performance
4848 // problems, and we don't use such values yet. Once we have a more efficient
4849 // array representation, this should be reinstated, and used by CodeGen.
Richard Smithe24f5fc2011-11-17 22:56:20 +00004850 // The same problem affects large records.
4851 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
4852 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00004853 return false;
4854
Richard Smith180f4792011-11-10 06:34:14 +00004855 // FIXME: If this is the initializer for an lvalue, pass that in.
Richard Smithf48fdb02011-12-09 22:58:01 +00004856 EvalInfo Info(Ctx, Result);
4857 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00004858}
4859
Jay Foad4ba2a172011-01-12 09:06:06 +00004860bool Expr::EvaluateAsBooleanCondition(bool &Result,
4861 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00004862 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00004863 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith177dce72011-11-01 16:57:24 +00004864 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00004865 Result);
John McCallcd7a4452010-01-05 23:42:56 +00004866}
4867
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004868bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00004869 EvalResult ExprResult;
Richard Smith51f47082011-10-29 00:50:52 +00004870 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smithf48fdb02011-12-09 22:58:01 +00004871 !ExprResult.Val.isInt())
Richard Smithc49bd112011-10-28 17:51:58 +00004872 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004873
Richard Smithc49bd112011-10-28 17:51:58 +00004874 Result = ExprResult.Val.getInt();
4875 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004876}
4877
Jay Foad4ba2a172011-01-12 09:06:06 +00004878bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00004879 EvalInfo Info(Ctx, Result);
4880
John McCallefdb83e2010-05-07 21:00:08 +00004881 LValue LV;
Richard Smith9a17a682011-11-07 05:07:52 +00004882 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smithc1c5f272011-12-13 06:39:58 +00004883 CheckLValueConstantExpression(Info, this, LV, Result.Val,
4884 CCEK_Constant);
Eli Friedmanb2f295c2009-09-13 10:17:44 +00004885}
4886
Richard Smith51f47082011-10-29 00:50:52 +00004887/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
4888/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00004889bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00004890 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00004891 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00004892}
Anders Carlsson51fe9962008-11-22 21:04:56 +00004893
Jay Foad4ba2a172011-01-12 09:06:06 +00004894bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00004895 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004896}
4897
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004898APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00004899 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00004900 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00004901 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00004902 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00004903 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00004904
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00004905 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00004906}
John McCalld905f5a2010-05-07 05:32:02 +00004907
Abramo Bagnarae17a6432010-05-14 17:07:14 +00004908 bool Expr::EvalResult::isGlobalLValue() const {
4909 assert(Val.isLValue());
4910 return IsGlobalLValue(Val.getLValueBase());
4911 }
4912
4913
John McCalld905f5a2010-05-07 05:32:02 +00004914/// isIntegerConstantExpr - this recursive routine will test if an expression is
4915/// an integer constant expression.
4916
4917/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
4918/// comma, etc
4919///
4920/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
4921/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
4922/// cast+dereference.
4923
4924// CheckICE - This function does the fundamental ICE checking: the returned
4925// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
4926// Note that to reduce code duplication, this helper does no evaluation
4927// itself; the caller checks whether the expression is evaluatable, and
4928// in the rare cases where CheckICE actually cares about the evaluated
4929// value, it calls into Evalute.
4930//
4931// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00004932// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00004933// 1: This expression is not an ICE, but if it isn't evaluated, it's
4934// a legal subexpression for an ICE. This return value is used to handle
4935// the comma operator in C99 mode.
4936// 2: This expression is not an ICE, and is not a legal subexpression for one.
4937
Dan Gohman3c46e8d2010-07-26 21:25:24 +00004938namespace {
4939
John McCalld905f5a2010-05-07 05:32:02 +00004940struct ICEDiag {
4941 unsigned Val;
4942 SourceLocation Loc;
4943
4944 public:
4945 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
4946 ICEDiag() : Val(0) {}
4947};
4948
Dan Gohman3c46e8d2010-07-26 21:25:24 +00004949}
4950
4951static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00004952
4953static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
4954 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00004955 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00004956 !EVResult.Val.isInt()) {
4957 return ICEDiag(2, E->getLocStart());
4958 }
4959 return NoDiag();
4960}
4961
4962static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
4963 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004964 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00004965 return ICEDiag(2, E->getLocStart());
4966 }
4967
4968 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00004969#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00004970#define STMT(Node, Base) case Expr::Node##Class:
4971#define EXPR(Node, Base)
4972#include "clang/AST/StmtNodes.inc"
4973 case Expr::PredefinedExprClass:
4974 case Expr::FloatingLiteralClass:
4975 case Expr::ImaginaryLiteralClass:
4976 case Expr::StringLiteralClass:
4977 case Expr::ArraySubscriptExprClass:
4978 case Expr::MemberExprClass:
4979 case Expr::CompoundAssignOperatorClass:
4980 case Expr::CompoundLiteralExprClass:
4981 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004982 case Expr::DesignatedInitExprClass:
4983 case Expr::ImplicitValueInitExprClass:
4984 case Expr::ParenListExprClass:
4985 case Expr::VAArgExprClass:
4986 case Expr::AddrLabelExprClass:
4987 case Expr::StmtExprClass:
4988 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00004989 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004990 case Expr::CXXDynamicCastExprClass:
4991 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00004992 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004993 case Expr::CXXNullPtrLiteralExprClass:
4994 case Expr::CXXThisExprClass:
4995 case Expr::CXXThrowExprClass:
4996 case Expr::CXXNewExprClass:
4997 case Expr::CXXDeleteExprClass:
4998 case Expr::CXXPseudoDestructorExprClass:
4999 case Expr::UnresolvedLookupExprClass:
5000 case Expr::DependentScopeDeclRefExprClass:
5001 case Expr::CXXConstructExprClass:
5002 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00005003 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00005004 case Expr::CXXTemporaryObjectExprClass:
5005 case Expr::CXXUnresolvedConstructExprClass:
5006 case Expr::CXXDependentScopeMemberExprClass:
5007 case Expr::UnresolvedMemberExprClass:
5008 case Expr::ObjCStringLiteralClass:
5009 case Expr::ObjCEncodeExprClass:
5010 case Expr::ObjCMessageExprClass:
5011 case Expr::ObjCSelectorExprClass:
5012 case Expr::ObjCProtocolExprClass:
5013 case Expr::ObjCIvarRefExprClass:
5014 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005015 case Expr::ObjCIsaExprClass:
5016 case Expr::ShuffleVectorExprClass:
5017 case Expr::BlockExprClass:
5018 case Expr::BlockDeclRefExprClass:
5019 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00005020 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00005021 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00005022 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00005023 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005024 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00005025 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00005026 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00005027 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005028 case Expr::InitListExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005029 return ICEDiag(2, E->getLocStart());
5030
Douglas Gregoree8aff02011-01-04 17:33:58 +00005031 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005032 case Expr::GNUNullExprClass:
5033 // GCC considers the GNU __null value to be an integral constant expression.
5034 return NoDiag();
5035
John McCall91a57552011-07-15 05:09:51 +00005036 case Expr::SubstNonTypeTemplateParmExprClass:
5037 return
5038 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
5039
John McCalld905f5a2010-05-07 05:32:02 +00005040 case Expr::ParenExprClass:
5041 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00005042 case Expr::GenericSelectionExprClass:
5043 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005044 case Expr::IntegerLiteralClass:
5045 case Expr::CharacterLiteralClass:
5046 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00005047 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005048 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00005049 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00005050 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00005051 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00005052 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005053 return NoDiag();
5054 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00005055 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00005056 // C99 6.6/3 allows function calls within unevaluated subexpressions of
5057 // constant expressions, but they can never be ICEs because an ICE cannot
5058 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00005059 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00005060 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00005061 return CheckEvalInICE(E, Ctx);
5062 return ICEDiag(2, E->getLocStart());
5063 }
5064 case Expr::DeclRefExprClass:
5065 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
5066 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00005067 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00005068 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
5069
5070 // Parameter variables are never constants. Without this check,
5071 // getAnyInitializer() can find a default argument, which leads
5072 // to chaos.
5073 if (isa<ParmVarDecl>(D))
5074 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5075
5076 // C++ 7.1.5.1p2
5077 // A variable of non-volatile const-qualified integral or enumeration
5078 // type initialized by an ICE can be used in ICEs.
5079 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00005080 if (!Dcl->getType()->isIntegralOrEnumerationType())
5081 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5082
John McCalld905f5a2010-05-07 05:32:02 +00005083 // Look for a declaration of this variable that has an initializer.
5084 const VarDecl *ID = 0;
5085 const Expr *Init = Dcl->getAnyInitializer(ID);
5086 if (Init) {
5087 if (ID->isInitKnownICE()) {
5088 // We have already checked whether this subexpression is an
5089 // integral constant expression.
5090 if (ID->isInitICE())
5091 return NoDiag();
5092 else
5093 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5094 }
5095
5096 // It's an ICE whether or not the definition we found is
5097 // out-of-line. See DR 721 and the discussion in Clang PR
5098 // 6206 for details.
5099
5100 if (Dcl->isCheckingICE()) {
5101 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5102 }
5103
5104 Dcl->setCheckingICE();
5105 ICEDiag Result = CheckICE(Init, Ctx);
5106 // Cache the result of the ICE test.
5107 Dcl->setInitKnownICE(Result.Val == 0);
5108 return Result;
5109 }
5110 }
5111 }
5112 return ICEDiag(2, E->getLocStart());
5113 case Expr::UnaryOperatorClass: {
5114 const UnaryOperator *Exp = cast<UnaryOperator>(E);
5115 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005116 case UO_PostInc:
5117 case UO_PostDec:
5118 case UO_PreInc:
5119 case UO_PreDec:
5120 case UO_AddrOf:
5121 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00005122 // C99 6.6/3 allows increment and decrement within unevaluated
5123 // subexpressions of constant expressions, but they can never be ICEs
5124 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00005125 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00005126 case UO_Extension:
5127 case UO_LNot:
5128 case UO_Plus:
5129 case UO_Minus:
5130 case UO_Not:
5131 case UO_Real:
5132 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00005133 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005134 }
5135
5136 // OffsetOf falls through here.
5137 }
5138 case Expr::OffsetOfExprClass: {
5139 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00005140 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00005141 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00005142 // compliance: we should warn earlier for offsetof expressions with
5143 // array subscripts that aren't ICEs, and if the array subscripts
5144 // are ICEs, the value of the offsetof must be an integer constant.
5145 return CheckEvalInICE(E, Ctx);
5146 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005147 case Expr::UnaryExprOrTypeTraitExprClass: {
5148 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
5149 if ((Exp->getKind() == UETT_SizeOf) &&
5150 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00005151 return ICEDiag(2, E->getLocStart());
5152 return NoDiag();
5153 }
5154 case Expr::BinaryOperatorClass: {
5155 const BinaryOperator *Exp = cast<BinaryOperator>(E);
5156 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005157 case BO_PtrMemD:
5158 case BO_PtrMemI:
5159 case BO_Assign:
5160 case BO_MulAssign:
5161 case BO_DivAssign:
5162 case BO_RemAssign:
5163 case BO_AddAssign:
5164 case BO_SubAssign:
5165 case BO_ShlAssign:
5166 case BO_ShrAssign:
5167 case BO_AndAssign:
5168 case BO_XorAssign:
5169 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00005170 // C99 6.6/3 allows assignments within unevaluated subexpressions of
5171 // constant expressions, but they can never be ICEs because an ICE cannot
5172 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00005173 return ICEDiag(2, E->getLocStart());
5174
John McCall2de56d12010-08-25 11:45:40 +00005175 case BO_Mul:
5176 case BO_Div:
5177 case BO_Rem:
5178 case BO_Add:
5179 case BO_Sub:
5180 case BO_Shl:
5181 case BO_Shr:
5182 case BO_LT:
5183 case BO_GT:
5184 case BO_LE:
5185 case BO_GE:
5186 case BO_EQ:
5187 case BO_NE:
5188 case BO_And:
5189 case BO_Xor:
5190 case BO_Or:
5191 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00005192 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5193 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00005194 if (Exp->getOpcode() == BO_Div ||
5195 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00005196 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00005197 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00005198 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005199 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005200 if (REval == 0)
5201 return ICEDiag(1, E->getLocStart());
5202 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005203 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005204 if (LEval.isMinSignedValue())
5205 return ICEDiag(1, E->getLocStart());
5206 }
5207 }
5208 }
John McCall2de56d12010-08-25 11:45:40 +00005209 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00005210 if (Ctx.getLangOptions().C99) {
5211 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
5212 // if it isn't evaluated.
5213 if (LHSResult.Val == 0 && RHSResult.Val == 0)
5214 return ICEDiag(1, E->getLocStart());
5215 } else {
5216 // In both C89 and C++, commas in ICEs are illegal.
5217 return ICEDiag(2, E->getLocStart());
5218 }
5219 }
5220 if (LHSResult.Val >= RHSResult.Val)
5221 return LHSResult;
5222 return RHSResult;
5223 }
John McCall2de56d12010-08-25 11:45:40 +00005224 case BO_LAnd:
5225 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00005226 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5227 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
5228 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
5229 // Rare case where the RHS has a comma "side-effect"; we need
5230 // to actually check the condition to see whether the side
5231 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00005232 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005233 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00005234 return RHSResult;
5235 return NoDiag();
5236 }
5237
5238 if (LHSResult.Val >= RHSResult.Val)
5239 return LHSResult;
5240 return RHSResult;
5241 }
5242 }
5243 }
5244 case Expr::ImplicitCastExprClass:
5245 case Expr::CStyleCastExprClass:
5246 case Expr::CXXFunctionalCastExprClass:
5247 case Expr::CXXStaticCastExprClass:
5248 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00005249 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005250 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00005251 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith98326ed2011-10-25 00:21:54 +00005252 if (isa<ExplicitCastExpr>(E) &&
Richard Smith32cb4712011-10-24 18:26:35 +00005253 isa<FloatingLiteral>(SubExpr->IgnoreParenImpCasts()))
5254 return NoDiag();
Eli Friedmaneea0e812011-09-29 21:49:34 +00005255 switch (cast<CastExpr>(E)->getCastKind()) {
5256 case CK_LValueToRValue:
5257 case CK_NoOp:
5258 case CK_IntegralToBoolean:
5259 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00005260 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00005261 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00005262 return ICEDiag(2, E->getLocStart());
5263 }
John McCalld905f5a2010-05-07 05:32:02 +00005264 }
John McCall56ca35d2011-02-17 10:25:35 +00005265 case Expr::BinaryConditionalOperatorClass: {
5266 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
5267 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
5268 if (CommonResult.Val == 2) return CommonResult;
5269 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
5270 if (FalseResult.Val == 2) return FalseResult;
5271 if (CommonResult.Val == 1) return CommonResult;
5272 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005273 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00005274 return FalseResult;
5275 }
John McCalld905f5a2010-05-07 05:32:02 +00005276 case Expr::ConditionalOperatorClass: {
5277 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
5278 // If the condition (ignoring parens) is a __builtin_constant_p call,
5279 // then only the true side is actually considered in an integer constant
5280 // expression, and it is fully evaluated. This is an important GNU
5281 // extension. See GCC PR38377 for discussion.
5282 if (const CallExpr *CallCE
5283 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith180f4792011-11-10 06:34:14 +00005284 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p) {
John McCalld905f5a2010-05-07 05:32:02 +00005285 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00005286 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00005287 !EVResult.Val.isInt()) {
5288 return ICEDiag(2, E->getLocStart());
5289 }
5290 return NoDiag();
5291 }
5292 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005293 if (CondResult.Val == 2)
5294 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00005295
Richard Smithf48fdb02011-12-09 22:58:01 +00005296 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
5297 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00005298
John McCalld905f5a2010-05-07 05:32:02 +00005299 if (TrueResult.Val == 2)
5300 return TrueResult;
5301 if (FalseResult.Val == 2)
5302 return FalseResult;
5303 if (CondResult.Val == 1)
5304 return CondResult;
5305 if (TrueResult.Val == 0 && FalseResult.Val == 0)
5306 return NoDiag();
5307 // Rare case where the diagnostics depend on which side is evaluated
5308 // Note that if we get here, CondResult is 0, and at least one of
5309 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005310 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00005311 return FalseResult;
5312 }
5313 return TrueResult;
5314 }
5315 case Expr::CXXDefaultArgExprClass:
5316 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
5317 case Expr::ChooseExprClass: {
5318 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
5319 }
5320 }
5321
5322 // Silence a GCC warning
5323 return ICEDiag(2, E->getLocStart());
5324}
5325
Richard Smithf48fdb02011-12-09 22:58:01 +00005326/// Evaluate an expression as a C++11 integral constant expression.
5327static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
5328 const Expr *E,
5329 llvm::APSInt *Value,
5330 SourceLocation *Loc) {
5331 if (!E->getType()->isIntegralOrEnumerationType()) {
5332 if (Loc) *Loc = E->getExprLoc();
5333 return false;
5334 }
5335
5336 Expr::EvalResult Result;
Richard Smithdd1f29b2011-12-12 09:28:41 +00005337 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
5338 Result.Diag = &Diags;
5339 EvalInfo Info(Ctx, Result);
5340
5341 bool IsICE = EvaluateAsRValue(Info, E, Result.Val);
5342 if (!Diags.empty()) {
5343 IsICE = false;
5344 if (Loc) *Loc = Diags[0].first;
5345 } else if (!IsICE && Loc) {
5346 *Loc = E->getExprLoc();
Richard Smithf48fdb02011-12-09 22:58:01 +00005347 }
Richard Smithdd1f29b2011-12-12 09:28:41 +00005348
5349 if (!IsICE)
5350 return false;
5351
5352 assert(Result.Val.isInt() && "pointer cast to int is not an ICE");
5353 if (Value) *Value = Result.Val.getInt();
5354 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00005355}
5356
Richard Smithdd1f29b2011-12-12 09:28:41 +00005357bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00005358 if (Ctx.getLangOptions().CPlusPlus0x)
5359 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
5360
John McCalld905f5a2010-05-07 05:32:02 +00005361 ICEDiag d = CheckICE(this, Ctx);
5362 if (d.Val != 0) {
5363 if (Loc) *Loc = d.Loc;
5364 return false;
5365 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005366 return true;
5367}
5368
5369bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
5370 SourceLocation *Loc, bool isEvaluated) const {
5371 if (Ctx.getLangOptions().CPlusPlus0x)
5372 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
5373
5374 if (!isIntegerConstantExpr(Ctx, Loc))
5375 return false;
5376 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00005377 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00005378 return true;
5379}