blob: 630136ea7f862465f8615c3140ee0a6af9417929 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner60f36222009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump2346cd22009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlsson7a241ba2008-07-03 04:20:39 +000027using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000030
Chris Lattnercdf34e72008-07-11 22:52:41 +000031/// EvalInfo - This is a private struct used by the evaluator to capture
32/// information about a subexpression as it is folded. It retains information
33/// about the AST context, but also maintains information about the folded
34/// expression.
35///
36/// If an expression could be evaluated, it is still possible it is not a C
37/// "integer constant expression" or constant expression. If not, this struct
38/// captures information about how and why not.
39///
40/// One bit of information passed *into* the request for constant folding
41/// indicates whether the subexpression is "evaluated" or not according to C
42/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
43/// evaluate the expression regardless of what the RHS is, but C only allows
44/// certain things in certain situations.
John McCall93d91dc2010-05-07 17:22:02 +000045namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000046 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000047 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000048 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000049
Richard Smithce40ad62011-11-12 22:28:03 +000050 QualType getType(APValue::LValueBase B) {
51 if (!B) return QualType();
52 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
53 return D->getType();
54 return B.get<const Expr*>()->getType();
55 }
56
Richard Smithd62306a2011-11-10 06:34:14 +000057 /// Get an LValue path entry, which is known to not be an array index, as a
58 /// field declaration.
59 const FieldDecl *getAsField(APValue::LValuePathEntry E) {
60 APValue::BaseOrMemberType Value;
61 Value.setFromOpaqueValue(E.BaseOrMember);
62 return dyn_cast<FieldDecl>(Value.getPointer());
63 }
64 /// Get an LValue path entry, which is known to not be an array index, as a
65 /// base class declaration.
66 const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
67 APValue::BaseOrMemberType Value;
68 Value.setFromOpaqueValue(E.BaseOrMember);
69 return dyn_cast<CXXRecordDecl>(Value.getPointer());
70 }
71 /// Determine whether this LValue path entry for a base class names a virtual
72 /// base class.
73 bool isVirtualBaseClass(APValue::LValuePathEntry E) {
74 APValue::BaseOrMemberType Value;
75 Value.setFromOpaqueValue(E.BaseOrMember);
76 return Value.getInt();
77 }
78
Richard Smith80815602011-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 Smithd62306a2011-11-10 06:34:14 +000088 else if (const FieldDecl *FD = getAsField(Path[I]))
Richard Smith80815602011-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 Smith96e0c102011-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 Smith80815602011-11-07 05:07:52 +0000110 typedef APValue::LValuePathEntry PathEntry;
111
Richard Smith96e0c102011-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 Smith80815602011-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 Smithce40ad62011-11-12 22:28:03 +0000125 ArrayElement = SubobjectIsArrayElement(getType(V.getLValueBase()),
Richard Smith80815602011-11-07 05:07:52 +0000126 V.getLValuePath());
127 else
128 assert(V.getLValuePath().empty() &&"Null pointer with nonempty path");
Richard Smith027bf112011-11-17 22:56:20 +0000129 OnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000130 }
131 }
132
Richard Smith96e0c102011-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 Smith80815602011-11-07 05:07:52 +0000145 Entry.ArrayIndex = N;
Richard Smith96e0c102011-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 Smithd62306a2011-11-10 06:34:14 +0000151 void addDecl(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000152 if (Invalid) return;
153 if (OnePastTheEnd) {
154 setInvalid();
155 return;
156 }
157 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000158 APValue::BaseOrMemberType Value(D, Virtual);
159 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-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 Smithf3e9e432011-11-07 09:22:26 +0000167 // FIXME: Make sure the index stays within bounds, or one past the end.
Richard Smith80815602011-11-07 05:07:52 +0000168 Entries.back().ArrayIndex += N;
Richard Smith96e0c102011-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 Smith0b0a0b62011-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 Smith027bf112011-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 Smith0b0a0b62011-10-29 20:57:55 +0000186 class CCValue : public APValue {
187 typedef llvm::APSInt APSInt;
188 typedef llvm::APFloat APFloat;
Richard Smithfec09922011-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 Smith96e0c102011-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 Smith0b0a0b62011-10-29 20:57:55 +0000195 public:
Richard Smithfec09922011-11-01 16:57:24 +0000196 struct GlobalValue {};
197
Richard Smith0b0a0b62011-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 Smithfec09922011-11-01 16:57:24 +0000204 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smithce40ad62011-11-12 22:28:03 +0000205 CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F,
Richard Smith96e0c102011-11-04 02:25:55 +0000206 const SubobjectDesignator &D) :
Richard Smith80815602011-11-07 05:07:52 +0000207 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smithfec09922011-11-01 16:57:24 +0000208 CCValue(const APValue &V, GlobalValue) :
Richard Smith80815602011-11-07 05:07:52 +0000209 APValue(V), CallFrame(0), Designator(V) {}
Richard Smith027bf112011-11-17 22:56:20 +0000210 CCValue(const ValueDecl *D, bool IsDerivedMember,
211 ArrayRef<const CXXRecordDecl*> Path) :
212 APValue(D, IsDerivedMember, Path) {}
Richard Smith0b0a0b62011-10-29 20:57:55 +0000213
Richard Smithfec09922011-11-01 16:57:24 +0000214 CallStackFrame *getLValueFrame() const {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000215 assert(getKind() == LValue);
Richard Smithfec09922011-11-01 16:57:24 +0000216 return CallFrame;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000217 }
Richard Smith96e0c102011-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 Smith0b0a0b62011-10-29 20:57:55 +0000225 };
226
Richard Smith254a73d2011-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 Smith4e4c78ff2011-10-31 05:52:43 +0000232 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000233
Richard Smithf6f003a2011-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 Smithd62306a2011-11-10 06:34:14 +0000240 /// This - The binding for the this pointer in this call, if any.
241 const LValue *This;
242
Richard Smith254a73d2011-10-28 22:34:42 +0000243 /// ParmBindings - Parameter bindings for this function call, indexed by
244 /// parameters' function scope indices.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000245 const CCValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000246
Richard Smith4e4c78ff2011-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 Smithf6f003a2011-12-16 19:06:07 +0000252 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
253 const FunctionDecl *Callee, const LValue *This,
Richard Smithd62306a2011-11-10 06:34:14 +0000254 const CCValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000255 ~CallStackFrame();
Richard Smith254a73d2011-10-28 22:34:42 +0000256 };
257
Richard Smith92b1ce02011-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 Smith4e4c78ff2011-10-31 05:52:43 +0000274 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000275 ASTContext &Ctx;
Richard Smith4e4c78ff2011-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 Smith4e4c78ff2011-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 Smithd62306a2011-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 Smith357362d2011-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 Smith4e4c78ff2011-10-31 05:52:43 +0000307
308 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smith92b1ce02011-12-12 09:28:41 +0000309 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smithf6f003a2011-12-16 19:06:07 +0000310 CallStackDepth(0), BottomFrame(*this, SourceLocation(), 0, 0, 0),
311 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000312
Richard Smith4e4c78ff2011-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 Smithd62306a2011-11-10 06:34:14 +0000319 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
320 EvaluatingDecl = VD;
321 EvaluatingDeclValue = &Value;
322 }
323
Richard Smith9a568822011-11-21 19:36:32 +0000324 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
325
Richard Smith357362d2011-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 Smith9a568822011-11-21 19:36:32 +0000332 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000333
Richard Smith357362d2011-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 Smithf6f003a2011-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 Smith357362d2011-12-13 06:39:58 +0000345 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000346 /// Diagnose that the evaluation cannot be folded.
Richard Smith357362d2011-12-13 06:39:58 +0000347 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
348 unsigned ExtraNotes = 0) {
Richard Smithf57d8cb2011-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 Smith92b1ce02011-12-12 09:28:41 +0000352 if (EvalStatus.Diag) {
Richard Smithf6f003a2011-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 Smith357362d2011-12-13 06:39:58 +0000358 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000359 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-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 Smith92b1ce02011-12-12 09:28:41 +0000364 }
Richard Smith357362d2011-12-13 06:39:58 +0000365 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-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 Smith357362d2011-12-13 06:39:58 +0000371 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId,
372 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000373 // Don't override a previous diagnostic.
374 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
375 return OptionalDiagnostic();
Richard Smith357362d2011-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 Smithf57d8cb2011-12-09 22:58:01 +0000384 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000385
386 /// Add a stack of notes to a prior diagnostic.
387 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
388 if (HasActiveDiagnostic) {
389 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
390 Diags.begin(), Diags.end());
391 }
392 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000393 };
Richard Smithf6f003a2011-12-16 19:06:07 +0000394}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000395
Richard Smithf6f003a2011-12-16 19:06:07 +0000396CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
397 const FunctionDecl *Callee, const LValue *This,
398 const CCValue *Arguments)
399 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
400 This(This), Arguments(Arguments) {
401 Info.CurrentCall = this;
402 ++Info.CallStackDepth;
403}
404
405CallStackFrame::~CallStackFrame() {
406 assert(Info.CurrentCall == this && "calls retired out of order");
407 --Info.CallStackDepth;
408 Info.CurrentCall = Caller;
409}
410
411/// Produce a string describing the given constexpr call.
412static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
413 unsigned ArgIndex = 0;
414 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
415 !isa<CXXConstructorDecl>(Frame->Callee);
416
417 if (!IsMemberCall)
418 Out << *Frame->Callee << '(';
419
420 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
421 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
422 if (ArgIndex > IsMemberCall)
423 Out << ", ";
424
425 const ParmVarDecl *Param = *I;
426 const CCValue &Arg = Frame->Arguments[ArgIndex];
427 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
428 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
429 else {
430 // Deliberately slice off the frame to form an APValue we can print.
431 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
432 Arg.getLValueDesignator().Entries,
433 Arg.getLValueDesignator().OnePastTheEnd);
434 Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
435 }
436
437 if (ArgIndex == 0 && IsMemberCall)
438 Out << "->" << *Frame->Callee << '(';
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000439 }
440
Richard Smithf6f003a2011-12-16 19:06:07 +0000441 Out << ')';
442}
443
444void EvalInfo::addCallStack(unsigned Limit) {
445 // Determine which calls to skip, if any.
446 unsigned ActiveCalls = CallStackDepth - 1;
447 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
448 if (Limit && Limit < ActiveCalls) {
449 SkipStart = Limit / 2 + Limit % 2;
450 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000451 }
452
Richard Smithf6f003a2011-12-16 19:06:07 +0000453 // Walk the call stack and add the diagnostics.
454 unsigned CallIdx = 0;
455 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
456 Frame = Frame->Caller, ++CallIdx) {
457 // Skip this call?
458 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
459 if (CallIdx == SkipStart) {
460 // Note that we're skipping calls.
461 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
462 << unsigned(ActiveCalls - Limit);
463 }
464 continue;
465 }
466
467 llvm::SmallVector<char, 128> Buffer;
468 llvm::raw_svector_ostream Out(Buffer);
469 describeCall(Frame, Out);
470 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
471 }
472}
473
474namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000475 struct ComplexValue {
476 private:
477 bool IsInt;
478
479 public:
480 APSInt IntReal, IntImag;
481 APFloat FloatReal, FloatImag;
482
483 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
484
485 void makeComplexFloat() { IsInt = false; }
486 bool isComplexFloat() const { return !IsInt; }
487 APFloat &getComplexFloatReal() { return FloatReal; }
488 APFloat &getComplexFloatImag() { return FloatImag; }
489
490 void makeComplexInt() { IsInt = true; }
491 bool isComplexInt() const { return IsInt; }
492 APSInt &getComplexIntReal() { return IntReal; }
493 APSInt &getComplexIntImag() { return IntImag; }
494
Richard Smith0b0a0b62011-10-29 20:57:55 +0000495 void moveInto(CCValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000496 if (isComplexFloat())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000497 v = CCValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000498 else
Richard Smith0b0a0b62011-10-29 20:57:55 +0000499 v = CCValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000500 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000501 void setFrom(const CCValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000502 assert(v.isComplexFloat() || v.isComplexInt());
503 if (v.isComplexFloat()) {
504 makeComplexFloat();
505 FloatReal = v.getComplexFloatReal();
506 FloatImag = v.getComplexFloatImag();
507 } else {
508 makeComplexInt();
509 IntReal = v.getComplexIntReal();
510 IntImag = v.getComplexIntImag();
511 }
512 }
John McCall93d91dc2010-05-07 17:22:02 +0000513 };
John McCall45d55e42010-05-07 21:00:08 +0000514
515 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000516 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000517 CharUnits Offset;
Richard Smithfec09922011-11-01 16:57:24 +0000518 CallStackFrame *Frame;
Richard Smith96e0c102011-11-04 02:25:55 +0000519 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000520
Richard Smithce40ad62011-11-12 22:28:03 +0000521 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000522 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000523 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithfec09922011-11-01 16:57:24 +0000524 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith96e0c102011-11-04 02:25:55 +0000525 SubobjectDesignator &getLValueDesignator() { return Designator; }
526 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000527
Richard Smith0b0a0b62011-10-29 20:57:55 +0000528 void moveInto(CCValue &V) const {
Richard Smith96e0c102011-11-04 02:25:55 +0000529 V = CCValue(Base, Offset, Frame, Designator);
John McCall45d55e42010-05-07 21:00:08 +0000530 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000531 void setFrom(const CCValue &V) {
532 assert(V.isLValue());
533 Base = V.getLValueBase();
534 Offset = V.getLValueOffset();
Richard Smithfec09922011-11-01 16:57:24 +0000535 Frame = V.getLValueFrame();
Richard Smith96e0c102011-11-04 02:25:55 +0000536 Designator = V.getLValueDesignator();
537 }
538
Richard Smithce40ad62011-11-12 22:28:03 +0000539 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
540 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000541 Offset = CharUnits::Zero();
542 Frame = F;
543 Designator = SubobjectDesignator();
John McCallc07a0c72011-02-17 10:25:35 +0000544 }
John McCall45d55e42010-05-07 21:00:08 +0000545 };
Richard Smith027bf112011-11-17 22:56:20 +0000546
547 struct MemberPtr {
548 MemberPtr() {}
549 explicit MemberPtr(const ValueDecl *Decl) :
550 DeclAndIsDerivedMember(Decl, false), Path() {}
551
552 /// The member or (direct or indirect) field referred to by this member
553 /// pointer, or 0 if this is a null member pointer.
554 const ValueDecl *getDecl() const {
555 return DeclAndIsDerivedMember.getPointer();
556 }
557 /// Is this actually a member of some type derived from the relevant class?
558 bool isDerivedMember() const {
559 return DeclAndIsDerivedMember.getInt();
560 }
561 /// Get the class which the declaration actually lives in.
562 const CXXRecordDecl *getContainingRecord() const {
563 return cast<CXXRecordDecl>(
564 DeclAndIsDerivedMember.getPointer()->getDeclContext());
565 }
566
567 void moveInto(CCValue &V) const {
568 V = CCValue(getDecl(), isDerivedMember(), Path);
569 }
570 void setFrom(const CCValue &V) {
571 assert(V.isMemberPointer());
572 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
573 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
574 Path.clear();
575 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
576 Path.insert(Path.end(), P.begin(), P.end());
577 }
578
579 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
580 /// whether the member is a member of some class derived from the class type
581 /// of the member pointer.
582 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
583 /// Path - The path of base/derived classes from the member declaration's
584 /// class (exclusive) to the class type of the member pointer (inclusive).
585 SmallVector<const CXXRecordDecl*, 4> Path;
586
587 /// Perform a cast towards the class of the Decl (either up or down the
588 /// hierarchy).
589 bool castBack(const CXXRecordDecl *Class) {
590 assert(!Path.empty());
591 const CXXRecordDecl *Expected;
592 if (Path.size() >= 2)
593 Expected = Path[Path.size() - 2];
594 else
595 Expected = getContainingRecord();
596 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
597 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
598 // if B does not contain the original member and is not a base or
599 // derived class of the class containing the original member, the result
600 // of the cast is undefined.
601 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
602 // (D::*). We consider that to be a language defect.
603 return false;
604 }
605 Path.pop_back();
606 return true;
607 }
608 /// Perform a base-to-derived member pointer cast.
609 bool castToDerived(const CXXRecordDecl *Derived) {
610 if (!getDecl())
611 return true;
612 if (!isDerivedMember()) {
613 Path.push_back(Derived);
614 return true;
615 }
616 if (!castBack(Derived))
617 return false;
618 if (Path.empty())
619 DeclAndIsDerivedMember.setInt(false);
620 return true;
621 }
622 /// Perform a derived-to-base member pointer cast.
623 bool castToBase(const CXXRecordDecl *Base) {
624 if (!getDecl())
625 return true;
626 if (Path.empty())
627 DeclAndIsDerivedMember.setInt(true);
628 if (isDerivedMember()) {
629 Path.push_back(Base);
630 return true;
631 }
632 return castBack(Base);
633 }
634 };
Richard Smith357362d2011-12-13 06:39:58 +0000635
636 /// Kinds of constant expression checking, for diagnostics.
637 enum CheckConstantExpressionKind {
638 CCEK_Constant, ///< A normal constant.
639 CCEK_ReturnValue, ///< A constexpr function return value.
640 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
641 };
John McCall93d91dc2010-05-07 17:22:02 +0000642}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000643
Richard Smith0b0a0b62011-10-29 20:57:55 +0000644static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithed5165f2011-11-04 05:33:44 +0000645static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smith357362d2011-12-13 06:39:58 +0000646 const LValue &This, const Expr *E,
647 CheckConstantExpressionKind CCEK
648 = CCEK_Constant);
John McCall45d55e42010-05-07 21:00:08 +0000649static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
650static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +0000651static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
652 EvalInfo &Info);
653static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000654static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000655static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000656 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000657static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000658static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000659
660//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000661// Misc utilities
662//===----------------------------------------------------------------------===//
663
Richard Smithd62306a2011-11-10 06:34:14 +0000664/// Should this call expression be treated as a string literal?
665static bool IsStringLiteralCall(const CallExpr *E) {
666 unsigned Builtin = E->isBuiltinCall();
667 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
668 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
669}
670
Richard Smithce40ad62011-11-12 22:28:03 +0000671static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +0000672 // C++11 [expr.const]p3 An address constant expression is a prvalue core
673 // constant expression of pointer type that evaluates to...
674
675 // ... a null pointer value, or a prvalue core constant expression of type
676 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +0000677 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +0000678
Richard Smithce40ad62011-11-12 22:28:03 +0000679 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
680 // ... the address of an object with static storage duration,
681 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
682 return VD->hasGlobalStorage();
683 // ... the address of a function,
684 return isa<FunctionDecl>(D);
685 }
686
687 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +0000688 switch (E->getStmtClass()) {
689 default:
690 return false;
Richard Smithd62306a2011-11-10 06:34:14 +0000691 case Expr::CompoundLiteralExprClass:
692 return cast<CompoundLiteralExpr>(E)->isFileScope();
693 // A string literal has static storage duration.
694 case Expr::StringLiteralClass:
695 case Expr::PredefinedExprClass:
696 case Expr::ObjCStringLiteralClass:
697 case Expr::ObjCEncodeExprClass:
698 return true;
699 case Expr::CallExprClass:
700 return IsStringLiteralCall(cast<CallExpr>(E));
701 // For GCC compatibility, &&label has static storage duration.
702 case Expr::AddrLabelExprClass:
703 return true;
704 // A Block literal expression may be used as the initialization value for
705 // Block variables at global or local static scope.
706 case Expr::BlockExprClass:
707 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
708 }
John McCall95007602010-05-10 23:27:23 +0000709}
710
Richard Smith80815602011-11-07 05:07:52 +0000711/// Check that this reference or pointer core constant expression is a valid
712/// value for a constant expression. Type T should be either LValue or CCValue.
713template<typename T>
Richard Smithf57d8cb2011-12-09 22:58:01 +0000714static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +0000715 const T &LVal, APValue &Value,
716 CheckConstantExpressionKind CCEK) {
717 APValue::LValueBase Base = LVal.getLValueBase();
718 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
719
720 if (!IsGlobalLValue(Base)) {
721 if (Info.getLangOpts().CPlusPlus0x) {
722 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
723 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
724 << E->isGLValue() << !Designator.Entries.empty()
725 << !!VD << CCEK << VD;
726 if (VD)
727 Info.Note(VD->getLocation(), diag::note_declared_at);
728 else
729 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
730 diag::note_constexpr_temporary_here);
731 } else {
732 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
733 }
Richard Smith80815602011-11-07 05:07:52 +0000734 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000735 }
Richard Smith80815602011-11-07 05:07:52 +0000736
Richard Smith80815602011-11-07 05:07:52 +0000737 // A constant expression must refer to an object or be a null pointer.
Richard Smith027bf112011-11-17 22:56:20 +0000738 if (Designator.Invalid ||
Richard Smith80815602011-11-07 05:07:52 +0000739 (!LVal.getLValueBase() && !Designator.Entries.empty())) {
Richard Smith357362d2011-12-13 06:39:58 +0000740 // FIXME: This is not a core constant expression. We should have already
741 // produced a CCE diagnostic.
Richard Smith80815602011-11-07 05:07:52 +0000742 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
743 APValue::NoLValuePath());
744 return true;
745 }
746
Richard Smith357362d2011-12-13 06:39:58 +0000747 // Does this refer one past the end of some object?
748 // This is technically not an address constant expression nor a reference
749 // constant expression, but we allow it for address constant expressions.
750 if (E->isGLValue() && Base && Designator.OnePastTheEnd) {
751 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
752 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
753 << !Designator.Entries.empty() << !!VD << VD;
754 if (VD)
755 Info.Note(VD->getLocation(), diag::note_declared_at);
756 else
757 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
758 diag::note_constexpr_temporary_here);
759 return false;
760 }
761
Richard Smith80815602011-11-07 05:07:52 +0000762 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
Richard Smith027bf112011-11-17 22:56:20 +0000763 Designator.Entries, Designator.OnePastTheEnd);
Richard Smith80815602011-11-07 05:07:52 +0000764 return true;
765}
766
Richard Smith0b0a0b62011-10-29 20:57:55 +0000767/// Check that this core constant expression value is a valid value for a
Richard Smithed5165f2011-11-04 05:33:44 +0000768/// constant expression, and if it is, produce the corresponding constant value.
Richard Smithf57d8cb2011-12-09 22:58:01 +0000769/// If not, report an appropriate diagnostic.
770static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +0000771 const CCValue &CCValue, APValue &Value,
772 CheckConstantExpressionKind CCEK
773 = CCEK_Constant) {
Richard Smith80815602011-11-07 05:07:52 +0000774 if (!CCValue.isLValue()) {
775 Value = CCValue;
776 return true;
777 }
Richard Smith357362d2011-12-13 06:39:58 +0000778 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000779}
780
Richard Smith83c68212011-10-31 05:11:32 +0000781const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +0000782 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +0000783}
784
785static bool IsLiteralLValue(const LValue &Value) {
Richard Smithce40ad62011-11-12 22:28:03 +0000786 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith83c68212011-10-31 05:11:32 +0000787}
788
Richard Smithcecf1842011-11-01 21:06:14 +0000789static bool IsWeakLValue(const LValue &Value) {
790 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +0000791 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +0000792}
793
Richard Smith027bf112011-11-17 22:56:20 +0000794static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +0000795 // A null base expression indicates a null pointer. These are always
796 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +0000797 if (!Value.getLValueBase()) {
798 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +0000799 return true;
800 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000801
John McCall95007602010-05-10 23:27:23 +0000802 // Require the base expression to be a global l-value.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000803 // FIXME: C++11 requires such conversions. Remove this check.
Richard Smith027bf112011-11-17 22:56:20 +0000804 if (!IsGlobalLValue(Value.getLValueBase())) return false;
John McCall95007602010-05-10 23:27:23 +0000805
Richard Smith027bf112011-11-17 22:56:20 +0000806 // We have a non-null base. These are generally known to be true, but if it's
807 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000808 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +0000809 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +0000810 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +0000811}
812
Richard Smith0b0a0b62011-10-29 20:57:55 +0000813static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +0000814 switch (Val.getKind()) {
815 case APValue::Uninitialized:
816 return false;
817 case APValue::Int:
818 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000819 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000820 case APValue::Float:
821 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000822 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000823 case APValue::ComplexInt:
824 Result = Val.getComplexIntReal().getBoolValue() ||
825 Val.getComplexIntImag().getBoolValue();
826 return true;
827 case APValue::ComplexFloat:
828 Result = !Val.getComplexFloatReal().isZero() ||
829 !Val.getComplexFloatImag().isZero();
830 return true;
Richard Smith027bf112011-11-17 22:56:20 +0000831 case APValue::LValue:
832 return EvalPointerValueAsBool(Val, Result);
833 case APValue::MemberPointer:
834 Result = Val.getMemberPointerDecl();
835 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000836 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +0000837 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +0000838 case APValue::Struct:
839 case APValue::Union:
Richard Smith11562c52011-10-28 17:51:58 +0000840 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000841 }
842
Richard Smith11562c52011-10-28 17:51:58 +0000843 llvm_unreachable("unknown APValue kind");
844}
845
846static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
847 EvalInfo &Info) {
848 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000849 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +0000850 if (!Evaluate(Val, Info, E))
851 return false;
852 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +0000853}
854
Richard Smith357362d2011-12-13 06:39:58 +0000855template<typename T>
856static bool HandleOverflow(EvalInfo &Info, const Expr *E,
857 const T &SrcValue, QualType DestType) {
858 llvm::SmallVector<char, 32> Buffer;
859 SrcValue.toString(Buffer);
860 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
861 << StringRef(Buffer.data(), Buffer.size()) << DestType;
862 return false;
863}
864
865static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
866 QualType SrcType, const APFloat &Value,
867 QualType DestType, APSInt &Result) {
868 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000869 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000870 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000871
Richard Smith357362d2011-12-13 06:39:58 +0000872 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000873 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +0000874 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
875 & APFloat::opInvalidOp)
876 return HandleOverflow(Info, E, Value, DestType);
877 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000878}
879
Richard Smith357362d2011-12-13 06:39:58 +0000880static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
881 QualType SrcType, QualType DestType,
882 APFloat &Result) {
883 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000884 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +0000885 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
886 APFloat::rmNearestTiesToEven, &ignored)
887 & APFloat::opOverflow)
888 return HandleOverflow(Info, E, Value, DestType);
889 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000890}
891
Mike Stump11289f42009-09-09 15:08:12 +0000892static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000893 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000894 unsigned DestWidth = Ctx.getIntWidth(DestType);
895 APSInt Result = Value;
896 // Figure out if this is a truncate, extend or noop cast.
897 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000898 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000899 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000900 return Result;
901}
902
Richard Smith357362d2011-12-13 06:39:58 +0000903static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
904 QualType SrcType, const APSInt &Value,
905 QualType DestType, APFloat &Result) {
906 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
907 if (Result.convertFromAPInt(Value, Value.isSigned(),
908 APFloat::rmNearestTiesToEven)
909 & APFloat::opOverflow)
910 return HandleOverflow(Info, E, Value, DestType);
911 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000912}
913
Richard Smith027bf112011-11-17 22:56:20 +0000914static bool FindMostDerivedObject(EvalInfo &Info, const LValue &LVal,
915 const CXXRecordDecl *&MostDerivedType,
916 unsigned &MostDerivedPathLength,
917 bool &MostDerivedIsArrayElement) {
918 const SubobjectDesignator &D = LVal.Designator;
919 if (D.Invalid || !LVal.Base)
Richard Smithd62306a2011-11-10 06:34:14 +0000920 return false;
921
Richard Smith027bf112011-11-17 22:56:20 +0000922 const Type *T = getType(LVal.Base).getTypePtr();
Richard Smithd62306a2011-11-10 06:34:14 +0000923
924 // Find path prefix which leads to the most-derived subobject.
Richard Smithd62306a2011-11-10 06:34:14 +0000925 MostDerivedType = T->getAsCXXRecordDecl();
Richard Smith027bf112011-11-17 22:56:20 +0000926 MostDerivedPathLength = 0;
927 MostDerivedIsArrayElement = false;
Richard Smithd62306a2011-11-10 06:34:14 +0000928
929 for (unsigned I = 0, N = D.Entries.size(); I != N; ++I) {
930 bool IsArray = T && T->isArrayType();
931 if (IsArray)
932 T = T->getBaseElementTypeUnsafe();
933 else if (const FieldDecl *FD = getAsField(D.Entries[I]))
934 T = FD->getType().getTypePtr();
935 else
936 T = 0;
937
938 if (T) {
939 MostDerivedType = T->getAsCXXRecordDecl();
940 MostDerivedPathLength = I + 1;
941 MostDerivedIsArrayElement = IsArray;
942 }
943 }
944
Richard Smithd62306a2011-11-10 06:34:14 +0000945 // (B*)&d + 1 has no most-derived object.
946 if (D.OnePastTheEnd && MostDerivedPathLength != D.Entries.size())
947 return false;
948
Richard Smith027bf112011-11-17 22:56:20 +0000949 return MostDerivedType != 0;
950}
951
952static void TruncateLValueBasePath(EvalInfo &Info, LValue &Result,
953 const RecordDecl *TruncatedType,
954 unsigned TruncatedElements,
955 bool IsArrayElement) {
956 SubobjectDesignator &D = Result.Designator;
957 const RecordDecl *RD = TruncatedType;
958 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smithd62306a2011-11-10 06:34:14 +0000959 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
960 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +0000961 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +0000962 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +0000963 else
Richard Smithd62306a2011-11-10 06:34:14 +0000964 Result.Offset -= Layout.getBaseClassOffset(Base);
965 RD = Base;
966 }
Richard Smith027bf112011-11-17 22:56:20 +0000967 D.Entries.resize(TruncatedElements);
968 D.ArrayElement = IsArrayElement;
969}
970
971/// If the given LValue refers to a base subobject of some object, find the most
972/// derived object and the corresponding complete record type. This is necessary
973/// in order to find the offset of a virtual base class.
974static bool ExtractMostDerivedObject(EvalInfo &Info, LValue &Result,
975 const CXXRecordDecl *&MostDerivedType) {
976 unsigned MostDerivedPathLength;
977 bool MostDerivedIsArrayElement;
978 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
979 MostDerivedPathLength, MostDerivedIsArrayElement))
980 return false;
981
982 // Remove the trailing base class path entries and their offsets.
983 TruncateLValueBasePath(Info, Result, MostDerivedType, MostDerivedPathLength,
984 MostDerivedIsArrayElement);
Richard Smithd62306a2011-11-10 06:34:14 +0000985 return true;
986}
987
988static void HandleLValueDirectBase(EvalInfo &Info, LValue &Obj,
989 const CXXRecordDecl *Derived,
990 const CXXRecordDecl *Base,
991 const ASTRecordLayout *RL = 0) {
992 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
993 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
994 Obj.Designator.addDecl(Base, /*Virtual*/ false);
995}
996
997static bool HandleLValueBase(EvalInfo &Info, LValue &Obj,
998 const CXXRecordDecl *DerivedDecl,
999 const CXXBaseSpecifier *Base) {
1000 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1001
1002 if (!Base->isVirtual()) {
1003 HandleLValueDirectBase(Info, Obj, DerivedDecl, BaseDecl);
1004 return true;
1005 }
1006
1007 // Extract most-derived object and corresponding type.
1008 if (!ExtractMostDerivedObject(Info, Obj, DerivedDecl))
1009 return false;
1010
1011 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1012 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1013 Obj.Designator.addDecl(BaseDecl, /*Virtual*/ true);
1014 return true;
1015}
1016
1017/// Update LVal to refer to the given field, which must be a member of the type
1018/// currently described by LVal.
1019static void HandleLValueMember(EvalInfo &Info, LValue &LVal,
1020 const FieldDecl *FD,
1021 const ASTRecordLayout *RL = 0) {
1022 if (!RL)
1023 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1024
1025 unsigned I = FD->getFieldIndex();
1026 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
1027 LVal.Designator.addDecl(FD);
1028}
1029
1030/// Get the size of the given type in char units.
1031static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1032 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1033 // extension.
1034 if (Type->isVoidType() || Type->isFunctionType()) {
1035 Size = CharUnits::One();
1036 return true;
1037 }
1038
1039 if (!Type->isConstantSizeType()) {
1040 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1041 return false;
1042 }
1043
1044 Size = Info.Ctx.getTypeSizeInChars(Type);
1045 return true;
1046}
1047
1048/// Update a pointer value to model pointer arithmetic.
1049/// \param Info - Information about the ongoing evaluation.
1050/// \param LVal - The pointer value to be updated.
1051/// \param EltTy - The pointee type represented by LVal.
1052/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
1053static bool HandleLValueArrayAdjustment(EvalInfo &Info, LValue &LVal,
1054 QualType EltTy, int64_t Adjustment) {
1055 CharUnits SizeOfPointee;
1056 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1057 return false;
1058
1059 // Compute the new offset in the appropriate width.
1060 LVal.Offset += Adjustment * SizeOfPointee;
1061 LVal.Designator.adjustIndex(Adjustment);
1062 return true;
1063}
1064
Richard Smith27908702011-10-24 17:54:18 +00001065/// Try to evaluate the initializer for a variable declaration.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001066static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1067 const VarDecl *VD,
Richard Smithfec09922011-11-01 16:57:24 +00001068 CallStackFrame *Frame, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001069 // If this is a parameter to an active constexpr function call, perform
1070 // argument substitution.
1071 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001072 if (!Frame || !Frame->Arguments) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001073 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001074 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001075 }
Richard Smithfec09922011-11-01 16:57:24 +00001076 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1077 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001078 }
Richard Smith27908702011-10-24 17:54:18 +00001079
Richard Smithd0b4dd62011-12-19 06:19:21 +00001080 // Dig out the initializer, and use the declaration which it's attached to.
1081 const Expr *Init = VD->getAnyInitializer(VD);
1082 if (!Init || Init->isValueDependent()) {
1083 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1084 return false;
1085 }
1086
Richard Smithd62306a2011-11-10 06:34:14 +00001087 // If we're currently evaluating the initializer of this declaration, use that
1088 // in-flight value.
1089 if (Info.EvaluatingDecl == VD) {
1090 Result = CCValue(*Info.EvaluatingDeclValue, CCValue::GlobalValue());
1091 return !Result.isUninit();
1092 }
1093
Richard Smithcecf1842011-11-01 21:06:14 +00001094 // Never evaluate the initializer of a weak variable. We can't be sure that
1095 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001096 if (VD->isWeak()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001097 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001098 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001099 }
Richard Smithcecf1842011-11-01 21:06:14 +00001100
Richard Smithd0b4dd62011-12-19 06:19:21 +00001101 // Check that we can fold the initializer. In C++, we will have already done
1102 // this in the cases where it matters for conformance.
1103 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1104 if (!VD->evaluateValue(Notes)) {
1105 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1106 Notes.size() + 1) << VD;
1107 Info.Note(VD->getLocation(), diag::note_declared_at);
1108 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001109 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001110 } else if (!VD->checkInitIsICE()) {
1111 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1112 Notes.size() + 1) << VD;
1113 Info.Note(VD->getLocation(), diag::note_declared_at);
1114 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001115 }
Richard Smith27908702011-10-24 17:54:18 +00001116
Richard Smithd0b4dd62011-12-19 06:19:21 +00001117 Result = CCValue(*VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +00001118 return true;
Richard Smith27908702011-10-24 17:54:18 +00001119}
1120
Richard Smith11562c52011-10-28 17:51:58 +00001121static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001122 Qualifiers Quals = T.getQualifiers();
1123 return Quals.hasConst() && !Quals.hasVolatile();
1124}
1125
Richard Smithe97cbd72011-11-11 04:05:33 +00001126/// Get the base index of the given base class within an APValue representing
1127/// the given derived class.
1128static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1129 const CXXRecordDecl *Base) {
1130 Base = Base->getCanonicalDecl();
1131 unsigned Index = 0;
1132 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1133 E = Derived->bases_end(); I != E; ++I, ++Index) {
1134 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1135 return Index;
1136 }
1137
1138 llvm_unreachable("base class missing from derived class's bases list");
1139}
1140
Richard Smithf3e9e432011-11-07 09:22:26 +00001141/// Extract the designated sub-object of an rvalue.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001142static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1143 CCValue &Obj, QualType ObjType,
Richard Smithf3e9e432011-11-07 09:22:26 +00001144 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001145 if (Sub.Invalid || Sub.OnePastTheEnd) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001146 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +00001147 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001148 }
Richard Smith6804be52011-11-11 08:28:03 +00001149 if (Sub.Entries.empty())
Richard Smithf3e9e432011-11-07 09:22:26 +00001150 return true;
Richard Smithf3e9e432011-11-07 09:22:26 +00001151
1152 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1153 const APValue *O = &Obj;
Richard Smithd62306a2011-11-10 06:34:14 +00001154 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001155 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001156 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001157 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001158 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001159 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001160 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001161 if (CAT->getSize().ule(Index)) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001162 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +00001163 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001164 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001165 if (O->getArrayInitializedElts() > Index)
1166 O = &O->getArrayInitializedElt(Index);
1167 else
1168 O = &O->getArrayFiller();
1169 ObjType = CAT->getElementType();
Richard Smithd62306a2011-11-10 06:34:14 +00001170 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1171 // Next subobject is a class, struct or union field.
1172 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1173 if (RD->isUnion()) {
1174 const FieldDecl *UnionField = O->getUnionField();
1175 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001176 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001177 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +00001178 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001179 }
Richard Smithd62306a2011-11-10 06:34:14 +00001180 O = &O->getUnionValue();
1181 } else
1182 O = &O->getStructField(Field->getFieldIndex());
1183 ObjType = Field->getType();
Richard Smithf3e9e432011-11-07 09:22:26 +00001184 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001185 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001186 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1187 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1188 O = &O->getStructBase(getBaseIndex(Derived, Base));
1189 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithf3e9e432011-11-07 09:22:26 +00001190 }
Richard Smithd62306a2011-11-10 06:34:14 +00001191
Richard Smithf57d8cb2011-12-09 22:58:01 +00001192 if (O->isUninit()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001193 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +00001194 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001195 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001196 }
1197
Richard Smithf3e9e432011-11-07 09:22:26 +00001198 Obj = CCValue(*O, CCValue::GlobalValue());
1199 return true;
1200}
1201
Richard Smithd62306a2011-11-10 06:34:14 +00001202/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1203/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1204/// for looking up the glvalue referred to by an entity of reference type.
1205///
1206/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001207/// \param Conv - The expression for which we are performing the conversion.
1208/// Used for diagnostics.
Richard Smithd62306a2011-11-10 06:34:14 +00001209/// \param Type - The type we expect this conversion to produce.
1210/// \param LVal - The glvalue on which we are attempting to perform this action.
1211/// \param RVal - The produced value will be placed here.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001212static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1213 QualType Type,
Richard Smithf3e9e432011-11-07 09:22:26 +00001214 const LValue &LVal, CCValue &RVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001215 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001216 CallStackFrame *Frame = LVal.Frame;
Richard Smith11562c52011-10-28 17:51:58 +00001217
Richard Smithf57d8cb2011-12-09 22:58:01 +00001218 if (!LVal.Base) {
1219 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith92b1ce02011-12-12 09:28:41 +00001220 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith11562c52011-10-28 17:51:58 +00001221 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001222 }
Richard Smith11562c52011-10-28 17:51:58 +00001223
Richard Smithce40ad62011-11-12 22:28:03 +00001224 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smith11562c52011-10-28 17:51:58 +00001225 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1226 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +00001227 // expressions are constant expressions too. Inside constexpr functions,
1228 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +00001229 // In C, such things can also be folded, although they are not ICEs.
1230 //
Richard Smith254a73d2011-10-28 22:34:42 +00001231 // FIXME: volatile-qualified ParmVarDecls need special handling. A literal
1232 // interpretation of C++11 suggests that volatile parameters are OK if
1233 // they're never read (there's no prohibition against constructing volatile
1234 // objects in constant expressions), but lvalue-to-rvalue conversions on
1235 // them are not permitted.
Richard Smith11562c52011-10-28 17:51:58 +00001236 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001237 if (!VD || VD->isInvalidDecl()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001238 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001239 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001240 }
1241
Richard Smithce40ad62011-11-12 22:28:03 +00001242 QualType VT = VD->getType();
Richard Smith96e0c102011-11-04 02:25:55 +00001243 if (!isa<ParmVarDecl>(VD)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001244 if (!IsConstNonVolatile(VT)) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001245 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001246 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001247 }
Richard Smitha08acd82011-11-07 03:22:51 +00001248 // FIXME: Allow folding of values of any literal type in all languages.
1249 if (!VT->isIntegralOrEnumerationType() && !VT->isRealFloatingType() &&
Richard Smithf57d8cb2011-12-09 22:58:01 +00001250 !VD->isConstexpr()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001251 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001252 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001253 }
Richard Smith96e0c102011-11-04 02:25:55 +00001254 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00001255 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smith11562c52011-10-28 17:51:58 +00001256 return false;
1257
Richard Smith0b0a0b62011-10-29 20:57:55 +00001258 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf57d8cb2011-12-09 22:58:01 +00001259 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smith11562c52011-10-28 17:51:58 +00001260
1261 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1262 // conversion. This happens when the declaration and the lvalue should be
1263 // considered synonymous, for instance when initializing an array of char
1264 // from a string literal. Continue as if the initializer lvalue was the
1265 // value we were originally given.
Richard Smith96e0c102011-11-04 02:25:55 +00001266 assert(RVal.getLValueOffset().isZero() &&
1267 "offset for lvalue init of non-reference");
Richard Smithce40ad62011-11-12 22:28:03 +00001268 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001269 Frame = RVal.getLValueFrame();
Richard Smith11562c52011-10-28 17:51:58 +00001270 }
1271
Richard Smith96e0c102011-11-04 02:25:55 +00001272 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1273 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1274 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001275 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001276 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001277 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001278 }
Richard Smith96e0c102011-11-04 02:25:55 +00001279
1280 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith80815602011-11-07 05:07:52 +00001281 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001282 if (Index > S->getLength()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001283 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001284 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001285 }
Richard Smith96e0c102011-11-04 02:25:55 +00001286 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1287 Type->isUnsignedIntegerType());
1288 if (Index < S->getLength())
1289 Value = S->getCodeUnit(Index);
1290 RVal = CCValue(Value);
1291 return true;
1292 }
1293
Richard Smithf3e9e432011-11-07 09:22:26 +00001294 if (Frame) {
1295 // If this is a temporary expression with a nontrivial initializer, grab the
1296 // value from the relevant stack frame.
1297 RVal = Frame->Temporaries[Base];
1298 } else if (const CompoundLiteralExpr *CLE
1299 = dyn_cast<CompoundLiteralExpr>(Base)) {
1300 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1301 // initializer until now for such expressions. Such an expression can't be
1302 // an ICE in C, so this only matters for fold.
1303 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1304 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1305 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001306 } else {
Richard Smith92b1ce02011-12-12 09:28:41 +00001307 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001308 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001309 }
Richard Smith96e0c102011-11-04 02:25:55 +00001310
Richard Smithf57d8cb2011-12-09 22:58:01 +00001311 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1312 Type);
Richard Smith11562c52011-10-28 17:51:58 +00001313}
1314
Richard Smithe97cbd72011-11-11 04:05:33 +00001315/// Build an lvalue for the object argument of a member function call.
1316static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1317 LValue &This) {
1318 if (Object->getType()->isPointerType())
1319 return EvaluatePointer(Object, This, Info);
1320
1321 if (Object->isGLValue())
1322 return EvaluateLValue(Object, This, Info);
1323
Richard Smith027bf112011-11-17 22:56:20 +00001324 if (Object->getType()->isLiteralType())
1325 return EvaluateTemporary(Object, This, Info);
1326
1327 return false;
1328}
1329
1330/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1331/// lvalue referring to the result.
1332///
1333/// \param Info - Information about the ongoing evaluation.
1334/// \param BO - The member pointer access operation.
1335/// \param LV - Filled in with a reference to the resulting object.
1336/// \param IncludeMember - Specifies whether the member itself is included in
1337/// the resulting LValue subobject designator. This is not possible when
1338/// creating a bound member function.
1339/// \return The field or method declaration to which the member pointer refers,
1340/// or 0 if evaluation fails.
1341static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1342 const BinaryOperator *BO,
1343 LValue &LV,
1344 bool IncludeMember = true) {
1345 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1346
1347 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV))
1348 return 0;
1349
1350 MemberPtr MemPtr;
1351 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1352 return 0;
1353
1354 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1355 // member value, the behavior is undefined.
1356 if (!MemPtr.getDecl())
1357 return 0;
1358
1359 if (MemPtr.isDerivedMember()) {
1360 // This is a member of some derived class. Truncate LV appropriately.
1361 const CXXRecordDecl *MostDerivedType;
1362 unsigned MostDerivedPathLength;
1363 bool MostDerivedIsArrayElement;
1364 if (!FindMostDerivedObject(Info, LV, MostDerivedType, MostDerivedPathLength,
1365 MostDerivedIsArrayElement))
1366 return 0;
1367
1368 // The end of the derived-to-base path for the base object must match the
1369 // derived-to-base path for the member pointer.
1370 if (MostDerivedPathLength + MemPtr.Path.size() >
1371 LV.Designator.Entries.size())
1372 return 0;
1373 unsigned PathLengthToMember =
1374 LV.Designator.Entries.size() - MemPtr.Path.size();
1375 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1376 const CXXRecordDecl *LVDecl = getAsBaseClass(
1377 LV.Designator.Entries[PathLengthToMember + I]);
1378 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1379 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1380 return 0;
1381 }
1382
1383 // Truncate the lvalue to the appropriate derived class.
1384 bool ResultIsArray = false;
1385 if (PathLengthToMember == MostDerivedPathLength)
1386 ResultIsArray = MostDerivedIsArrayElement;
1387 TruncateLValueBasePath(Info, LV, MemPtr.getContainingRecord(),
1388 PathLengthToMember, ResultIsArray);
1389 } else if (!MemPtr.Path.empty()) {
1390 // Extend the LValue path with the member pointer's path.
1391 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1392 MemPtr.Path.size() + IncludeMember);
1393
1394 // Walk down to the appropriate base class.
1395 QualType LVType = BO->getLHS()->getType();
1396 if (const PointerType *PT = LVType->getAs<PointerType>())
1397 LVType = PT->getPointeeType();
1398 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1399 assert(RD && "member pointer access on non-class-type expression");
1400 // The first class in the path is that of the lvalue.
1401 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1402 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
1403 HandleLValueDirectBase(Info, LV, RD, Base);
1404 RD = Base;
1405 }
1406 // Finally cast to the class containing the member.
1407 HandleLValueDirectBase(Info, LV, RD, MemPtr.getContainingRecord());
1408 }
1409
1410 // Add the member. Note that we cannot build bound member functions here.
1411 if (IncludeMember) {
1412 // FIXME: Deal with IndirectFieldDecls.
1413 const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl());
1414 if (!FD) return 0;
1415 HandleLValueMember(Info, LV, FD);
1416 }
1417
1418 return MemPtr.getDecl();
1419}
1420
1421/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1422/// the provided lvalue, which currently refers to the base object.
1423static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1424 LValue &Result) {
1425 const CXXRecordDecl *MostDerivedType;
1426 unsigned MostDerivedPathLength;
1427 bool MostDerivedIsArrayElement;
1428
1429 // Check this cast doesn't take us outside the object.
1430 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
1431 MostDerivedPathLength,
1432 MostDerivedIsArrayElement))
1433 return false;
1434 SubobjectDesignator &D = Result.Designator;
1435 if (MostDerivedPathLength + E->path_size() > D.Entries.size())
1436 return false;
1437
1438 // Check the type of the final cast. We don't need to check the path,
1439 // since a cast can only be formed if the path is unique.
1440 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
1441 bool ResultIsArray = false;
1442 QualType TargetQT = E->getType();
1443 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1444 TargetQT = PT->getPointeeType();
1445 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1446 const CXXRecordDecl *FinalType;
1447 if (NewEntriesSize == MostDerivedPathLength) {
1448 ResultIsArray = MostDerivedIsArrayElement;
1449 FinalType = MostDerivedType;
1450 } else
1451 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
1452 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
1453 return false;
1454
1455 // Truncate the lvalue to the appropriate derived class.
1456 TruncateLValueBasePath(Info, Result, TargetType, NewEntriesSize,
1457 ResultIsArray);
1458 return true;
Richard Smithe97cbd72011-11-11 04:05:33 +00001459}
1460
Mike Stump876387b2009-10-27 22:09:17 +00001461namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00001462enum EvalStmtResult {
1463 /// Evaluation failed.
1464 ESR_Failed,
1465 /// Hit a 'return' statement.
1466 ESR_Returned,
1467 /// Evaluation succeeded.
1468 ESR_Succeeded
1469};
1470}
1471
1472// Evaluate a statement.
Richard Smith357362d2011-12-13 06:39:58 +00001473static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +00001474 const Stmt *S) {
1475 switch (S->getStmtClass()) {
1476 default:
1477 return ESR_Failed;
1478
1479 case Stmt::NullStmtClass:
1480 case Stmt::DeclStmtClass:
1481 return ESR_Succeeded;
1482
Richard Smith357362d2011-12-13 06:39:58 +00001483 case Stmt::ReturnStmtClass: {
1484 CCValue CCResult;
1485 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1486 if (!Evaluate(CCResult, Info, RetExpr) ||
1487 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1488 CCEK_ReturnValue))
1489 return ESR_Failed;
1490 return ESR_Returned;
1491 }
Richard Smith254a73d2011-10-28 22:34:42 +00001492
1493 case Stmt::CompoundStmtClass: {
1494 const CompoundStmt *CS = cast<CompoundStmt>(S);
1495 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1496 BE = CS->body_end(); BI != BE; ++BI) {
1497 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1498 if (ESR != ESR_Succeeded)
1499 return ESR;
1500 }
1501 return ESR_Succeeded;
1502 }
1503 }
1504}
1505
Richard Smith357362d2011-12-13 06:39:58 +00001506/// CheckConstexprFunction - Check that a function can be called in a constant
1507/// expression.
1508static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1509 const FunctionDecl *Declaration,
1510 const FunctionDecl *Definition) {
1511 // Can we evaluate this function call?
1512 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1513 return true;
1514
1515 if (Info.getLangOpts().CPlusPlus0x) {
1516 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001517 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1518 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00001519 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1520 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1521 << DiagDecl;
1522 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1523 } else {
1524 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1525 }
1526 return false;
1527}
1528
Richard Smithd62306a2011-11-10 06:34:14 +00001529namespace {
Richard Smith60494462011-11-11 05:48:57 +00001530typedef SmallVector<CCValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00001531}
1532
1533/// EvaluateArgs - Evaluate the arguments to a function call.
1534static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1535 EvalInfo &Info) {
1536 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1537 I != E; ++I)
1538 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1539 return false;
1540 return true;
1541}
1542
Richard Smith254a73d2011-10-28 22:34:42 +00001543/// Evaluate a function call.
Richard Smithf6f003a2011-12-16 19:06:07 +00001544static bool HandleFunctionCall(const Expr *CallExpr, const FunctionDecl *Callee,
1545 const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00001546 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith357362d2011-12-13 06:39:58 +00001547 EvalInfo &Info, APValue &Result) {
1548 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smith254a73d2011-10-28 22:34:42 +00001549 return false;
1550
Richard Smithd62306a2011-11-10 06:34:14 +00001551 ArgVector ArgValues(Args.size());
1552 if (!EvaluateArgs(Args, ArgValues, Info))
1553 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00001554
Richard Smithf6f003a2011-12-16 19:06:07 +00001555 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Callee, This,
1556 ArgValues.data());
Richard Smith254a73d2011-10-28 22:34:42 +00001557 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1558}
1559
Richard Smithd62306a2011-11-10 06:34:14 +00001560/// Evaluate a constructor call.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001561static bool HandleConstructorCall(const Expr *CallExpr, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00001562 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00001563 const CXXConstructorDecl *Definition,
Richard Smithe97cbd72011-11-11 04:05:33 +00001564 EvalInfo &Info,
Richard Smithd62306a2011-11-10 06:34:14 +00001565 APValue &Result) {
Richard Smith357362d2011-12-13 06:39:58 +00001566 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smithd62306a2011-11-10 06:34:14 +00001567 return false;
1568
1569 ArgVector ArgValues(Args.size());
1570 if (!EvaluateArgs(Args, ArgValues, Info))
1571 return false;
1572
Richard Smithf6f003a2011-12-16 19:06:07 +00001573 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Definition,
1574 &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00001575
1576 // If it's a delegating constructor, just delegate.
1577 if (Definition->isDelegatingConstructor()) {
1578 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1579 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1580 }
1581
1582 // Reserve space for the struct members.
1583 const CXXRecordDecl *RD = Definition->getParent();
1584 if (!RD->isUnion())
1585 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1586 std::distance(RD->field_begin(), RD->field_end()));
1587
1588 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1589
1590 unsigned BasesSeen = 0;
1591#ifndef NDEBUG
1592 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1593#endif
1594 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1595 E = Definition->init_end(); I != E; ++I) {
1596 if ((*I)->isBaseInitializer()) {
1597 QualType BaseType((*I)->getBaseClass(), 0);
1598#ifndef NDEBUG
1599 // Non-virtual base classes are initialized in the order in the class
1600 // definition. We cannot have a virtual base class for a literal type.
1601 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1602 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1603 "base class initializers not in expected order");
1604 ++BaseIt;
1605#endif
1606 LValue Subobject = This;
1607 HandleLValueDirectBase(Info, Subobject, RD,
1608 BaseType->getAsCXXRecordDecl(), &Layout);
1609 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1610 Subobject, (*I)->getInit()))
1611 return false;
1612 } else if (FieldDecl *FD = (*I)->getMember()) {
1613 LValue Subobject = This;
1614 HandleLValueMember(Info, Subobject, FD, &Layout);
1615 if (RD->isUnion()) {
1616 Result = APValue(FD);
Richard Smith357362d2011-12-13 06:39:58 +00001617 if (!EvaluateConstantExpression(Result.getUnionValue(), Info, Subobject,
1618 (*I)->getInit(), CCEK_MemberInit))
Richard Smithd62306a2011-11-10 06:34:14 +00001619 return false;
1620 } else if (!EvaluateConstantExpression(
1621 Result.getStructField(FD->getFieldIndex()),
Richard Smith357362d2011-12-13 06:39:58 +00001622 Info, Subobject, (*I)->getInit(), CCEK_MemberInit))
Richard Smithd62306a2011-11-10 06:34:14 +00001623 return false;
1624 } else {
1625 // FIXME: handle indirect field initializers
Richard Smith92b1ce02011-12-12 09:28:41 +00001626 Info.Diag((*I)->getInit()->getExprLoc(),
Richard Smithf57d8cb2011-12-09 22:58:01 +00001627 diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +00001628 return false;
1629 }
1630 }
1631
1632 return true;
1633}
1634
Richard Smith254a73d2011-10-28 22:34:42 +00001635namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001636class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +00001637 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +00001638 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +00001639public:
1640
Richard Smith725810a2011-10-16 21:26:27 +00001641 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +00001642
1643 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +00001644 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +00001645 return true;
1646 }
1647
Peter Collingbournee9200682011-05-13 03:29:01 +00001648 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1649 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001650 return Visit(E->getResultExpr());
1651 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001652 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001653 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001654 return true;
1655 return false;
1656 }
John McCall31168b02011-06-15 23:02:42 +00001657 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001658 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001659 return true;
1660 return false;
1661 }
1662 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001663 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001664 return true;
1665 return false;
1666 }
1667
Mike Stump876387b2009-10-27 22:09:17 +00001668 // We don't want to evaluate BlockExprs multiple times, as they generate
1669 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +00001670 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1671 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1672 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +00001673 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001674 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1675 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1676 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1677 bool VisitStringLiteral(const StringLiteral *E) { return false; }
1678 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1679 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +00001680 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +00001681 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001682 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001683 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +00001684 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001685 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
1686 bool VisitBinAssign(const BinaryOperator *E) { return true; }
1687 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
1688 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001689 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001690 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
1691 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
1692 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
1693 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
1694 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001695 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001696 return true;
Mike Stumpfa502902009-10-29 20:48:09 +00001697 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +00001698 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001699 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +00001700
1701 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +00001702 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +00001703 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
1704 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00001705 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +00001706 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +00001707 return false;
1708 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001709
Peter Collingbournee9200682011-05-13 03:29:01 +00001710 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +00001711};
1712
John McCallc07a0c72011-02-17 10:25:35 +00001713class OpaqueValueEvaluation {
1714 EvalInfo &info;
1715 OpaqueValueExpr *opaqueValue;
1716
1717public:
1718 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
1719 Expr *value)
1720 : info(info), opaqueValue(opaqueValue) {
1721
1722 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +00001723 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +00001724 this->opaqueValue = 0;
1725 return;
1726 }
John McCallc07a0c72011-02-17 10:25:35 +00001727 }
1728
1729 bool hasError() const { return opaqueValue == 0; }
1730
1731 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +00001732 // FIXME: This will not work for recursive constexpr functions using opaque
1733 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +00001734 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
1735 }
1736};
1737
Mike Stump876387b2009-10-27 22:09:17 +00001738} // end anonymous namespace
1739
Eli Friedman9a156e52008-11-12 09:44:48 +00001740//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00001741// Generic Evaluation
1742//===----------------------------------------------------------------------===//
1743namespace {
1744
Richard Smithf57d8cb2011-12-09 22:58:01 +00001745// FIXME: RetTy is always bool. Remove it.
1746template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00001747class ExprEvaluatorBase
1748 : public ConstStmtVisitor<Derived, RetTy> {
1749private:
Richard Smith0b0a0b62011-10-29 20:57:55 +00001750 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001751 return static_cast<Derived*>(this)->Success(V, E);
1752 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001753 RetTy DerivedValueInitialization(const Expr *E) {
1754 return static_cast<Derived*>(this)->ValueInitialization(E);
1755 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001756
1757protected:
1758 EvalInfo &Info;
1759 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
1760 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
1761
Richard Smith92b1ce02011-12-12 09:28:41 +00001762 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith187ef012011-12-12 09:41:58 +00001763 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001764 }
1765
1766 /// Report an evaluation error. This should only be called when an error is
1767 /// first discovered. When propagating an error, just return false.
1768 bool Error(const Expr *E, diag::kind D) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001769 Info.Diag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001770 return false;
1771 }
1772 bool Error(const Expr *E) {
1773 return Error(E, diag::note_invalid_subexpr_in_const_expr);
1774 }
1775
1776 RetTy ValueInitialization(const Expr *E) { return Error(E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00001777
Peter Collingbournee9200682011-05-13 03:29:01 +00001778public:
1779 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
1780
1781 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00001782 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00001783 }
1784 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001785 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001786 }
1787
1788 RetTy VisitParenExpr(const ParenExpr *E)
1789 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1790 RetTy VisitUnaryExtension(const UnaryOperator *E)
1791 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1792 RetTy VisitUnaryPlus(const UnaryOperator *E)
1793 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1794 RetTy VisitChooseExpr(const ChooseExpr *E)
1795 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
1796 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
1797 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00001798 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
1799 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00001800 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
1801 { return StmtVisitorTy::Visit(E->getExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001802
Richard Smith6d6ecc32011-12-12 12:46:16 +00001803 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
1804 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
1805 return static_cast<Derived*>(this)->VisitCastExpr(E);
1806 }
1807 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
1808 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
1809 return static_cast<Derived*>(this)->VisitCastExpr(E);
1810 }
1811
Richard Smith027bf112011-11-17 22:56:20 +00001812 RetTy VisitBinaryOperator(const BinaryOperator *E) {
1813 switch (E->getOpcode()) {
1814 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00001815 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00001816
1817 case BO_Comma:
1818 VisitIgnoredValue(E->getLHS());
1819 return StmtVisitorTy::Visit(E->getRHS());
1820
1821 case BO_PtrMemD:
1822 case BO_PtrMemI: {
1823 LValue Obj;
1824 if (!HandleMemberPointerAccess(Info, E, Obj))
1825 return false;
1826 CCValue Result;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001827 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00001828 return false;
1829 return DerivedSuccess(Result, E);
1830 }
1831 }
1832 }
1833
Peter Collingbournee9200682011-05-13 03:29:01 +00001834 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
1835 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
1836 if (opaque.hasError())
Richard Smithf57d8cb2011-12-09 22:58:01 +00001837 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001838
1839 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +00001840 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001841 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001842
1843 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
1844 }
1845
1846 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
1847 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00001848 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001849 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001850
Richard Smith11562c52011-10-28 17:51:58 +00001851 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +00001852 return StmtVisitorTy::Visit(EvalExpr);
1853 }
1854
1855 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001856 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00001857 if (!Value) {
1858 const Expr *Source = E->getSourceExpr();
1859 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00001860 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00001861 if (Source == E) { // sanity checking.
1862 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00001863 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00001864 }
1865 return StmtVisitorTy::Visit(Source);
1866 }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001867 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001868 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001869
Richard Smith254a73d2011-10-28 22:34:42 +00001870 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00001871 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00001872 QualType CalleeType = Callee->getType();
1873
Richard Smith254a73d2011-10-28 22:34:42 +00001874 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00001875 LValue *This = 0, ThisVal;
1876 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith656d49d2011-11-10 09:31:24 +00001877
Richard Smithe97cbd72011-11-11 04:05:33 +00001878 // Extract function decl and 'this' pointer from the callee.
1879 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001880 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00001881 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
1882 // Explicit bound member calls, such as x.f() or p->g();
1883 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001884 return false;
1885 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00001886 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00001887 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
1888 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00001889 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
1890 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00001891 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00001892 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00001893 return Error(Callee);
1894
1895 FD = dyn_cast<FunctionDecl>(Member);
1896 if (!FD)
1897 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00001898 } else if (CalleeType->isFunctionPointerType()) {
1899 CCValue Call;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001900 if (!Evaluate(Call, Info, Callee))
1901 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00001902
Richard Smithf57d8cb2011-12-09 22:58:01 +00001903 if (!Call.isLValue() || !Call.getLValueOffset().isZero())
1904 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00001905 FD = dyn_cast_or_null<FunctionDecl>(
1906 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00001907 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00001908 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00001909
1910 // Overloaded operator calls to member functions are represented as normal
1911 // calls with '*this' as the first argument.
1912 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1913 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001914 // FIXME: When selecting an implicit conversion for an overloaded
1915 // operator delete, we sometimes try to evaluate calls to conversion
1916 // operators without a 'this' parameter!
1917 if (Args.empty())
1918 return Error(E);
1919
Richard Smithe97cbd72011-11-11 04:05:33 +00001920 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
1921 return false;
1922 This = &ThisVal;
1923 Args = Args.slice(1);
1924 }
1925
1926 // Don't call function pointers which have been cast to some other type.
1927 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001928 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00001929 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00001930 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00001931
Richard Smith357362d2011-12-13 06:39:58 +00001932 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00001933 Stmt *Body = FD->getBody(Definition);
Richard Smithed5165f2011-11-04 05:33:44 +00001934 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00001935
Richard Smith357362d2011-12-13 06:39:58 +00001936 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smithf6f003a2011-12-16 19:06:07 +00001937 !HandleFunctionCall(E, Definition, This, Args, Body, Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001938 return false;
1939
1940 return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
Richard Smith254a73d2011-10-28 22:34:42 +00001941 }
1942
Richard Smith11562c52011-10-28 17:51:58 +00001943 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1944 return StmtVisitorTy::Visit(E->getInitializer());
1945 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001946 RetTy VisitInitListExpr(const InitListExpr *E) {
1947 if (Info.getLangOpts().CPlusPlus0x) {
1948 if (E->getNumInits() == 0)
1949 return DerivedValueInitialization(E);
1950 if (E->getNumInits() == 1)
1951 return StmtVisitorTy::Visit(E->getInit(0));
1952 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00001953 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00001954 }
1955 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1956 return DerivedValueInitialization(E);
1957 }
1958 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
1959 return DerivedValueInitialization(E);
1960 }
Richard Smith027bf112011-11-17 22:56:20 +00001961 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
1962 return DerivedValueInitialization(E);
1963 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001964
Richard Smithd62306a2011-11-10 06:34:14 +00001965 /// A member expression where the object is a prvalue is itself a prvalue.
1966 RetTy VisitMemberExpr(const MemberExpr *E) {
1967 assert(!E->isArrow() && "missing call to bound member function?");
1968
1969 CCValue Val;
1970 if (!Evaluate(Val, Info, E->getBase()))
1971 return false;
1972
1973 QualType BaseTy = E->getBase()->getType();
1974
1975 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00001976 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00001977 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
1978 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
1979 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
1980
1981 SubobjectDesignator Designator;
1982 Designator.addDecl(FD);
1983
Richard Smithf57d8cb2011-12-09 22:58:01 +00001984 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smithd62306a2011-11-10 06:34:14 +00001985 DerivedSuccess(Val, E);
1986 }
1987
Richard Smith11562c52011-10-28 17:51:58 +00001988 RetTy VisitCastExpr(const CastExpr *E) {
1989 switch (E->getCastKind()) {
1990 default:
1991 break;
1992
1993 case CK_NoOp:
1994 return StmtVisitorTy::Visit(E->getSubExpr());
1995
1996 case CK_LValueToRValue: {
1997 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001998 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
1999 return false;
2000 CCValue RVal;
2001 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2002 return false;
2003 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00002004 }
2005 }
2006
Richard Smithf57d8cb2011-12-09 22:58:01 +00002007 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002008 }
2009
Richard Smith4a678122011-10-24 18:44:57 +00002010 /// Visit a value which is evaluated, but whose value is ignored.
2011 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002012 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +00002013 if (!Evaluate(Scratch, Info, E))
2014 Info.EvalStatus.HasSideEffects = true;
2015 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002016};
2017
2018}
2019
2020//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002021// Common base class for lvalue and temporary evaluation.
2022//===----------------------------------------------------------------------===//
2023namespace {
2024template<class Derived>
2025class LValueExprEvaluatorBase
2026 : public ExprEvaluatorBase<Derived, bool> {
2027protected:
2028 LValue &Result;
2029 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2030 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2031
2032 bool Success(APValue::LValueBase B) {
2033 Result.set(B);
2034 return true;
2035 }
2036
2037public:
2038 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2039 ExprEvaluatorBaseTy(Info), Result(Result) {}
2040
2041 bool Success(const CCValue &V, const Expr *E) {
2042 Result.setFrom(V);
2043 return true;
2044 }
Richard Smith027bf112011-11-17 22:56:20 +00002045
2046 bool CheckValidLValue() {
2047 // C++11 [basic.lval]p1: An lvalue designates a function or an object. Hence
2048 // there are no null references, nor once-past-the-end references.
2049 // FIXME: Check for one-past-the-end array indices
2050 return Result.Base && !Result.Designator.Invalid &&
2051 !Result.Designator.OnePastTheEnd;
2052 }
2053
2054 bool VisitMemberExpr(const MemberExpr *E) {
2055 // Handle non-static data members.
2056 QualType BaseTy;
2057 if (E->isArrow()) {
2058 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2059 return false;
2060 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00002061 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002062 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00002063 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2064 return false;
2065 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00002066 } else {
2067 if (!this->Visit(E->getBase()))
2068 return false;
2069 BaseTy = E->getBase()->getType();
2070 }
2071 // FIXME: In C++11, require the result to be a valid lvalue.
2072
2073 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2074 // FIXME: Handle IndirectFieldDecls
Richard Smithf57d8cb2011-12-09 22:58:01 +00002075 if (!FD) return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002076 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2077 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2078 (void)BaseTy;
2079
2080 HandleLValueMember(this->Info, Result, FD);
2081
2082 if (FD->getType()->isReferenceType()) {
2083 CCValue RefValue;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002084 if (!HandleLValueToRValueConversion(this->Info, E, FD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002085 RefValue))
2086 return false;
2087 return Success(RefValue, E);
2088 }
2089 return true;
2090 }
2091
2092 bool VisitBinaryOperator(const BinaryOperator *E) {
2093 switch (E->getOpcode()) {
2094 default:
2095 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2096
2097 case BO_PtrMemD:
2098 case BO_PtrMemI:
2099 return HandleMemberPointerAccess(this->Info, E, Result);
2100 }
2101 }
2102
2103 bool VisitCastExpr(const CastExpr *E) {
2104 switch (E->getCastKind()) {
2105 default:
2106 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2107
2108 case CK_DerivedToBase:
2109 case CK_UncheckedDerivedToBase: {
2110 if (!this->Visit(E->getSubExpr()))
2111 return false;
2112 if (!CheckValidLValue())
2113 return false;
2114
2115 // Now figure out the necessary offset to add to the base LV to get from
2116 // the derived class to the base class.
2117 QualType Type = E->getSubExpr()->getType();
2118
2119 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2120 PathE = E->path_end(); PathI != PathE; ++PathI) {
2121 if (!HandleLValueBase(this->Info, Result, Type->getAsCXXRecordDecl(),
2122 *PathI))
2123 return false;
2124 Type = (*PathI)->getType();
2125 }
2126
2127 return true;
2128 }
2129 }
2130 }
2131};
2132}
2133
2134//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00002135// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00002136//
2137// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2138// function designators (in C), decl references to void objects (in C), and
2139// temporaries (if building with -Wno-address-of-temporary).
2140//
2141// LValue evaluation produces values comprising a base expression of one of the
2142// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00002143// - Declarations
2144// * VarDecl
2145// * FunctionDecl
2146// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00002147// * CompoundLiteralExpr in C
2148// * StringLiteral
2149// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00002150// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00002151// * ObjCEncodeExpr
2152// * AddrLabelExpr
2153// * BlockExpr
2154// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00002155// - Locals and temporaries
2156// * Any Expr, with a Frame indicating the function in which the temporary was
2157// evaluated.
2158// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00002159//===----------------------------------------------------------------------===//
2160namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002161class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00002162 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00002163public:
Richard Smith027bf112011-11-17 22:56:20 +00002164 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2165 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00002166
Richard Smith11562c52011-10-28 17:51:58 +00002167 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2168
Peter Collingbournee9200682011-05-13 03:29:01 +00002169 bool VisitDeclRefExpr(const DeclRefExpr *E);
2170 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002171 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002172 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2173 bool VisitMemberExpr(const MemberExpr *E);
2174 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2175 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
2176 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2177 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002178
Peter Collingbournee9200682011-05-13 03:29:01 +00002179 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00002180 switch (E->getCastKind()) {
2181 default:
Richard Smith027bf112011-11-17 22:56:20 +00002182 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002183
Eli Friedmance3e02a2011-10-11 00:13:24 +00002184 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002185 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00002186 if (!Visit(E->getSubExpr()))
2187 return false;
2188 Result.Designator.setInvalid();
2189 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00002190
Richard Smith027bf112011-11-17 22:56:20 +00002191 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00002192 if (!Visit(E->getSubExpr()))
2193 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002194 if (!CheckValidLValue())
2195 return false;
2196 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00002197 }
2198 }
Sebastian Redl12757ab2011-09-24 17:48:14 +00002199
Eli Friedman449fe542009-03-23 04:56:01 +00002200 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +00002201
Eli Friedman9a156e52008-11-12 09:44:48 +00002202};
2203} // end anonymous namespace
2204
Richard Smith11562c52011-10-28 17:51:58 +00002205/// Evaluate an expression as an lvalue. This can be legitimately called on
2206/// expressions which are not glvalues, in a few cases:
2207/// * function designators in C,
2208/// * "extern void" objects,
2209/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +00002210static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002211 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2212 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2213 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +00002214 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002215}
2216
Peter Collingbournee9200682011-05-13 03:29:01 +00002217bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002218 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2219 return Success(FD);
2220 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00002221 return VisitVarDecl(E, VD);
2222 return Error(E);
2223}
Richard Smith733237d2011-10-24 23:14:33 +00002224
Richard Smith11562c52011-10-28 17:51:58 +00002225bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +00002226 if (!VD->getType()->isReferenceType()) {
2227 if (isa<ParmVarDecl>(VD)) {
Richard Smithce40ad62011-11-12 22:28:03 +00002228 Result.set(VD, Info.CurrentCall);
Richard Smithfec09922011-11-01 16:57:24 +00002229 return true;
2230 }
Richard Smithce40ad62011-11-12 22:28:03 +00002231 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00002232 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00002233
Richard Smith0b0a0b62011-10-29 20:57:55 +00002234 CCValue V;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002235 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2236 return false;
2237 return Success(V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00002238}
2239
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002240bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2241 const MaterializeTemporaryExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002242 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002243 if (E->getType()->isRecordType())
Richard Smith027bf112011-11-17 22:56:20 +00002244 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2245
2246 Result.set(E, Info.CurrentCall);
2247 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2248 Result, E->GetTemporaryExpr());
2249 }
2250
2251 // Materialization of an lvalue temporary occurs when we need to force a copy
2252 // (for instance, if it's a bitfield).
2253 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2254 if (!Visit(E->GetTemporaryExpr()))
2255 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002256 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002257 Info.CurrentCall->Temporaries[E]))
2258 return false;
Richard Smithce40ad62011-11-12 22:28:03 +00002259 Result.set(E, Info.CurrentCall);
Richard Smith027bf112011-11-17 22:56:20 +00002260 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002261}
2262
Peter Collingbournee9200682011-05-13 03:29:01 +00002263bool
2264LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002265 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2266 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2267 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00002268 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002269}
2270
Peter Collingbournee9200682011-05-13 03:29:01 +00002271bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002272 // Handle static data members.
2273 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2274 VisitIgnoredValue(E->getBase());
2275 return VisitVarDecl(E, VD);
2276 }
2277
Richard Smith254a73d2011-10-28 22:34:42 +00002278 // Handle static member functions.
2279 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2280 if (MD->isStatic()) {
2281 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00002282 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00002283 }
2284 }
2285
Richard Smithd62306a2011-11-10 06:34:14 +00002286 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00002287 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002288}
2289
Peter Collingbournee9200682011-05-13 03:29:01 +00002290bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002291 // FIXME: Deal with vectors as array subscript bases.
2292 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002293 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002294
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002295 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00002296 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002297
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002298 APSInt Index;
2299 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00002300 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002301 int64_t IndexValue
2302 = Index.isSigned() ? Index.getSExtValue()
2303 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002304
Richard Smith027bf112011-11-17 22:56:20 +00002305 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smithd62306a2011-11-10 06:34:14 +00002306 return HandleLValueArrayAdjustment(Info, Result, E->getType(), IndexValue);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002307}
Eli Friedman9a156e52008-11-12 09:44:48 +00002308
Peter Collingbournee9200682011-05-13 03:29:01 +00002309bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002310 // FIXME: In C++11, require the result to be a valid lvalue.
John McCall45d55e42010-05-07 21:00:08 +00002311 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00002312}
2313
Eli Friedman9a156e52008-11-12 09:44:48 +00002314//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00002315// Pointer Evaluation
2316//===----------------------------------------------------------------------===//
2317
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002318namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002319class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002320 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00002321 LValue &Result;
2322
Peter Collingbournee9200682011-05-13 03:29:01 +00002323 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002324 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00002325 return true;
2326 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002327public:
Mike Stump11289f42009-09-09 15:08:12 +00002328
John McCall45d55e42010-05-07 21:00:08 +00002329 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002330 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00002331
Richard Smith0b0a0b62011-10-29 20:57:55 +00002332 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002333 Result.setFrom(V);
2334 return true;
2335 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002336 bool ValueInitialization(const Expr *E) {
2337 return Success((Expr*)0);
2338 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002339
John McCall45d55e42010-05-07 21:00:08 +00002340 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002341 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00002342 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002343 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00002344 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002345 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00002346 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002347 bool VisitCallExpr(const CallExpr *E);
2348 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00002349 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00002350 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002351 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00002352 }
Richard Smithd62306a2011-11-10 06:34:14 +00002353 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2354 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002355 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002356 Result = *Info.CurrentCall->This;
2357 return true;
2358 }
John McCallc07a0c72011-02-17 10:25:35 +00002359
Eli Friedman449fe542009-03-23 04:56:01 +00002360 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002361};
Chris Lattner05706e882008-07-11 18:11:29 +00002362} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002363
John McCall45d55e42010-05-07 21:00:08 +00002364static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002365 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00002366 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00002367}
2368
John McCall45d55e42010-05-07 21:00:08 +00002369bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002370 if (E->getOpcode() != BO_Add &&
2371 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00002372 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00002373
Chris Lattner05706e882008-07-11 18:11:29 +00002374 const Expr *PExp = E->getLHS();
2375 const Expr *IExp = E->getRHS();
2376 if (IExp->getType()->isPointerType())
2377 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00002378
John McCall45d55e42010-05-07 21:00:08 +00002379 if (!EvaluatePointer(PExp, Result, Info))
2380 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002381
John McCall45d55e42010-05-07 21:00:08 +00002382 llvm::APSInt Offset;
2383 if (!EvaluateInteger(IExp, Offset, Info))
2384 return false;
2385 int64_t AdditionalOffset
2386 = Offset.isSigned() ? Offset.getSExtValue()
2387 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00002388 if (E->getOpcode() == BO_Sub)
2389 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00002390
Richard Smithd62306a2011-11-10 06:34:14 +00002391 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smith027bf112011-11-17 22:56:20 +00002392 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smithd62306a2011-11-10 06:34:14 +00002393 return HandleLValueArrayAdjustment(Info, Result, Pointee, AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00002394}
Eli Friedman9a156e52008-11-12 09:44:48 +00002395
John McCall45d55e42010-05-07 21:00:08 +00002396bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2397 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002398}
Mike Stump11289f42009-09-09 15:08:12 +00002399
Peter Collingbournee9200682011-05-13 03:29:01 +00002400bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2401 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00002402
Eli Friedman847a2bc2009-12-27 05:43:15 +00002403 switch (E->getCastKind()) {
2404 default:
2405 break;
2406
John McCalle3027922010-08-25 11:45:40 +00002407 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00002408 case CK_CPointerToObjCPointerCast:
2409 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00002410 case CK_AnyPointerToBlockPointerCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002411 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2412 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2413 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00002414 if (!E->getType()->isVoidPointerType()) {
2415 if (SubExpr->getType()->isVoidPointerType())
2416 CCEDiag(E, diag::note_constexpr_invalid_cast)
2417 << 3 << SubExpr->getType();
2418 else
2419 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2420 }
Richard Smith96e0c102011-11-04 02:25:55 +00002421 if (!Visit(SubExpr))
2422 return false;
2423 Result.Designator.setInvalid();
2424 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00002425
Anders Carlsson18275092010-10-31 20:41:46 +00002426 case CK_DerivedToBase:
2427 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002428 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00002429 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002430 if (!Result.Base && Result.Offset.isZero())
2431 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00002432
Richard Smithd62306a2011-11-10 06:34:14 +00002433 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00002434 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00002435 QualType Type =
2436 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00002437
Richard Smithd62306a2011-11-10 06:34:14 +00002438 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00002439 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithd62306a2011-11-10 06:34:14 +00002440 if (!HandleLValueBase(Info, Result, Type->getAsCXXRecordDecl(), *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00002441 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002442 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00002443 }
2444
Anders Carlsson18275092010-10-31 20:41:46 +00002445 return true;
2446 }
2447
Richard Smith027bf112011-11-17 22:56:20 +00002448 case CK_BaseToDerived:
2449 if (!Visit(E->getSubExpr()))
2450 return false;
2451 if (!Result.Base && Result.Offset.isZero())
2452 return true;
2453 return HandleBaseToDerivedCast(Info, E, Result);
2454
Richard Smith0b0a0b62011-10-29 20:57:55 +00002455 case CK_NullToPointer:
2456 return ValueInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00002457
John McCalle3027922010-08-25 11:45:40 +00002458 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00002459 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2460
Richard Smith0b0a0b62011-10-29 20:57:55 +00002461 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00002462 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00002463 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00002464
John McCall45d55e42010-05-07 21:00:08 +00002465 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002466 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2467 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00002468 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002469 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithfec09922011-11-01 16:57:24 +00002470 Result.Frame = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00002471 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00002472 return true;
2473 } else {
2474 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002475 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00002476 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00002477 }
2478 }
John McCalle3027922010-08-25 11:45:40 +00002479 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00002480 if (SubExpr->isGLValue()) {
2481 if (!EvaluateLValue(SubExpr, Result, Info))
2482 return false;
2483 } else {
2484 Result.set(SubExpr, Info.CurrentCall);
2485 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2486 Info, Result, SubExpr))
2487 return false;
2488 }
Richard Smith96e0c102011-11-04 02:25:55 +00002489 // The result is a pointer to the first element of the array.
2490 Result.Designator.addIndex(0);
2491 return true;
Richard Smithdd785442011-10-31 20:57:44 +00002492
John McCalle3027922010-08-25 11:45:40 +00002493 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00002494 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002495 }
2496
Richard Smith11562c52011-10-28 17:51:58 +00002497 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00002498}
Chris Lattner05706e882008-07-11 18:11:29 +00002499
Peter Collingbournee9200682011-05-13 03:29:01 +00002500bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00002501 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00002502 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00002503
Peter Collingbournee9200682011-05-13 03:29:01 +00002504 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002505}
Chris Lattner05706e882008-07-11 18:11:29 +00002506
2507//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002508// Member Pointer Evaluation
2509//===----------------------------------------------------------------------===//
2510
2511namespace {
2512class MemberPointerExprEvaluator
2513 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2514 MemberPtr &Result;
2515
2516 bool Success(const ValueDecl *D) {
2517 Result = MemberPtr(D);
2518 return true;
2519 }
2520public:
2521
2522 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2523 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2524
2525 bool Success(const CCValue &V, const Expr *E) {
2526 Result.setFrom(V);
2527 return true;
2528 }
Richard Smith027bf112011-11-17 22:56:20 +00002529 bool ValueInitialization(const Expr *E) {
2530 return Success((const ValueDecl*)0);
2531 }
2532
2533 bool VisitCastExpr(const CastExpr *E);
2534 bool VisitUnaryAddrOf(const UnaryOperator *E);
2535};
2536} // end anonymous namespace
2537
2538static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2539 EvalInfo &Info) {
2540 assert(E->isRValue() && E->getType()->isMemberPointerType());
2541 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2542}
2543
2544bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2545 switch (E->getCastKind()) {
2546 default:
2547 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2548
2549 case CK_NullToMemberPointer:
2550 return ValueInitialization(E);
2551
2552 case CK_BaseToDerivedMemberPointer: {
2553 if (!Visit(E->getSubExpr()))
2554 return false;
2555 if (E->path_empty())
2556 return true;
2557 // Base-to-derived member pointer casts store the path in derived-to-base
2558 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2559 // the wrong end of the derived->base arc, so stagger the path by one class.
2560 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2561 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2562 PathI != PathE; ++PathI) {
2563 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2564 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2565 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002566 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002567 }
2568 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2569 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002570 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002571 return true;
2572 }
2573
2574 case CK_DerivedToBaseMemberPointer:
2575 if (!Visit(E->getSubExpr()))
2576 return false;
2577 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2578 PathE = E->path_end(); PathI != PathE; ++PathI) {
2579 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2580 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2581 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002582 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002583 }
2584 return true;
2585 }
2586}
2587
2588bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2589 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
2590 // member can be formed.
2591 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
2592}
2593
2594//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00002595// Record Evaluation
2596//===----------------------------------------------------------------------===//
2597
2598namespace {
2599 class RecordExprEvaluator
2600 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
2601 const LValue &This;
2602 APValue &Result;
2603 public:
2604
2605 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
2606 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
2607
2608 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002609 return CheckConstantExpression(Info, E, V, Result);
Richard Smithd62306a2011-11-10 06:34:14 +00002610 }
Richard Smithd62306a2011-11-10 06:34:14 +00002611
Richard Smithe97cbd72011-11-11 04:05:33 +00002612 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00002613 bool VisitInitListExpr(const InitListExpr *E);
2614 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
2615 };
2616}
2617
Richard Smithe97cbd72011-11-11 04:05:33 +00002618bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
2619 switch (E->getCastKind()) {
2620 default:
2621 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2622
2623 case CK_ConstructorConversion:
2624 return Visit(E->getSubExpr());
2625
2626 case CK_DerivedToBase:
2627 case CK_UncheckedDerivedToBase: {
2628 CCValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002629 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00002630 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002631 if (!DerivedObject.isStruct())
2632 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00002633
2634 // Derived-to-base rvalue conversion: just slice off the derived part.
2635 APValue *Value = &DerivedObject;
2636 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
2637 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2638 PathE = E->path_end(); PathI != PathE; ++PathI) {
2639 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
2640 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2641 Value = &Value->getStructBase(getBaseIndex(RD, Base));
2642 RD = Base;
2643 }
2644 Result = *Value;
2645 return true;
2646 }
2647 }
2648}
2649
Richard Smithd62306a2011-11-10 06:34:14 +00002650bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2651 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2652 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2653
2654 if (RD->isUnion()) {
2655 Result = APValue(E->getInitializedFieldInUnion());
2656 if (!E->getNumInits())
2657 return true;
2658 LValue Subobject = This;
2659 HandleLValueMember(Info, Subobject, E->getInitializedFieldInUnion(),
2660 &Layout);
2661 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2662 Subobject, E->getInit(0));
2663 }
2664
2665 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
2666 "initializer list for class with base classes");
2667 Result = APValue(APValue::UninitStruct(), 0,
2668 std::distance(RD->field_begin(), RD->field_end()));
2669 unsigned ElementNo = 0;
2670 for (RecordDecl::field_iterator Field = RD->field_begin(),
2671 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
2672 // Anonymous bit-fields are not considered members of the class for
2673 // purposes of aggregate initialization.
2674 if (Field->isUnnamedBitfield())
2675 continue;
2676
2677 LValue Subobject = This;
2678 HandleLValueMember(Info, Subobject, *Field, &Layout);
2679
2680 if (ElementNo < E->getNumInits()) {
2681 if (!EvaluateConstantExpression(
2682 Result.getStructField((*Field)->getFieldIndex()),
2683 Info, Subobject, E->getInit(ElementNo++)))
2684 return false;
2685 } else {
2686 // Perform an implicit value-initialization for members beyond the end of
2687 // the initializer list.
2688 ImplicitValueInitExpr VIE(Field->getType());
2689 if (!EvaluateConstantExpression(
2690 Result.getStructField((*Field)->getFieldIndex()),
2691 Info, Subobject, &VIE))
2692 return false;
2693 }
2694 }
2695
2696 return true;
2697}
2698
2699bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
2700 const CXXConstructorDecl *FD = E->getConstructor();
2701 const FunctionDecl *Definition = 0;
2702 FD->getBody(Definition);
2703
Richard Smith357362d2011-12-13 06:39:58 +00002704 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
2705 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002706
2707 // FIXME: Elide the copy/move construction wherever we can.
2708 if (E->isElidable())
2709 if (const MaterializeTemporaryExpr *ME
2710 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
2711 return Visit(ME->GetTemporaryExpr());
2712
2713 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00002714 return HandleConstructorCall(E, This, Args,
2715 cast<CXXConstructorDecl>(Definition), Info,
2716 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00002717}
2718
2719static bool EvaluateRecord(const Expr *E, const LValue &This,
2720 APValue &Result, EvalInfo &Info) {
2721 assert(E->isRValue() && E->getType()->isRecordType() &&
2722 E->getType()->isLiteralType() &&
2723 "can't evaluate expression as a record rvalue");
2724 return RecordExprEvaluator(Info, This, Result).Visit(E);
2725}
2726
2727//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002728// Temporary Evaluation
2729//
2730// Temporaries are represented in the AST as rvalues, but generally behave like
2731// lvalues. The full-object of which the temporary is a subobject is implicitly
2732// materialized so that a reference can bind to it.
2733//===----------------------------------------------------------------------===//
2734namespace {
2735class TemporaryExprEvaluator
2736 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
2737public:
2738 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
2739 LValueExprEvaluatorBaseTy(Info, Result) {}
2740
2741 /// Visit an expression which constructs the value of this temporary.
2742 bool VisitConstructExpr(const Expr *E) {
2743 Result.set(E, Info.CurrentCall);
2744 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2745 Result, E);
2746 }
2747
2748 bool VisitCastExpr(const CastExpr *E) {
2749 switch (E->getCastKind()) {
2750 default:
2751 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
2752
2753 case CK_ConstructorConversion:
2754 return VisitConstructExpr(E->getSubExpr());
2755 }
2756 }
2757 bool VisitInitListExpr(const InitListExpr *E) {
2758 return VisitConstructExpr(E);
2759 }
2760 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
2761 return VisitConstructExpr(E);
2762 }
2763 bool VisitCallExpr(const CallExpr *E) {
2764 return VisitConstructExpr(E);
2765 }
2766};
2767} // end anonymous namespace
2768
2769/// Evaluate an expression of record type as a temporary.
2770static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002771 assert(E->isRValue() && E->getType()->isRecordType());
2772 if (!E->getType()->isLiteralType()) {
2773 if (Info.getLangOpts().CPlusPlus0x)
2774 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
2775 << E->getType();
2776 else
2777 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
2778 return false;
2779 }
Richard Smith027bf112011-11-17 22:56:20 +00002780 return TemporaryExprEvaluator(Info, Result).Visit(E);
2781}
2782
2783//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002784// Vector Evaluation
2785//===----------------------------------------------------------------------===//
2786
2787namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002788 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00002789 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
2790 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002791 public:
Mike Stump11289f42009-09-09 15:08:12 +00002792
Richard Smith2d406342011-10-22 21:10:00 +00002793 VectorExprEvaluator(EvalInfo &info, APValue &Result)
2794 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00002795
Richard Smith2d406342011-10-22 21:10:00 +00002796 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
2797 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
2798 // FIXME: remove this APValue copy.
2799 Result = APValue(V.data(), V.size());
2800 return true;
2801 }
Richard Smithed5165f2011-11-04 05:33:44 +00002802 bool Success(const CCValue &V, const Expr *E) {
2803 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00002804 Result = V;
2805 return true;
2806 }
Richard Smith2d406342011-10-22 21:10:00 +00002807 bool ValueInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002808
Richard Smith2d406342011-10-22 21:10:00 +00002809 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00002810 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00002811 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00002812 bool VisitInitListExpr(const InitListExpr *E);
2813 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00002814 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00002815 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00002816 // shufflevector, ExtVectorElementExpr
2817 // (Note that these require implementing conversions
2818 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002819 };
2820} // end anonymous namespace
2821
2822static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002823 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00002824 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002825}
2826
Richard Smith2d406342011-10-22 21:10:00 +00002827bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
2828 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00002829 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00002830
Richard Smith161f09a2011-12-06 22:44:34 +00002831 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00002832 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002833
Eli Friedmanc757de22011-03-25 00:43:55 +00002834 switch (E->getCastKind()) {
2835 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00002836 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00002837 if (SETy->isIntegerType()) {
2838 APSInt IntResult;
2839 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002840 return false;
Richard Smith2d406342011-10-22 21:10:00 +00002841 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00002842 } else if (SETy->isRealFloatingType()) {
2843 APFloat F(0.0);
2844 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002845 return false;
Richard Smith2d406342011-10-22 21:10:00 +00002846 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00002847 } else {
Richard Smith2d406342011-10-22 21:10:00 +00002848 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002849 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00002850
2851 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00002852 SmallVector<APValue, 4> Elts(NElts, Val);
2853 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00002854 }
Eli Friedmanc757de22011-03-25 00:43:55 +00002855 default:
Richard Smith11562c52011-10-28 17:51:58 +00002856 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002857 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002858}
2859
Richard Smith2d406342011-10-22 21:10:00 +00002860bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002861VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00002862 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002863 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00002864 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00002865
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002866 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002867 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002868
John McCall875679e2010-06-11 17:54:15 +00002869 // If a vector is initialized with a single element, that value
2870 // becomes every element of the vector, not just the first.
2871 // This is the behavior described in the IBM AltiVec documentation.
2872 if (NumInits == 1) {
Richard Smith2d406342011-10-22 21:10:00 +00002873
2874 // Handle the case where the vector is initialized by another
Tanya Lattner5ac257d2011-04-15 22:42:59 +00002875 // vector (OpenCL 6.1.6).
2876 if (E->getInit(0)->getType()->isVectorType())
Richard Smith2d406342011-10-22 21:10:00 +00002877 return Visit(E->getInit(0));
2878
John McCall875679e2010-06-11 17:54:15 +00002879 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002880 if (EltTy->isIntegerType()) {
2881 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +00002882 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002883 return false;
John McCall875679e2010-06-11 17:54:15 +00002884 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002885 } else {
2886 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +00002887 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002888 return false;
John McCall875679e2010-06-11 17:54:15 +00002889 InitValue = APValue(f);
2890 }
2891 for (unsigned i = 0; i < NumElements; i++) {
2892 Elements.push_back(InitValue);
2893 }
2894 } else {
2895 for (unsigned i = 0; i < NumElements; i++) {
2896 if (EltTy->isIntegerType()) {
2897 llvm::APSInt sInt(32);
2898 if (i < NumInits) {
2899 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002900 return false;
John McCall875679e2010-06-11 17:54:15 +00002901 } else {
2902 sInt = Info.Ctx.MakeIntValue(0, EltTy);
2903 }
2904 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +00002905 } else {
John McCall875679e2010-06-11 17:54:15 +00002906 llvm::APFloat f(0.0);
2907 if (i < NumInits) {
2908 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002909 return false;
John McCall875679e2010-06-11 17:54:15 +00002910 } else {
2911 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
2912 }
2913 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +00002914 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002915 }
2916 }
Richard Smith2d406342011-10-22 21:10:00 +00002917 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002918}
2919
Richard Smith2d406342011-10-22 21:10:00 +00002920bool
2921VectorExprEvaluator::ValueInitialization(const Expr *E) {
2922 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00002923 QualType EltTy = VT->getElementType();
2924 APValue ZeroElement;
2925 if (EltTy->isIntegerType())
2926 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
2927 else
2928 ZeroElement =
2929 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
2930
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002931 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00002932 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00002933}
2934
Richard Smith2d406342011-10-22 21:10:00 +00002935bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00002936 VisitIgnoredValue(E->getSubExpr());
Richard Smith2d406342011-10-22 21:10:00 +00002937 return ValueInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00002938}
2939
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002940//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00002941// Array Evaluation
2942//===----------------------------------------------------------------------===//
2943
2944namespace {
2945 class ArrayExprEvaluator
2946 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00002947 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00002948 APValue &Result;
2949 public:
2950
Richard Smithd62306a2011-11-10 06:34:14 +00002951 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
2952 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00002953
2954 bool Success(const APValue &V, const Expr *E) {
2955 assert(V.isArray() && "Expected array type");
2956 Result = V;
2957 return true;
2958 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002959
Richard Smithd62306a2011-11-10 06:34:14 +00002960 bool ValueInitialization(const Expr *E) {
2961 const ConstantArrayType *CAT =
2962 Info.Ctx.getAsConstantArrayType(E->getType());
2963 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002964 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002965
2966 Result = APValue(APValue::UninitArray(), 0,
2967 CAT->getSize().getZExtValue());
2968 if (!Result.hasArrayFiller()) return true;
2969
2970 // Value-initialize all elements.
2971 LValue Subobject = This;
2972 Subobject.Designator.addIndex(0);
2973 ImplicitValueInitExpr VIE(CAT->getElementType());
2974 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
2975 Subobject, &VIE);
2976 }
2977
Richard Smithf3e9e432011-11-07 09:22:26 +00002978 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00002979 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithf3e9e432011-11-07 09:22:26 +00002980 };
2981} // end anonymous namespace
2982
Richard Smithd62306a2011-11-10 06:34:14 +00002983static bool EvaluateArray(const Expr *E, const LValue &This,
2984 APValue &Result, EvalInfo &Info) {
Richard Smithf3e9e432011-11-07 09:22:26 +00002985 assert(E->isRValue() && E->getType()->isArrayType() &&
2986 E->getType()->isLiteralType() && "not a literal array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00002987 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00002988}
2989
2990bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2991 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
2992 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002993 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00002994
2995 Result = APValue(APValue::UninitArray(), E->getNumInits(),
2996 CAT->getSize().getZExtValue());
Richard Smithd62306a2011-11-10 06:34:14 +00002997 LValue Subobject = This;
2998 Subobject.Designator.addIndex(0);
2999 unsigned Index = 0;
Richard Smithf3e9e432011-11-07 09:22:26 +00003000 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smithd62306a2011-11-10 06:34:14 +00003001 I != End; ++I, ++Index) {
3002 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
3003 Info, Subobject, cast<Expr>(*I)))
Richard Smithf3e9e432011-11-07 09:22:26 +00003004 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003005 if (!HandleLValueArrayAdjustment(Info, Subobject, CAT->getElementType(), 1))
3006 return false;
3007 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003008
3009 if (!Result.hasArrayFiller()) return true;
3010 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smithd62306a2011-11-10 06:34:14 +00003011 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3012 // but sometimes does:
3013 // struct S { constexpr S() : p(&p) {} void *p; };
3014 // S s[10] = {};
Richard Smithf3e9e432011-11-07 09:22:26 +00003015 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smithd62306a2011-11-10 06:34:14 +00003016 Subobject, E->getArrayFiller());
Richard Smithf3e9e432011-11-07 09:22:26 +00003017}
3018
Richard Smith027bf112011-11-17 22:56:20 +00003019bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3020 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3021 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003022 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003023
3024 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3025 if (!Result.hasArrayFiller())
3026 return true;
3027
3028 const CXXConstructorDecl *FD = E->getConstructor();
3029 const FunctionDecl *Definition = 0;
3030 FD->getBody(Definition);
3031
Richard Smith357362d2011-12-13 06:39:58 +00003032 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3033 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003034
3035 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3036 // but sometimes does:
3037 // struct S { constexpr S() : p(&p) {} void *p; };
3038 // S s[10];
3039 LValue Subobject = This;
3040 Subobject.Designator.addIndex(0);
3041 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003042 return HandleConstructorCall(E, Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00003043 cast<CXXConstructorDecl>(Definition),
3044 Info, Result.getArrayFiller());
3045}
3046
Richard Smithf3e9e432011-11-07 09:22:26 +00003047//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003048// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003049//
3050// As a GNU extension, we support casting pointers to sufficiently-wide integer
3051// types and back in constant folding. Integer values are thus represented
3052// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00003053//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003054
3055namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003056class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003057 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003058 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003059public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00003060 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003061 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00003062
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003063 bool Success(const llvm::APSInt &SI, const Expr *E) {
3064 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00003065 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003066 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003067 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003068 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003069 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003070 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003071 return true;
3072 }
3073
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003074 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003075 assert(E->getType()->isIntegralOrEnumerationType() &&
3076 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003077 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003078 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003079 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00003080 Result.getInt().setIsUnsigned(
3081 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003082 return true;
3083 }
3084
3085 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003086 assert(E->getType()->isIntegralOrEnumerationType() &&
3087 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003088 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003089 return true;
3090 }
3091
Ken Dyckdbc01912011-03-11 02:13:43 +00003092 bool Success(CharUnits Size, const Expr *E) {
3093 return Success(Size.getQuantity(), E);
3094 }
3095
Richard Smith0b0a0b62011-10-29 20:57:55 +00003096 bool Success(const CCValue &V, const Expr *E) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00003097 if (V.isLValue()) {
3098 Result = V;
3099 return true;
3100 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003101 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00003102 }
Mike Stump11289f42009-09-09 15:08:12 +00003103
Richard Smith4ce706a2011-10-11 21:43:33 +00003104 bool ValueInitialization(const Expr *E) { return Success(0, E); }
3105
Peter Collingbournee9200682011-05-13 03:29:01 +00003106 //===--------------------------------------------------------------------===//
3107 // Visitor Methods
3108 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003109
Chris Lattner7174bf32008-07-12 00:38:25 +00003110 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003111 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00003112 }
3113 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003114 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00003115 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003116
3117 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3118 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003119 if (CheckReferencedDecl(E, E->getDecl()))
3120 return true;
3121
3122 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003123 }
3124 bool VisitMemberExpr(const MemberExpr *E) {
3125 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00003126 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003127 return true;
3128 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003129
3130 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003131 }
3132
Peter Collingbournee9200682011-05-13 03:29:01 +00003133 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00003134 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00003135 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00003136 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00003137
Peter Collingbournee9200682011-05-13 03:29:01 +00003138 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003139 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00003140
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003141 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003142 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003143 }
Mike Stump11289f42009-09-09 15:08:12 +00003144
Richard Smith4ce706a2011-10-11 21:43:33 +00003145 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00003146 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00003147 return ValueInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003148 }
3149
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003150 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003151 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003152 }
3153
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003154 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3155 return Success(E->getValue(), E);
3156 }
3157
John Wiegley6242b6a2011-04-28 00:16:57 +00003158 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3159 return Success(E->getValue(), E);
3160 }
3161
John Wiegleyf9f65842011-04-25 06:54:41 +00003162 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3163 return Success(E->getValue(), E);
3164 }
3165
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003166 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003167 bool VisitUnaryImag(const UnaryOperator *E);
3168
Sebastian Redl5f0180d2010-09-10 20:55:47 +00003169 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003170 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00003171
Chris Lattnerf8d7f722008-07-11 21:24:13 +00003172private:
Ken Dyck160146e2010-01-27 17:10:57 +00003173 CharUnits GetAlignOfExpr(const Expr *E);
3174 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00003175 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00003176 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003177 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00003178};
Chris Lattner05706e882008-07-11 18:11:29 +00003179} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003180
Richard Smith11562c52011-10-28 17:51:58 +00003181/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3182/// produce either the integer value or a pointer.
3183///
3184/// GCC has a heinous extension which folds casts between pointer types and
3185/// pointer-sized integral types. We support this by allowing the evaluation of
3186/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3187/// Some simple arithmetic on such values is supported (they are treated much
3188/// like char*).
Richard Smithf57d8cb2011-12-09 22:58:01 +00003189static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00003190 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003191 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003192 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00003193}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003194
Richard Smithf57d8cb2011-12-09 22:58:01 +00003195static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003196 CCValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003197 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00003198 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003199 if (!Val.isInt()) {
3200 // FIXME: It would be better to produce the diagnostic for casting
3201 // a pointer to an integer.
Richard Smith92b1ce02011-12-12 09:28:41 +00003202 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003203 return false;
3204 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003205 Result = Val.getInt();
3206 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003207}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003208
Richard Smithf57d8cb2011-12-09 22:58:01 +00003209/// Check whether the given declaration can be directly converted to an integral
3210/// rvalue. If not, no diagnostic is produced; there are other things we can
3211/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003212bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00003213 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003214 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003215 // Check for signedness/width mismatches between E type and ECD value.
3216 bool SameSign = (ECD->getInitVal().isSigned()
3217 == E->getType()->isSignedIntegerOrEnumerationType());
3218 bool SameWidth = (ECD->getInitVal().getBitWidth()
3219 == Info.Ctx.getIntWidth(E->getType()));
3220 if (SameSign && SameWidth)
3221 return Success(ECD->getInitVal(), E);
3222 else {
3223 // Get rid of mismatch (otherwise Success assertions will fail)
3224 // by computing a new value matching the type of E.
3225 llvm::APSInt Val = ECD->getInitVal();
3226 if (!SameSign)
3227 Val.setIsSigned(!ECD->getInitVal().isSigned());
3228 if (!SameWidth)
3229 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3230 return Success(Val, E);
3231 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003232 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003233 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00003234}
3235
Chris Lattner86ee2862008-10-06 06:40:35 +00003236/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3237/// as GCC.
3238static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3239 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003240 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00003241 enum gcc_type_class {
3242 no_type_class = -1,
3243 void_type_class, integer_type_class, char_type_class,
3244 enumeral_type_class, boolean_type_class,
3245 pointer_type_class, reference_type_class, offset_type_class,
3246 real_type_class, complex_type_class,
3247 function_type_class, method_type_class,
3248 record_type_class, union_type_class,
3249 array_type_class, string_type_class,
3250 lang_type_class
3251 };
Mike Stump11289f42009-09-09 15:08:12 +00003252
3253 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00003254 // ideal, however it is what gcc does.
3255 if (E->getNumArgs() == 0)
3256 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00003257
Chris Lattner86ee2862008-10-06 06:40:35 +00003258 QualType ArgTy = E->getArg(0)->getType();
3259 if (ArgTy->isVoidType())
3260 return void_type_class;
3261 else if (ArgTy->isEnumeralType())
3262 return enumeral_type_class;
3263 else if (ArgTy->isBooleanType())
3264 return boolean_type_class;
3265 else if (ArgTy->isCharType())
3266 return string_type_class; // gcc doesn't appear to use char_type_class
3267 else if (ArgTy->isIntegerType())
3268 return integer_type_class;
3269 else if (ArgTy->isPointerType())
3270 return pointer_type_class;
3271 else if (ArgTy->isReferenceType())
3272 return reference_type_class;
3273 else if (ArgTy->isRealType())
3274 return real_type_class;
3275 else if (ArgTy->isComplexType())
3276 return complex_type_class;
3277 else if (ArgTy->isFunctionType())
3278 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00003279 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00003280 return record_type_class;
3281 else if (ArgTy->isUnionType())
3282 return union_type_class;
3283 else if (ArgTy->isArrayType())
3284 return array_type_class;
3285 else if (ArgTy->isUnionType())
3286 return union_type_class;
3287 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00003288 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00003289 return -1;
3290}
3291
John McCall95007602010-05-10 23:27:23 +00003292/// Retrieves the "underlying object type" of the given expression,
3293/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00003294QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3295 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3296 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00003297 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00003298 } else if (const Expr *E = B.get<const Expr*>()) {
3299 if (isa<CompoundLiteralExpr>(E))
3300 return E->getType();
John McCall95007602010-05-10 23:27:23 +00003301 }
3302
3303 return QualType();
3304}
3305
Peter Collingbournee9200682011-05-13 03:29:01 +00003306bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00003307 // TODO: Perhaps we should let LLVM lower this?
3308 LValue Base;
3309 if (!EvaluatePointer(E->getArg(0), Base, Info))
3310 return false;
3311
3312 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00003313 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00003314
Richard Smithce40ad62011-11-12 22:28:03 +00003315 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00003316 if (T.isNull() ||
3317 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00003318 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00003319 T->isVariablyModifiedType() ||
3320 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003321 return Error(E);
John McCall95007602010-05-10 23:27:23 +00003322
3323 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3324 CharUnits Offset = Base.getLValueOffset();
3325
3326 if (!Offset.isNegative() && Offset <= Size)
3327 Size -= Offset;
3328 else
3329 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00003330 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00003331}
3332
Peter Collingbournee9200682011-05-13 03:29:01 +00003333bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003334 switch (E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003335 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00003336 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003337
3338 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00003339 if (TryEvaluateBuiltinObjectSize(E))
3340 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00003341
Eric Christopher99469702010-01-19 22:58:35 +00003342 // If evaluating the argument has side-effects we can't determine
3343 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003344 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00003345 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00003346 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00003347 return Success(0, E);
3348 }
Mike Stump876387b2009-10-27 22:09:17 +00003349
Richard Smithf57d8cb2011-12-09 22:58:01 +00003350 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003351 }
3352
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003353 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003354 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00003355
Richard Smith10c7c902011-12-09 02:04:48 +00003356 case Builtin::BI__builtin_constant_p: {
3357 const Expr *Arg = E->getArg(0);
3358 QualType ArgType = Arg->getType();
3359 // __builtin_constant_p always has one operand. The rules which gcc follows
3360 // are not precisely documented, but are as follows:
3361 //
3362 // - If the operand is of integral, floating, complex or enumeration type,
3363 // and can be folded to a known value of that type, it returns 1.
3364 // - If the operand and can be folded to a pointer to the first character
3365 // of a string literal (or such a pointer cast to an integral type), it
3366 // returns 1.
3367 //
3368 // Otherwise, it returns 0.
3369 //
3370 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3371 // its support for this does not currently work.
3372 int IsConstant = 0;
3373 if (ArgType->isIntegralOrEnumerationType()) {
3374 // Note, a pointer cast to an integral type is only a constant if it is
3375 // a pointer to the first character of a string literal.
3376 Expr::EvalResult Result;
3377 if (Arg->EvaluateAsRValue(Result, Info.Ctx) && !Result.HasSideEffects) {
3378 APValue &V = Result.Val;
3379 if (V.getKind() == APValue::LValue) {
3380 if (const Expr *E = V.getLValueBase().dyn_cast<const Expr*>())
3381 IsConstant = isa<StringLiteral>(E) && V.getLValueOffset().isZero();
3382 } else {
3383 IsConstant = 1;
3384 }
3385 }
3386 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3387 IsConstant = Arg->isEvaluatable(Info.Ctx);
3388 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3389 LValue LV;
3390 // Use a separate EvalInfo: ignore constexpr parameter and 'this' bindings
3391 // during the check.
3392 Expr::EvalStatus Status;
3393 EvalInfo SubInfo(Info.Ctx, Status);
3394 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, SubInfo)
3395 : EvaluatePointer(Arg, LV, SubInfo)) &&
3396 !Status.HasSideEffects)
3397 if (const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>())
3398 IsConstant = isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3399 }
3400
3401 return Success(IsConstant, E);
3402 }
Chris Lattnerd545ad12009-09-23 06:06:36 +00003403 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00003404 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00003405 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00003406 return Success(Operand, E);
3407 }
Eli Friedmand5c93992010-02-13 00:10:10 +00003408
3409 case Builtin::BI__builtin_expect:
3410 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003411
3412 case Builtin::BIstrlen:
3413 case Builtin::BI__builtin_strlen:
3414 // As an extension, we support strlen() and __builtin_strlen() as constant
3415 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00003416 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003417 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
3418 // The string literal may have embedded null characters. Find the first
3419 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003420 StringRef Str = S->getString();
3421 StringRef::size_type Pos = Str.find(0);
3422 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003423 Str = Str.substr(0, Pos);
3424
3425 return Success(Str.size(), E);
3426 }
3427
Richard Smithf57d8cb2011-12-09 22:58:01 +00003428 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003429
3430 case Builtin::BI__atomic_is_lock_free: {
3431 APSInt SizeVal;
3432 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
3433 return false;
3434
3435 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
3436 // of two less than the maximum inline atomic width, we know it is
3437 // lock-free. If the size isn't a power of two, or greater than the
3438 // maximum alignment where we promote atomics, we know it is not lock-free
3439 // (at least not in the sense of atomic_is_lock_free). Otherwise,
3440 // the answer can only be determined at runtime; for example, 16-byte
3441 // atomics have lock-free implementations on some, but not all,
3442 // x86-64 processors.
3443
3444 // Check power-of-two.
3445 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
3446 if (!Size.isPowerOfTwo())
3447#if 0
3448 // FIXME: Suppress this folding until the ABI for the promotion width
3449 // settles.
3450 return Success(0, E);
3451#else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003452 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003453#endif
3454
3455#if 0
3456 // Check against promotion width.
3457 // FIXME: Suppress this folding until the ABI for the promotion width
3458 // settles.
3459 unsigned PromoteWidthBits =
3460 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
3461 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
3462 return Success(0, E);
3463#endif
3464
3465 // Check against inlining width.
3466 unsigned InlineWidthBits =
3467 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
3468 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
3469 return Success(1, E);
3470
Richard Smithf57d8cb2011-12-09 22:58:01 +00003471 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003472 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003473 }
Chris Lattner7174bf32008-07-12 00:38:25 +00003474}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003475
Richard Smith8b3497e2011-10-31 01:37:14 +00003476static bool HasSameBase(const LValue &A, const LValue &B) {
3477 if (!A.getLValueBase())
3478 return !B.getLValueBase();
3479 if (!B.getLValueBase())
3480 return false;
3481
Richard Smithce40ad62011-11-12 22:28:03 +00003482 if (A.getLValueBase().getOpaqueValue() !=
3483 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003484 const Decl *ADecl = GetLValueBaseDecl(A);
3485 if (!ADecl)
3486 return false;
3487 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00003488 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00003489 return false;
3490 }
3491
3492 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithfec09922011-11-01 16:57:24 +00003493 A.getLValueFrame() == B.getLValueFrame();
Richard Smith8b3497e2011-10-31 01:37:14 +00003494}
3495
Chris Lattnere13042c2008-07-11 19:10:17 +00003496bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003497 if (E->isAssignmentOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003498 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003499
John McCalle3027922010-08-25 11:45:40 +00003500 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00003501 VisitIgnoredValue(E->getLHS());
3502 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00003503 }
3504
3505 if (E->isLogicalOp()) {
3506 // These need to be handled specially because the operands aren't
3507 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003508 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00003509
Richard Smith11562c52011-10-28 17:51:58 +00003510 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00003511 // We were able to evaluate the LHS, see if we can get away with not
3512 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00003513 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003514 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003515
Richard Smith11562c52011-10-28 17:51:58 +00003516 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00003517 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003518 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003519 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003520 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003521 }
3522 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003523 // FIXME: If both evaluations fail, we should produce the diagnostic from
3524 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
3525 // less clear how to diagnose this.
Richard Smith11562c52011-10-28 17:51:58 +00003526 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00003527 // We can't evaluate the LHS; however, sometimes the result
3528 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003529 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003530 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003531 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00003532 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003533
3534 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003535 }
3536 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00003537 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00003538
Eli Friedman5a332ea2008-11-13 06:09:17 +00003539 return false;
3540 }
3541
Anders Carlssonacc79812008-11-16 07:17:21 +00003542 QualType LHSTy = E->getLHS()->getType();
3543 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003544
3545 if (LHSTy->isAnyComplexType()) {
3546 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00003547 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003548
3549 if (!EvaluateComplex(E->getLHS(), LHS, Info))
3550 return false;
3551
3552 if (!EvaluateComplex(E->getRHS(), RHS, Info))
3553 return false;
3554
3555 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00003556 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003557 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00003558 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003559 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
3560
John McCalle3027922010-08-25 11:45:40 +00003561 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003562 return Success((CR_r == APFloat::cmpEqual &&
3563 CR_i == APFloat::cmpEqual), E);
3564 else {
John McCalle3027922010-08-25 11:45:40 +00003565 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003566 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00003567 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00003568 CR_r == APFloat::cmpLessThan ||
3569 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00003570 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00003571 CR_i == APFloat::cmpLessThan ||
3572 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003573 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003574 } else {
John McCalle3027922010-08-25 11:45:40 +00003575 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003576 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
3577 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
3578 else {
John McCalle3027922010-08-25 11:45:40 +00003579 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003580 "Invalid compex comparison.");
3581 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
3582 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
3583 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003584 }
3585 }
Mike Stump11289f42009-09-09 15:08:12 +00003586
Anders Carlssonacc79812008-11-16 07:17:21 +00003587 if (LHSTy->isRealFloatingType() &&
3588 RHSTy->isRealFloatingType()) {
3589 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00003590
Anders Carlssonacc79812008-11-16 07:17:21 +00003591 if (!EvaluateFloat(E->getRHS(), RHS, Info))
3592 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003593
Anders Carlssonacc79812008-11-16 07:17:21 +00003594 if (!EvaluateFloat(E->getLHS(), LHS, Info))
3595 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003596
Anders Carlssonacc79812008-11-16 07:17:21 +00003597 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00003598
Anders Carlssonacc79812008-11-16 07:17:21 +00003599 switch (E->getOpcode()) {
3600 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003601 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00003602 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003603 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00003604 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003605 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00003606 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003607 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00003608 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00003609 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003610 E);
John McCalle3027922010-08-25 11:45:40 +00003611 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003612 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00003613 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00003614 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00003615 || CR == APFloat::cmpLessThan
3616 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00003617 }
Anders Carlssonacc79812008-11-16 07:17:21 +00003618 }
Mike Stump11289f42009-09-09 15:08:12 +00003619
Eli Friedmana38da572009-04-28 19:17:36 +00003620 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003621 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCall45d55e42010-05-07 21:00:08 +00003622 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003623 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
3624 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003625
John McCall45d55e42010-05-07 21:00:08 +00003626 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003627 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
3628 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003629
Richard Smith8b3497e2011-10-31 01:37:14 +00003630 // Reject differing bases from the normal codepath; we special-case
3631 // comparisons to null.
3632 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith83c68212011-10-31 05:11:32 +00003633 // Inequalities and subtractions between unrelated pointers have
3634 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00003635 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003636 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00003637 // A constant address may compare equal to the address of a symbol.
3638 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00003639 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00003640 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
3641 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003642 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00003643 // It's implementation-defined whether distinct literals will have
Eli Friedman42fbd622011-10-31 22:54:30 +00003644 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smithe9e20dd32011-11-04 01:10:57 +00003645 // distinct. However, we do know that the address of a literal will be
3646 // non-null.
3647 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
3648 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003649 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00003650 // We can't tell whether weak symbols will end up pointing to the same
3651 // object.
3652 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003653 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00003654 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00003655 // (Note that clang defaults to -fmerge-all-constants, which can
3656 // lead to inconsistent results for comparisons involving the address
3657 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00003658 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00003659 }
Eli Friedman64004332009-03-23 04:38:34 +00003660
Richard Smithf3e9e432011-11-07 09:22:26 +00003661 // FIXME: Implement the C++11 restrictions:
3662 // - Pointer subtractions must be on elements of the same array.
3663 // - Pointer comparisons must be between members with the same access.
3664
John McCalle3027922010-08-25 11:45:40 +00003665 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00003666 QualType Type = E->getLHS()->getType();
3667 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003668
Richard Smithd62306a2011-11-10 06:34:14 +00003669 CharUnits ElementSize;
3670 if (!HandleSizeof(Info, ElementType, ElementSize))
3671 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003672
Richard Smithd62306a2011-11-10 06:34:14 +00003673 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dyck02990832010-01-15 12:37:54 +00003674 RHSValue.getLValueOffset();
3675 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00003676 }
Richard Smith8b3497e2011-10-31 01:37:14 +00003677
3678 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
3679 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
3680 switch (E->getOpcode()) {
3681 default: llvm_unreachable("missing comparison operator");
3682 case BO_LT: return Success(LHSOffset < RHSOffset, E);
3683 case BO_GT: return Success(LHSOffset > RHSOffset, E);
3684 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
3685 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
3686 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
3687 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmana38da572009-04-28 19:17:36 +00003688 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003689 }
3690 }
Douglas Gregorb90df602010-06-16 00:17:44 +00003691 if (!LHSTy->isIntegralOrEnumerationType() ||
3692 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smith027bf112011-11-17 22:56:20 +00003693 // We can't continue from here for non-integral types.
3694 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00003695 }
3696
Anders Carlsson9c181652008-07-08 14:35:21 +00003697 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00003698 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00003699 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003700 return false;
Eli Friedmanbd840592008-07-27 05:46:18 +00003701
Richard Smith11562c52011-10-28 17:51:58 +00003702 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003703 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003704 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00003705
3706 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00003707 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00003708 CharUnits AdditionalOffset = CharUnits::fromQuantity(
3709 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00003710 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00003711 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00003712 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00003713 LHSVal.getLValueOffset() -= AdditionalOffset;
3714 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00003715 return true;
3716 }
3717
3718 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00003719 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00003720 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003721 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
3722 LHSVal.getInt().getZExtValue());
3723 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00003724 return true;
3725 }
3726
3727 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00003728 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003729 return Error(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00003730
Richard Smith11562c52011-10-28 17:51:58 +00003731 APSInt &LHS = LHSVal.getInt();
3732 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00003733
Anders Carlsson9c181652008-07-08 14:35:21 +00003734 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00003735 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003736 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003737 case BO_Mul: return Success(LHS * RHS, E);
3738 case BO_Add: return Success(LHS + RHS, E);
3739 case BO_Sub: return Success(LHS - RHS, E);
3740 case BO_And: return Success(LHS & RHS, E);
3741 case BO_Xor: return Success(LHS ^ RHS, E);
3742 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00003743 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00003744 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003745 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00003746 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00003747 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00003748 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003749 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00003750 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00003751 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00003752 // During constant-folding, a negative shift is an opposite shift.
3753 if (RHS.isSigned() && RHS.isNegative()) {
3754 RHS = -RHS;
3755 goto shift_right;
3756 }
3757
3758 shift_left:
3759 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00003760 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3761 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003762 }
John McCalle3027922010-08-25 11:45:40 +00003763 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00003764 // During constant-folding, a negative shift is an opposite shift.
3765 if (RHS.isSigned() && RHS.isNegative()) {
3766 RHS = -RHS;
3767 goto shift_left;
3768 }
3769
3770 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00003771 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00003772 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3773 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003774 }
Mike Stump11289f42009-09-09 15:08:12 +00003775
Richard Smith11562c52011-10-28 17:51:58 +00003776 case BO_LT: return Success(LHS < RHS, E);
3777 case BO_GT: return Success(LHS > RHS, E);
3778 case BO_LE: return Success(LHS <= RHS, E);
3779 case BO_GE: return Success(LHS >= RHS, E);
3780 case BO_EQ: return Success(LHS == RHS, E);
3781 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00003782 }
Anders Carlsson9c181652008-07-08 14:35:21 +00003783}
3784
Ken Dyck160146e2010-01-27 17:10:57 +00003785CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003786 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3787 // the result is the size of the referenced type."
3788 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3789 // result shall be the alignment of the referenced type."
3790 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
3791 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00003792
3793 // __alignof is defined to return the preferred alignment.
3794 return Info.Ctx.toCharUnitsFromBits(
3795 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00003796}
3797
Ken Dyck160146e2010-01-27 17:10:57 +00003798CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00003799 E = E->IgnoreParens();
3800
3801 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00003802 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00003803 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00003804 return Info.Ctx.getDeclAlign(DRE->getDecl(),
3805 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00003806
Chris Lattner68061312009-01-24 21:53:27 +00003807 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00003808 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
3809 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00003810
Chris Lattner24aeeab2009-01-24 21:09:06 +00003811 return GetAlignOfType(E->getType());
3812}
3813
3814
Peter Collingbournee190dee2011-03-11 19:24:49 +00003815/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
3816/// a result as the expression's type.
3817bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
3818 const UnaryExprOrTypeTraitExpr *E) {
3819 switch(E->getKind()) {
3820 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00003821 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00003822 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00003823 else
Ken Dyckdbc01912011-03-11 02:13:43 +00003824 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00003825 }
Eli Friedman64004332009-03-23 04:38:34 +00003826
Peter Collingbournee190dee2011-03-11 19:24:49 +00003827 case UETT_VecStep: {
3828 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00003829
Peter Collingbournee190dee2011-03-11 19:24:49 +00003830 if (Ty->isVectorType()) {
3831 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00003832
Peter Collingbournee190dee2011-03-11 19:24:49 +00003833 // The vec_step built-in functions that take a 3-component
3834 // vector return 4. (OpenCL 1.1 spec 6.11.12)
3835 if (n == 3)
3836 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00003837
Peter Collingbournee190dee2011-03-11 19:24:49 +00003838 return Success(n, E);
3839 } else
3840 return Success(1, E);
3841 }
3842
3843 case UETT_SizeOf: {
3844 QualType SrcTy = E->getTypeOfArgument();
3845 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3846 // the result is the size of the referenced type."
3847 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3848 // result shall be the alignment of the referenced type."
3849 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
3850 SrcTy = Ref->getPointeeType();
3851
Richard Smithd62306a2011-11-10 06:34:14 +00003852 CharUnits Sizeof;
3853 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00003854 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003855 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003856 }
3857 }
3858
3859 llvm_unreachable("unknown expr/type trait");
Richard Smithf57d8cb2011-12-09 22:58:01 +00003860 return Error(E);
Chris Lattnerf8d7f722008-07-11 21:24:13 +00003861}
3862
Peter Collingbournee9200682011-05-13 03:29:01 +00003863bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00003864 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00003865 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00003866 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003867 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00003868 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00003869 for (unsigned i = 0; i != n; ++i) {
3870 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
3871 switch (ON.getKind()) {
3872 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00003873 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00003874 APSInt IdxResult;
3875 if (!EvaluateInteger(Idx, IdxResult, Info))
3876 return false;
3877 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
3878 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003879 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00003880 CurrentType = AT->getElementType();
3881 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
3882 Result += IdxResult.getSExtValue() * ElementSize;
3883 break;
3884 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00003885
Douglas Gregor882211c2010-04-28 22:16:22 +00003886 case OffsetOfExpr::OffsetOfNode::Field: {
3887 FieldDecl *MemberDecl = ON.getField();
3888 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003889 if (!RT)
3890 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00003891 RecordDecl *RD = RT->getDecl();
3892 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00003893 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00003894 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00003895 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00003896 CurrentType = MemberDecl->getType().getNonReferenceType();
3897 break;
3898 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00003899
Douglas Gregor882211c2010-04-28 22:16:22 +00003900 case OffsetOfExpr::OffsetOfNode::Identifier:
3901 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00003902 return Error(OOE);
3903
Douglas Gregord1702062010-04-29 00:18:15 +00003904 case OffsetOfExpr::OffsetOfNode::Base: {
3905 CXXBaseSpecifier *BaseSpec = ON.getBase();
3906 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003907 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00003908
3909 // Find the layout of the class whose base we are looking into.
3910 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003911 if (!RT)
3912 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00003913 RecordDecl *RD = RT->getDecl();
3914 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
3915
3916 // Find the base class itself.
3917 CurrentType = BaseSpec->getType();
3918 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
3919 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003920 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00003921
3922 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00003923 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00003924 break;
3925 }
Douglas Gregor882211c2010-04-28 22:16:22 +00003926 }
3927 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003928 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00003929}
3930
Chris Lattnere13042c2008-07-11 19:10:17 +00003931bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003932 switch (E->getOpcode()) {
3933 default:
3934 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
3935 // See C99 6.6p3.
3936 return Error(E);
3937 case UO_Extension:
3938 // FIXME: Should extension allow i-c-e extension expressions in its scope?
3939 // If so, we could clear the diagnostic ID.
3940 return Visit(E->getSubExpr());
3941 case UO_Plus:
3942 // The result is just the value.
3943 return Visit(E->getSubExpr());
3944 case UO_Minus: {
3945 if (!Visit(E->getSubExpr()))
3946 return false;
3947 if (!Result.isInt()) return Error(E);
3948 return Success(-Result.getInt(), E);
3949 }
3950 case UO_Not: {
3951 if (!Visit(E->getSubExpr()))
3952 return false;
3953 if (!Result.isInt()) return Error(E);
3954 return Success(~Result.getInt(), E);
3955 }
3956 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00003957 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00003958 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00003959 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003960 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00003961 }
Anders Carlsson9c181652008-07-08 14:35:21 +00003962 }
Anders Carlsson9c181652008-07-08 14:35:21 +00003963}
Mike Stump11289f42009-09-09 15:08:12 +00003964
Chris Lattner477c4be2008-07-12 01:15:53 +00003965/// HandleCast - This is used to evaluate implicit or explicit casts where the
3966/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00003967bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
3968 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00003969 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00003970 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00003971
Eli Friedmanc757de22011-03-25 00:43:55 +00003972 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00003973 case CK_BaseToDerived:
3974 case CK_DerivedToBase:
3975 case CK_UncheckedDerivedToBase:
3976 case CK_Dynamic:
3977 case CK_ToUnion:
3978 case CK_ArrayToPointerDecay:
3979 case CK_FunctionToPointerDecay:
3980 case CK_NullToPointer:
3981 case CK_NullToMemberPointer:
3982 case CK_BaseToDerivedMemberPointer:
3983 case CK_DerivedToBaseMemberPointer:
3984 case CK_ConstructorConversion:
3985 case CK_IntegralToPointer:
3986 case CK_ToVoid:
3987 case CK_VectorSplat:
3988 case CK_IntegralToFloating:
3989 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00003990 case CK_CPointerToObjCPointerCast:
3991 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00003992 case CK_AnyPointerToBlockPointerCast:
3993 case CK_ObjCObjectLValueCast:
3994 case CK_FloatingRealToComplex:
3995 case CK_FloatingComplexToReal:
3996 case CK_FloatingComplexCast:
3997 case CK_FloatingComplexToIntegralComplex:
3998 case CK_IntegralRealToComplex:
3999 case CK_IntegralComplexCast:
4000 case CK_IntegralComplexToFloatingComplex:
4001 llvm_unreachable("invalid cast kind for integral value");
4002
Eli Friedman9faf2f92011-03-25 19:07:11 +00004003 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00004004 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004005 case CK_LValueBitCast:
4006 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00004007 case CK_ARCProduceObject:
4008 case CK_ARCConsumeObject:
4009 case CK_ARCReclaimReturnedObject:
4010 case CK_ARCExtendBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004011 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004012
4013 case CK_LValueToRValue:
4014 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004015 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004016
4017 case CK_MemberPointerToBoolean:
4018 case CK_PointerToBoolean:
4019 case CK_IntegralToBoolean:
4020 case CK_FloatingToBoolean:
4021 case CK_FloatingComplexToBoolean:
4022 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004023 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00004024 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00004025 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004026 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004027 }
4028
Eli Friedmanc757de22011-03-25 00:43:55 +00004029 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00004030 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00004031 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00004032
Eli Friedman742421e2009-02-20 01:15:07 +00004033 if (!Result.isInt()) {
4034 // Only allow casts of lvalues if they are lossless.
4035 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
4036 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004037
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004038 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004039 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00004040 }
Mike Stump11289f42009-09-09 15:08:12 +00004041
Eli Friedmanc757de22011-03-25 00:43:55 +00004042 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004043 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4044
John McCall45d55e42010-05-07 21:00:08 +00004045 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00004046 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00004047 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00004048
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004049 if (LV.getLValueBase()) {
4050 // Only allow based lvalue casts if they are lossless.
4051 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004052 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004053
Richard Smithcf74da72011-11-16 07:18:12 +00004054 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004055 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004056 return true;
4057 }
4058
Ken Dyck02990832010-01-15 12:37:54 +00004059 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
4060 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004061 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004062 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004063
Eli Friedmanc757de22011-03-25 00:43:55 +00004064 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00004065 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00004066 if (!EvaluateComplex(SubExpr, C, Info))
4067 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00004068 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00004069 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00004070
Eli Friedmanc757de22011-03-25 00:43:55 +00004071 case CK_FloatingToIntegral: {
4072 APFloat F(0.0);
4073 if (!EvaluateFloat(SubExpr, F, Info))
4074 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00004075
Richard Smith357362d2011-12-13 06:39:58 +00004076 APSInt Value;
4077 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
4078 return false;
4079 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004080 }
4081 }
Mike Stump11289f42009-09-09 15:08:12 +00004082
Eli Friedmanc757de22011-03-25 00:43:55 +00004083 llvm_unreachable("unknown cast resulting in integral value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004084 return Error(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00004085}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004086
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004087bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4088 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00004089 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004090 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4091 return false;
4092 if (!LV.isComplexInt())
4093 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004094 return Success(LV.getComplexIntReal(), E);
4095 }
4096
4097 return Visit(E->getSubExpr());
4098}
4099
Eli Friedman4e7a2412009-02-27 04:45:43 +00004100bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004101 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00004102 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004103 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4104 return false;
4105 if (!LV.isComplexInt())
4106 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004107 return Success(LV.getComplexIntImag(), E);
4108 }
4109
Richard Smith4a678122011-10-24 18:44:57 +00004110 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00004111 return Success(0, E);
4112}
4113
Douglas Gregor820ba7b2011-01-04 17:33:58 +00004114bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4115 return Success(E->getPackLength(), E);
4116}
4117
Sebastian Redl5f0180d2010-09-10 20:55:47 +00004118bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4119 return Success(E->getValue(), E);
4120}
4121
Chris Lattner05706e882008-07-11 18:11:29 +00004122//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00004123// Float Evaluation
4124//===----------------------------------------------------------------------===//
4125
4126namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004127class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004128 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00004129 APFloat &Result;
4130public:
4131 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004132 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00004133
Richard Smith0b0a0b62011-10-29 20:57:55 +00004134 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004135 Result = V.getFloat();
4136 return true;
4137 }
Eli Friedman24c01542008-08-22 00:06:13 +00004138
Richard Smith4ce706a2011-10-11 21:43:33 +00004139 bool ValueInitialization(const Expr *E) {
4140 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4141 return true;
4142 }
4143
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004144 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00004145
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004146 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00004147 bool VisitBinaryOperator(const BinaryOperator *E);
4148 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004149 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00004150
John McCallb1fb0d32010-05-07 22:08:54 +00004151 bool VisitUnaryReal(const UnaryOperator *E);
4152 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00004153
John McCallb1fb0d32010-05-07 22:08:54 +00004154 // FIXME: Missing: array subscript of vector, member of vector,
4155 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00004156};
4157} // end anonymous namespace
4158
4159static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004160 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004161 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00004162}
4163
Jay Foad39c79802011-01-12 09:06:06 +00004164static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00004165 QualType ResultTy,
4166 const Expr *Arg,
4167 bool SNaN,
4168 llvm::APFloat &Result) {
4169 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4170 if (!S) return false;
4171
4172 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4173
4174 llvm::APInt fill;
4175
4176 // Treat empty strings as if they were zero.
4177 if (S->getString().empty())
4178 fill = llvm::APInt(32, 0);
4179 else if (S->getString().getAsInteger(0, fill))
4180 return false;
4181
4182 if (SNaN)
4183 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
4184 else
4185 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
4186 return true;
4187}
4188
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004189bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004190 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004191 default:
4192 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4193
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004194 case Builtin::BI__builtin_huge_val:
4195 case Builtin::BI__builtin_huge_valf:
4196 case Builtin::BI__builtin_huge_vall:
4197 case Builtin::BI__builtin_inf:
4198 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00004199 case Builtin::BI__builtin_infl: {
4200 const llvm::fltSemantics &Sem =
4201 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00004202 Result = llvm::APFloat::getInf(Sem);
4203 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00004204 }
Mike Stump11289f42009-09-09 15:08:12 +00004205
John McCall16291492010-02-28 13:00:19 +00004206 case Builtin::BI__builtin_nans:
4207 case Builtin::BI__builtin_nansf:
4208 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004209 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4210 true, Result))
4211 return Error(E);
4212 return true;
John McCall16291492010-02-28 13:00:19 +00004213
Chris Lattner0b7282e2008-10-06 06:31:58 +00004214 case Builtin::BI__builtin_nan:
4215 case Builtin::BI__builtin_nanf:
4216 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00004217 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00004218 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004219 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4220 false, Result))
4221 return Error(E);
4222 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004223
4224 case Builtin::BI__builtin_fabs:
4225 case Builtin::BI__builtin_fabsf:
4226 case Builtin::BI__builtin_fabsl:
4227 if (!EvaluateFloat(E->getArg(0), Result, Info))
4228 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004229
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004230 if (Result.isNegative())
4231 Result.changeSign();
4232 return true;
4233
Mike Stump11289f42009-09-09 15:08:12 +00004234 case Builtin::BI__builtin_copysign:
4235 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004236 case Builtin::BI__builtin_copysignl: {
4237 APFloat RHS(0.);
4238 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4239 !EvaluateFloat(E->getArg(1), RHS, Info))
4240 return false;
4241 Result.copySign(RHS);
4242 return true;
4243 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004244 }
4245}
4246
John McCallb1fb0d32010-05-07 22:08:54 +00004247bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004248 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4249 ComplexValue CV;
4250 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4251 return false;
4252 Result = CV.FloatReal;
4253 return true;
4254 }
4255
4256 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00004257}
4258
4259bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004260 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4261 ComplexValue CV;
4262 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4263 return false;
4264 Result = CV.FloatImag;
4265 return true;
4266 }
4267
Richard Smith4a678122011-10-24 18:44:57 +00004268 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00004269 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4270 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00004271 return true;
4272}
4273
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004274bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004275 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004276 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004277 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00004278 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00004279 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00004280 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
4281 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004282 Result.changeSign();
4283 return true;
4284 }
4285}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004286
Eli Friedman24c01542008-08-22 00:06:13 +00004287bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004288 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
4289 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00004290
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004291 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00004292 if (!EvaluateFloat(E->getLHS(), Result, Info))
4293 return false;
4294 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4295 return false;
4296
4297 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004298 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004299 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00004300 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
4301 return true;
John McCalle3027922010-08-25 11:45:40 +00004302 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00004303 Result.add(RHS, APFloat::rmNearestTiesToEven);
4304 return true;
John McCalle3027922010-08-25 11:45:40 +00004305 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00004306 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
4307 return true;
John McCalle3027922010-08-25 11:45:40 +00004308 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00004309 Result.divide(RHS, APFloat::rmNearestTiesToEven);
4310 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00004311 }
4312}
4313
4314bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
4315 Result = E->getValue();
4316 return true;
4317}
4318
Peter Collingbournee9200682011-05-13 03:29:01 +00004319bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4320 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00004321
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004322 switch (E->getCastKind()) {
4323 default:
Richard Smith11562c52011-10-28 17:51:58 +00004324 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004325
4326 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004327 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00004328 return EvaluateInteger(SubExpr, IntResult, Info) &&
4329 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
4330 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00004331 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004332
4333 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004334 if (!Visit(SubExpr))
4335 return false;
Richard Smith357362d2011-12-13 06:39:58 +00004336 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
4337 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00004338 }
John McCalld7646252010-11-14 08:17:51 +00004339
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004340 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00004341 ComplexValue V;
4342 if (!EvaluateComplex(SubExpr, V, Info))
4343 return false;
4344 Result = V.getComplexFloatReal();
4345 return true;
4346 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004347 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004348
Richard Smithf57d8cb2011-12-09 22:58:01 +00004349 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004350}
4351
Eli Friedman24c01542008-08-22 00:06:13 +00004352//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004353// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00004354//===----------------------------------------------------------------------===//
4355
4356namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004357class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004358 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00004359 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00004360
Anders Carlsson537969c2008-11-16 20:27:53 +00004361public:
John McCall93d91dc2010-05-07 17:22:02 +00004362 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004363 : ExprEvaluatorBaseTy(info), Result(Result) {}
4364
Richard Smith0b0a0b62011-10-29 20:57:55 +00004365 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004366 Result.setFrom(V);
4367 return true;
4368 }
Mike Stump11289f42009-09-09 15:08:12 +00004369
Anders Carlsson537969c2008-11-16 20:27:53 +00004370 //===--------------------------------------------------------------------===//
4371 // Visitor Methods
4372 //===--------------------------------------------------------------------===//
4373
Peter Collingbournee9200682011-05-13 03:29:01 +00004374 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00004375
Peter Collingbournee9200682011-05-13 03:29:01 +00004376 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00004377
John McCall93d91dc2010-05-07 17:22:02 +00004378 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004379 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00004380 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00004381};
4382} // end anonymous namespace
4383
John McCall93d91dc2010-05-07 17:22:02 +00004384static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
4385 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004386 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004387 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00004388}
4389
Peter Collingbournee9200682011-05-13 03:29:01 +00004390bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
4391 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004392
4393 if (SubExpr->getType()->isRealFloatingType()) {
4394 Result.makeComplexFloat();
4395 APFloat &Imag = Result.FloatImag;
4396 if (!EvaluateFloat(SubExpr, Imag, Info))
4397 return false;
4398
4399 Result.FloatReal = APFloat(Imag.getSemantics());
4400 return true;
4401 } else {
4402 assert(SubExpr->getType()->isIntegerType() &&
4403 "Unexpected imaginary literal.");
4404
4405 Result.makeComplexInt();
4406 APSInt &Imag = Result.IntImag;
4407 if (!EvaluateInteger(SubExpr, Imag, Info))
4408 return false;
4409
4410 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
4411 return true;
4412 }
4413}
4414
Peter Collingbournee9200682011-05-13 03:29:01 +00004415bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004416
John McCallfcef3cf2010-12-14 17:51:41 +00004417 switch (E->getCastKind()) {
4418 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004419 case CK_BaseToDerived:
4420 case CK_DerivedToBase:
4421 case CK_UncheckedDerivedToBase:
4422 case CK_Dynamic:
4423 case CK_ToUnion:
4424 case CK_ArrayToPointerDecay:
4425 case CK_FunctionToPointerDecay:
4426 case CK_NullToPointer:
4427 case CK_NullToMemberPointer:
4428 case CK_BaseToDerivedMemberPointer:
4429 case CK_DerivedToBaseMemberPointer:
4430 case CK_MemberPointerToBoolean:
4431 case CK_ConstructorConversion:
4432 case CK_IntegralToPointer:
4433 case CK_PointerToIntegral:
4434 case CK_PointerToBoolean:
4435 case CK_ToVoid:
4436 case CK_VectorSplat:
4437 case CK_IntegralCast:
4438 case CK_IntegralToBoolean:
4439 case CK_IntegralToFloating:
4440 case CK_FloatingToIntegral:
4441 case CK_FloatingToBoolean:
4442 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00004443 case CK_CPointerToObjCPointerCast:
4444 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004445 case CK_AnyPointerToBlockPointerCast:
4446 case CK_ObjCObjectLValueCast:
4447 case CK_FloatingComplexToReal:
4448 case CK_FloatingComplexToBoolean:
4449 case CK_IntegralComplexToReal:
4450 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00004451 case CK_ARCProduceObject:
4452 case CK_ARCConsumeObject:
4453 case CK_ARCReclaimReturnedObject:
4454 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00004455 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00004456
John McCallfcef3cf2010-12-14 17:51:41 +00004457 case CK_LValueToRValue:
4458 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004459 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004460
4461 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004462 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004463 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004464 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004465
4466 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004467 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00004468 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004469 return false;
4470
John McCallfcef3cf2010-12-14 17:51:41 +00004471 Result.makeComplexFloat();
4472 Result.FloatImag = APFloat(Real.getSemantics());
4473 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004474 }
4475
John McCallfcef3cf2010-12-14 17:51:41 +00004476 case CK_FloatingComplexCast: {
4477 if (!Visit(E->getSubExpr()))
4478 return false;
4479
4480 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4481 QualType From
4482 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4483
Richard Smith357362d2011-12-13 06:39:58 +00004484 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
4485 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00004486 }
4487
4488 case CK_FloatingComplexToIntegralComplex: {
4489 if (!Visit(E->getSubExpr()))
4490 return false;
4491
4492 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4493 QualType From
4494 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4495 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00004496 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
4497 To, Result.IntReal) &&
4498 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
4499 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00004500 }
4501
4502 case CK_IntegralRealToComplex: {
4503 APSInt &Real = Result.IntReal;
4504 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
4505 return false;
4506
4507 Result.makeComplexInt();
4508 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
4509 return true;
4510 }
4511
4512 case CK_IntegralComplexCast: {
4513 if (!Visit(E->getSubExpr()))
4514 return false;
4515
4516 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4517 QualType From
4518 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4519
4520 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
4521 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
4522 return true;
4523 }
4524
4525 case CK_IntegralComplexToFloatingComplex: {
4526 if (!Visit(E->getSubExpr()))
4527 return false;
4528
4529 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4530 QualType From
4531 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4532 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00004533 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
4534 To, Result.FloatReal) &&
4535 HandleIntToFloatCast(Info, E, From, Result.IntImag,
4536 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00004537 }
4538 }
4539
4540 llvm_unreachable("unknown cast resulting in complex value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004541 return Error(E);
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004542}
4543
John McCall93d91dc2010-05-07 17:22:02 +00004544bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004545 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00004546 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4547
John McCall93d91dc2010-05-07 17:22:02 +00004548 if (!Visit(E->getLHS()))
4549 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004550
John McCall93d91dc2010-05-07 17:22:02 +00004551 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004552 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00004553 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004554
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004555 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
4556 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004557 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004558 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004559 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004560 if (Result.isComplexFloat()) {
4561 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
4562 APFloat::rmNearestTiesToEven);
4563 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
4564 APFloat::rmNearestTiesToEven);
4565 } else {
4566 Result.getComplexIntReal() += RHS.getComplexIntReal();
4567 Result.getComplexIntImag() += RHS.getComplexIntImag();
4568 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004569 break;
John McCalle3027922010-08-25 11:45:40 +00004570 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004571 if (Result.isComplexFloat()) {
4572 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
4573 APFloat::rmNearestTiesToEven);
4574 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
4575 APFloat::rmNearestTiesToEven);
4576 } else {
4577 Result.getComplexIntReal() -= RHS.getComplexIntReal();
4578 Result.getComplexIntImag() -= RHS.getComplexIntImag();
4579 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004580 break;
John McCalle3027922010-08-25 11:45:40 +00004581 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004582 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00004583 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004584 APFloat &LHS_r = LHS.getComplexFloatReal();
4585 APFloat &LHS_i = LHS.getComplexFloatImag();
4586 APFloat &RHS_r = RHS.getComplexFloatReal();
4587 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00004588
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004589 APFloat Tmp = LHS_r;
4590 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4591 Result.getComplexFloatReal() = Tmp;
4592 Tmp = LHS_i;
4593 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4594 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
4595
4596 Tmp = LHS_r;
4597 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4598 Result.getComplexFloatImag() = Tmp;
4599 Tmp = LHS_i;
4600 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4601 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
4602 } else {
John McCall93d91dc2010-05-07 17:22:02 +00004603 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00004604 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004605 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
4606 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00004607 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004608 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
4609 LHS.getComplexIntImag() * RHS.getComplexIntReal());
4610 }
4611 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004612 case BO_Div:
4613 if (Result.isComplexFloat()) {
4614 ComplexValue LHS = Result;
4615 APFloat &LHS_r = LHS.getComplexFloatReal();
4616 APFloat &LHS_i = LHS.getComplexFloatImag();
4617 APFloat &RHS_r = RHS.getComplexFloatReal();
4618 APFloat &RHS_i = RHS.getComplexFloatImag();
4619 APFloat &Res_r = Result.getComplexFloatReal();
4620 APFloat &Res_i = Result.getComplexFloatImag();
4621
4622 APFloat Den = RHS_r;
4623 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4624 APFloat Tmp = RHS_i;
4625 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4626 Den.add(Tmp, APFloat::rmNearestTiesToEven);
4627
4628 Res_r = LHS_r;
4629 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4630 Tmp = LHS_i;
4631 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4632 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
4633 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
4634
4635 Res_i = LHS_i;
4636 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4637 Tmp = LHS_r;
4638 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4639 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
4640 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
4641 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004642 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
4643 return Error(E, diag::note_expr_divide_by_zero);
4644
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004645 ComplexValue LHS = Result;
4646 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
4647 RHS.getComplexIntImag() * RHS.getComplexIntImag();
4648 Result.getComplexIntReal() =
4649 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
4650 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
4651 Result.getComplexIntImag() =
4652 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
4653 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
4654 }
4655 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004656 }
4657
John McCall93d91dc2010-05-07 17:22:02 +00004658 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004659}
4660
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004661bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
4662 // Get the operand value into 'Result'.
4663 if (!Visit(E->getSubExpr()))
4664 return false;
4665
4666 switch (E->getOpcode()) {
4667 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004668 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004669 case UO_Extension:
4670 return true;
4671 case UO_Plus:
4672 // The result is always just the subexpr.
4673 return true;
4674 case UO_Minus:
4675 if (Result.isComplexFloat()) {
4676 Result.getComplexFloatReal().changeSign();
4677 Result.getComplexFloatImag().changeSign();
4678 }
4679 else {
4680 Result.getComplexIntReal() = -Result.getComplexIntReal();
4681 Result.getComplexIntImag() = -Result.getComplexIntImag();
4682 }
4683 return true;
4684 case UO_Not:
4685 if (Result.isComplexFloat())
4686 Result.getComplexFloatImag().changeSign();
4687 else
4688 Result.getComplexIntImag() = -Result.getComplexIntImag();
4689 return true;
4690 }
4691}
4692
Anders Carlsson537969c2008-11-16 20:27:53 +00004693//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00004694// Void expression evaluation, primarily for a cast to void on the LHS of a
4695// comma operator
4696//===----------------------------------------------------------------------===//
4697
4698namespace {
4699class VoidExprEvaluator
4700 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
4701public:
4702 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
4703
4704 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00004705
4706 bool VisitCastExpr(const CastExpr *E) {
4707 switch (E->getCastKind()) {
4708 default:
4709 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4710 case CK_ToVoid:
4711 VisitIgnoredValue(E->getSubExpr());
4712 return true;
4713 }
4714 }
4715};
4716} // end anonymous namespace
4717
4718static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
4719 assert(E->isRValue() && E->getType()->isVoidType());
4720 return VoidExprEvaluator(Info).Visit(E);
4721}
4722
4723//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00004724// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00004725//===----------------------------------------------------------------------===//
4726
Richard Smith0b0a0b62011-10-29 20:57:55 +00004727static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004728 // In C, function designators are not lvalues, but we evaluate them as if they
4729 // are.
4730 if (E->isGLValue() || E->getType()->isFunctionType()) {
4731 LValue LV;
4732 if (!EvaluateLValue(E, LV, Info))
4733 return false;
4734 LV.moveInto(Result);
4735 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00004736 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004737 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00004738 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00004739 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004740 return false;
John McCall45d55e42010-05-07 21:00:08 +00004741 } else if (E->getType()->hasPointerRepresentation()) {
4742 LValue LV;
4743 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004744 return false;
Richard Smith725810a2011-10-16 21:26:27 +00004745 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00004746 } else if (E->getType()->isRealFloatingType()) {
4747 llvm::APFloat F(0.0);
4748 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004749 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004750 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00004751 } else if (E->getType()->isAnyComplexType()) {
4752 ComplexValue C;
4753 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004754 return false;
Richard Smith725810a2011-10-16 21:26:27 +00004755 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00004756 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00004757 MemberPtr P;
4758 if (!EvaluateMemberPointer(E, P, Info))
4759 return false;
4760 P.moveInto(Result);
4761 return true;
Richard Smithed5165f2011-11-04 05:33:44 +00004762 } else if (E->getType()->isArrayType() && E->getType()->isLiteralType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00004763 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00004764 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00004765 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00004766 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004767 Result = Info.CurrentCall->Temporaries[E];
Richard Smithed5165f2011-11-04 05:33:44 +00004768 } else if (E->getType()->isRecordType() && E->getType()->isLiteralType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00004769 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00004770 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00004771 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
4772 return false;
4773 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00004774 } else if (E->getType()->isVoidType()) {
Richard Smith357362d2011-12-13 06:39:58 +00004775 if (Info.getLangOpts().CPlusPlus0x)
4776 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
4777 << E->getType();
4778 else
4779 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith42d3af92011-12-07 00:43:50 +00004780 if (!EvaluateVoid(E, Info))
4781 return false;
Richard Smith357362d2011-12-13 06:39:58 +00004782 } else if (Info.getLangOpts().CPlusPlus0x) {
4783 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
4784 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004785 } else {
Richard Smith92b1ce02011-12-12 09:28:41 +00004786 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00004787 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004788 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004789
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00004790 return true;
4791}
4792
Richard Smithed5165f2011-11-04 05:33:44 +00004793/// EvaluateConstantExpression - Evaluate an expression as a constant expression
4794/// in-place in an APValue. In some cases, the in-place evaluation is essential,
4795/// since later initializers for an object can indirectly refer to subobjects
4796/// which were initialized earlier.
4797static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smith357362d2011-12-13 06:39:58 +00004798 const LValue &This, const Expr *E,
4799 CheckConstantExpressionKind CCEK) {
Richard Smithed5165f2011-11-04 05:33:44 +00004800 if (E->isRValue() && E->getType()->isLiteralType()) {
4801 // Evaluate arrays and record types in-place, so that later initializers can
4802 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00004803 if (E->getType()->isArrayType())
4804 return EvaluateArray(E, This, Result, Info);
4805 else if (E->getType()->isRecordType())
4806 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00004807 }
4808
4809 // For any other type, in-place evaluation is unimportant.
4810 CCValue CoreConstResult;
4811 return Evaluate(CoreConstResult, Info, E) &&
Richard Smith357362d2011-12-13 06:39:58 +00004812 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smithed5165f2011-11-04 05:33:44 +00004813}
4814
Richard Smithf57d8cb2011-12-09 22:58:01 +00004815/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
4816/// lvalue-to-rvalue cast if it is an lvalue.
4817static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
4818 CCValue Value;
4819 if (!::Evaluate(Value, Info, E))
4820 return false;
4821
4822 if (E->isGLValue()) {
4823 LValue LV;
4824 LV.setFrom(Value);
4825 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
4826 return false;
4827 }
4828
4829 // Check this core constant expression is a constant expression, and if so,
4830 // convert it to one.
4831 return CheckConstantExpression(Info, E, Value, Result);
4832}
Richard Smith11562c52011-10-28 17:51:58 +00004833
Richard Smith7b553f12011-10-29 00:50:52 +00004834/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00004835/// any crazy technique (that has nothing to do with language standards) that
4836/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00004837/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
4838/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00004839bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith036e2bd2011-12-10 01:10:13 +00004840 // Fast-path evaluations of integer literals, since we sometimes see files
4841 // containing vast quantities of these.
4842 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
4843 Result.Val = APValue(APSInt(L->getValue(),
4844 L->getType()->isUnsignedIntegerType()));
4845 return true;
4846 }
4847
Richard Smith5686e752011-11-10 03:30:42 +00004848 // FIXME: Evaluating initializers for large arrays can cause performance
4849 // problems, and we don't use such values yet. Once we have a more efficient
4850 // array representation, this should be reinstated, and used by CodeGen.
Richard Smith027bf112011-11-17 22:56:20 +00004851 // The same problem affects large records.
4852 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
4853 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith5686e752011-11-10 03:30:42 +00004854 return false;
4855
Richard Smithd62306a2011-11-10 06:34:14 +00004856 // FIXME: If this is the initializer for an lvalue, pass that in.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004857 EvalInfo Info(Ctx, Result);
4858 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00004859}
4860
Jay Foad39c79802011-01-12 09:06:06 +00004861bool Expr::EvaluateAsBooleanCondition(bool &Result,
4862 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00004863 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00004864 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithfec09922011-11-01 16:57:24 +00004865 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith0b0a0b62011-10-29 20:57:55 +00004866 Result);
John McCall1be1c632010-01-05 23:42:56 +00004867}
4868
Richard Smithcaf33902011-10-10 18:28:20 +00004869bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00004870 EvalResult ExprResult;
Richard Smith7b553f12011-10-29 00:50:52 +00004871 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00004872 !ExprResult.Val.isInt())
Richard Smith11562c52011-10-28 17:51:58 +00004873 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004874
Richard Smith11562c52011-10-28 17:51:58 +00004875 Result = ExprResult.Val.getInt();
4876 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00004877}
4878
Jay Foad39c79802011-01-12 09:06:06 +00004879bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00004880 EvalInfo Info(Ctx, Result);
4881
John McCall45d55e42010-05-07 21:00:08 +00004882 LValue LV;
Richard Smith80815602011-11-07 05:07:52 +00004883 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smith357362d2011-12-13 06:39:58 +00004884 CheckLValueConstantExpression(Info, this, LV, Result.Val,
4885 CCEK_Constant);
Eli Friedman7d45c482009-09-13 10:17:44 +00004886}
4887
Richard Smithd0b4dd62011-12-19 06:19:21 +00004888bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
4889 const VarDecl *VD,
4890 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
4891 Expr::EvalStatus EStatus;
4892 EStatus.Diag = &Notes;
4893
4894 EvalInfo InitInfo(Ctx, EStatus);
4895 InitInfo.setEvaluatingDecl(VD, Value);
4896
4897 LValue LVal;
4898 LVal.set(VD);
4899
4900 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
4901 !EStatus.HasSideEffects;
4902}
4903
Richard Smith7b553f12011-10-29 00:50:52 +00004904/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
4905/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00004906bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00004907 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00004908 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00004909}
Anders Carlsson59689ed2008-11-22 21:04:56 +00004910
Jay Foad39c79802011-01-12 09:06:06 +00004911bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00004912 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00004913}
4914
Richard Smithcaf33902011-10-10 18:28:20 +00004915APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00004916 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00004917 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00004918 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00004919 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00004920 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00004921
Anders Carlsson6736d1a22008-12-19 20:58:05 +00004922 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00004923}
John McCall864e3962010-05-07 05:32:02 +00004924
Abramo Bagnaraf8199452010-05-14 17:07:14 +00004925 bool Expr::EvalResult::isGlobalLValue() const {
4926 assert(Val.isLValue());
4927 return IsGlobalLValue(Val.getLValueBase());
4928 }
4929
4930
John McCall864e3962010-05-07 05:32:02 +00004931/// isIntegerConstantExpr - this recursive routine will test if an expression is
4932/// an integer constant expression.
4933
4934/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
4935/// comma, etc
4936///
4937/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
4938/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
4939/// cast+dereference.
4940
4941// CheckICE - This function does the fundamental ICE checking: the returned
4942// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
4943// Note that to reduce code duplication, this helper does no evaluation
4944// itself; the caller checks whether the expression is evaluatable, and
4945// in the rare cases where CheckICE actually cares about the evaluated
4946// value, it calls into Evalute.
4947//
4948// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00004949// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00004950// 1: This expression is not an ICE, but if it isn't evaluated, it's
4951// a legal subexpression for an ICE. This return value is used to handle
4952// the comma operator in C99 mode.
4953// 2: This expression is not an ICE, and is not a legal subexpression for one.
4954
Dan Gohman28ade552010-07-26 21:25:24 +00004955namespace {
4956
John McCall864e3962010-05-07 05:32:02 +00004957struct ICEDiag {
4958 unsigned Val;
4959 SourceLocation Loc;
4960
4961 public:
4962 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
4963 ICEDiag() : Val(0) {}
4964};
4965
Dan Gohman28ade552010-07-26 21:25:24 +00004966}
4967
4968static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00004969
4970static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
4971 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00004972 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00004973 !EVResult.Val.isInt()) {
4974 return ICEDiag(2, E->getLocStart());
4975 }
4976 return NoDiag();
4977}
4978
4979static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
4980 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00004981 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00004982 return ICEDiag(2, E->getLocStart());
4983 }
4984
4985 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00004986#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00004987#define STMT(Node, Base) case Expr::Node##Class:
4988#define EXPR(Node, Base)
4989#include "clang/AST/StmtNodes.inc"
4990 case Expr::PredefinedExprClass:
4991 case Expr::FloatingLiteralClass:
4992 case Expr::ImaginaryLiteralClass:
4993 case Expr::StringLiteralClass:
4994 case Expr::ArraySubscriptExprClass:
4995 case Expr::MemberExprClass:
4996 case Expr::CompoundAssignOperatorClass:
4997 case Expr::CompoundLiteralExprClass:
4998 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00004999 case Expr::DesignatedInitExprClass:
5000 case Expr::ImplicitValueInitExprClass:
5001 case Expr::ParenListExprClass:
5002 case Expr::VAArgExprClass:
5003 case Expr::AddrLabelExprClass:
5004 case Expr::StmtExprClass:
5005 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00005006 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00005007 case Expr::CXXDynamicCastExprClass:
5008 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00005009 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00005010 case Expr::CXXNullPtrLiteralExprClass:
5011 case Expr::CXXThisExprClass:
5012 case Expr::CXXThrowExprClass:
5013 case Expr::CXXNewExprClass:
5014 case Expr::CXXDeleteExprClass:
5015 case Expr::CXXPseudoDestructorExprClass:
5016 case Expr::UnresolvedLookupExprClass:
5017 case Expr::DependentScopeDeclRefExprClass:
5018 case Expr::CXXConstructExprClass:
5019 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00005020 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00005021 case Expr::CXXTemporaryObjectExprClass:
5022 case Expr::CXXUnresolvedConstructExprClass:
5023 case Expr::CXXDependentScopeMemberExprClass:
5024 case Expr::UnresolvedMemberExprClass:
5025 case Expr::ObjCStringLiteralClass:
5026 case Expr::ObjCEncodeExprClass:
5027 case Expr::ObjCMessageExprClass:
5028 case Expr::ObjCSelectorExprClass:
5029 case Expr::ObjCProtocolExprClass:
5030 case Expr::ObjCIvarRefExprClass:
5031 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00005032 case Expr::ObjCIsaExprClass:
5033 case Expr::ShuffleVectorExprClass:
5034 case Expr::BlockExprClass:
5035 case Expr::BlockDeclRefExprClass:
5036 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00005037 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00005038 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00005039 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00005040 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00005041 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00005042 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00005043 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00005044 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00005045 case Expr::InitListExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00005046 return ICEDiag(2, E->getLocStart());
5047
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005048 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00005049 case Expr::GNUNullExprClass:
5050 // GCC considers the GNU __null value to be an integral constant expression.
5051 return NoDiag();
5052
John McCall7c454bb2011-07-15 05:09:51 +00005053 case Expr::SubstNonTypeTemplateParmExprClass:
5054 return
5055 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
5056
John McCall864e3962010-05-07 05:32:02 +00005057 case Expr::ParenExprClass:
5058 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00005059 case Expr::GenericSelectionExprClass:
5060 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005061 case Expr::IntegerLiteralClass:
5062 case Expr::CharacterLiteralClass:
5063 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00005064 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00005065 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005066 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00005067 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00005068 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00005069 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00005070 return NoDiag();
5071 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00005072 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00005073 // C99 6.6/3 allows function calls within unevaluated subexpressions of
5074 // constant expressions, but they can never be ICEs because an ICE cannot
5075 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00005076 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005077 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00005078 return CheckEvalInICE(E, Ctx);
5079 return ICEDiag(2, E->getLocStart());
5080 }
5081 case Expr::DeclRefExprClass:
5082 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
5083 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00005084 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00005085 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
5086
5087 // Parameter variables are never constants. Without this check,
5088 // getAnyInitializer() can find a default argument, which leads
5089 // to chaos.
5090 if (isa<ParmVarDecl>(D))
5091 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5092
5093 // C++ 7.1.5.1p2
5094 // A variable of non-volatile const-qualified integral or enumeration
5095 // type initialized by an ICE can be used in ICEs.
5096 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00005097 if (!Dcl->getType()->isIntegralOrEnumerationType())
5098 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5099
Richard Smithd0b4dd62011-12-19 06:19:21 +00005100 const VarDecl *VD;
5101 // Look for a declaration of this variable that has an initializer, and
5102 // check whether it is an ICE.
5103 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
5104 return NoDiag();
5105 else
5106 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00005107 }
5108 }
5109 return ICEDiag(2, E->getLocStart());
5110 case Expr::UnaryOperatorClass: {
5111 const UnaryOperator *Exp = cast<UnaryOperator>(E);
5112 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00005113 case UO_PostInc:
5114 case UO_PostDec:
5115 case UO_PreInc:
5116 case UO_PreDec:
5117 case UO_AddrOf:
5118 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00005119 // C99 6.6/3 allows increment and decrement within unevaluated
5120 // subexpressions of constant expressions, but they can never be ICEs
5121 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00005122 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00005123 case UO_Extension:
5124 case UO_LNot:
5125 case UO_Plus:
5126 case UO_Minus:
5127 case UO_Not:
5128 case UO_Real:
5129 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00005130 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005131 }
5132
5133 // OffsetOf falls through here.
5134 }
5135 case Expr::OffsetOfExprClass: {
5136 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00005137 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00005138 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00005139 // compliance: we should warn earlier for offsetof expressions with
5140 // array subscripts that aren't ICEs, and if the array subscripts
5141 // are ICEs, the value of the offsetof must be an integer constant.
5142 return CheckEvalInICE(E, Ctx);
5143 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00005144 case Expr::UnaryExprOrTypeTraitExprClass: {
5145 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
5146 if ((Exp->getKind() == UETT_SizeOf) &&
5147 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00005148 return ICEDiag(2, E->getLocStart());
5149 return NoDiag();
5150 }
5151 case Expr::BinaryOperatorClass: {
5152 const BinaryOperator *Exp = cast<BinaryOperator>(E);
5153 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00005154 case BO_PtrMemD:
5155 case BO_PtrMemI:
5156 case BO_Assign:
5157 case BO_MulAssign:
5158 case BO_DivAssign:
5159 case BO_RemAssign:
5160 case BO_AddAssign:
5161 case BO_SubAssign:
5162 case BO_ShlAssign:
5163 case BO_ShrAssign:
5164 case BO_AndAssign:
5165 case BO_XorAssign:
5166 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00005167 // C99 6.6/3 allows assignments within unevaluated subexpressions of
5168 // constant expressions, but they can never be ICEs because an ICE cannot
5169 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00005170 return ICEDiag(2, E->getLocStart());
5171
John McCalle3027922010-08-25 11:45:40 +00005172 case BO_Mul:
5173 case BO_Div:
5174 case BO_Rem:
5175 case BO_Add:
5176 case BO_Sub:
5177 case BO_Shl:
5178 case BO_Shr:
5179 case BO_LT:
5180 case BO_GT:
5181 case BO_LE:
5182 case BO_GE:
5183 case BO_EQ:
5184 case BO_NE:
5185 case BO_And:
5186 case BO_Xor:
5187 case BO_Or:
5188 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00005189 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5190 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00005191 if (Exp->getOpcode() == BO_Div ||
5192 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00005193 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00005194 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00005195 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00005196 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00005197 if (REval == 0)
5198 return ICEDiag(1, E->getLocStart());
5199 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00005200 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00005201 if (LEval.isMinSignedValue())
5202 return ICEDiag(1, E->getLocStart());
5203 }
5204 }
5205 }
John McCalle3027922010-08-25 11:45:40 +00005206 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00005207 if (Ctx.getLangOptions().C99) {
5208 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
5209 // if it isn't evaluated.
5210 if (LHSResult.Val == 0 && RHSResult.Val == 0)
5211 return ICEDiag(1, E->getLocStart());
5212 } else {
5213 // In both C89 and C++, commas in ICEs are illegal.
5214 return ICEDiag(2, E->getLocStart());
5215 }
5216 }
5217 if (LHSResult.Val >= RHSResult.Val)
5218 return LHSResult;
5219 return RHSResult;
5220 }
John McCalle3027922010-08-25 11:45:40 +00005221 case BO_LAnd:
5222 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00005223 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5224 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
5225 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
5226 // Rare case where the RHS has a comma "side-effect"; we need
5227 // to actually check the condition to see whether the side
5228 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00005229 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00005230 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00005231 return RHSResult;
5232 return NoDiag();
5233 }
5234
5235 if (LHSResult.Val >= RHSResult.Val)
5236 return LHSResult;
5237 return RHSResult;
5238 }
5239 }
5240 }
5241 case Expr::ImplicitCastExprClass:
5242 case Expr::CStyleCastExprClass:
5243 case Expr::CXXFunctionalCastExprClass:
5244 case Expr::CXXStaticCastExprClass:
5245 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00005246 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005247 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00005248 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00005249 if (isa<ExplicitCastExpr>(E)) {
5250 if (const FloatingLiteral *FL
5251 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
5252 unsigned DestWidth = Ctx.getIntWidth(E->getType());
5253 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
5254 APSInt IgnoredVal(DestWidth, !DestSigned);
5255 bool Ignored;
5256 // If the value does not fit in the destination type, the behavior is
5257 // undefined, so we are not required to treat it as a constant
5258 // expression.
5259 if (FL->getValue().convertToInteger(IgnoredVal,
5260 llvm::APFloat::rmTowardZero,
5261 &Ignored) & APFloat::opInvalidOp)
5262 return ICEDiag(2, E->getLocStart());
5263 return NoDiag();
5264 }
5265 }
Eli Friedman76d4e432011-09-29 21:49:34 +00005266 switch (cast<CastExpr>(E)->getCastKind()) {
5267 case CK_LValueToRValue:
5268 case CK_NoOp:
5269 case CK_IntegralToBoolean:
5270 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00005271 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00005272 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00005273 return ICEDiag(2, E->getLocStart());
5274 }
John McCall864e3962010-05-07 05:32:02 +00005275 }
John McCallc07a0c72011-02-17 10:25:35 +00005276 case Expr::BinaryConditionalOperatorClass: {
5277 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
5278 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
5279 if (CommonResult.Val == 2) return CommonResult;
5280 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
5281 if (FalseResult.Val == 2) return FalseResult;
5282 if (CommonResult.Val == 1) return CommonResult;
5283 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00005284 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00005285 return FalseResult;
5286 }
John McCall864e3962010-05-07 05:32:02 +00005287 case Expr::ConditionalOperatorClass: {
5288 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
5289 // If the condition (ignoring parens) is a __builtin_constant_p call,
5290 // then only the true side is actually considered in an integer constant
5291 // expression, and it is fully evaluated. This is an important GNU
5292 // extension. See GCC PR38377 for discussion.
5293 if (const CallExpr *CallCE
5294 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smithd62306a2011-11-10 06:34:14 +00005295 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p) {
John McCall864e3962010-05-07 05:32:02 +00005296 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005297 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00005298 !EVResult.Val.isInt()) {
5299 return ICEDiag(2, E->getLocStart());
5300 }
5301 return NoDiag();
5302 }
5303 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005304 if (CondResult.Val == 2)
5305 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005306
Richard Smithf57d8cb2011-12-09 22:58:01 +00005307 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
5308 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005309
John McCall864e3962010-05-07 05:32:02 +00005310 if (TrueResult.Val == 2)
5311 return TrueResult;
5312 if (FalseResult.Val == 2)
5313 return FalseResult;
5314 if (CondResult.Val == 1)
5315 return CondResult;
5316 if (TrueResult.Val == 0 && FalseResult.Val == 0)
5317 return NoDiag();
5318 // Rare case where the diagnostics depend on which side is evaluated
5319 // Note that if we get here, CondResult is 0, and at least one of
5320 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00005321 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00005322 return FalseResult;
5323 }
5324 return TrueResult;
5325 }
5326 case Expr::CXXDefaultArgExprClass:
5327 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
5328 case Expr::ChooseExprClass: {
5329 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
5330 }
5331 }
5332
5333 // Silence a GCC warning
5334 return ICEDiag(2, E->getLocStart());
5335}
5336
Richard Smithf57d8cb2011-12-09 22:58:01 +00005337/// Evaluate an expression as a C++11 integral constant expression.
5338static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
5339 const Expr *E,
5340 llvm::APSInt *Value,
5341 SourceLocation *Loc) {
5342 if (!E->getType()->isIntegralOrEnumerationType()) {
5343 if (Loc) *Loc = E->getExprLoc();
5344 return false;
5345 }
5346
5347 Expr::EvalResult Result;
Richard Smith92b1ce02011-12-12 09:28:41 +00005348 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
5349 Result.Diag = &Diags;
5350 EvalInfo Info(Ctx, Result);
5351
5352 bool IsICE = EvaluateAsRValue(Info, E, Result.Val);
5353 if (!Diags.empty()) {
5354 IsICE = false;
5355 if (Loc) *Loc = Diags[0].first;
5356 } else if (!IsICE && Loc) {
5357 *Loc = E->getExprLoc();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005358 }
Richard Smith92b1ce02011-12-12 09:28:41 +00005359
5360 if (!IsICE)
5361 return false;
5362
5363 assert(Result.Val.isInt() && "pointer cast to int is not an ICE");
5364 if (Value) *Value = Result.Val.getInt();
5365 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005366}
5367
Richard Smith92b1ce02011-12-12 09:28:41 +00005368bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005369 if (Ctx.getLangOptions().CPlusPlus0x)
5370 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
5371
John McCall864e3962010-05-07 05:32:02 +00005372 ICEDiag d = CheckICE(this, Ctx);
5373 if (d.Val != 0) {
5374 if (Loc) *Loc = d.Loc;
5375 return false;
5376 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005377 return true;
5378}
5379
5380bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
5381 SourceLocation *Loc, bool isEvaluated) const {
5382 if (Ctx.getLangOptions().CPlusPlus0x)
5383 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
5384
5385 if (!isIntegerConstantExpr(Ctx, Loc))
5386 return false;
5387 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00005388 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00005389 return true;
5390}