1 //===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===//
2 //
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 defines the Expr interface and subclasses.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_CLANG_AST_EXPR_H
15 #define LLVM_CLANG_AST_EXPR_H
16
17 #include "clang/AST/APValue.h"
18 #include "clang/AST/ASTVector.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclAccessPair.h"
21 #include "clang/AST/OperationKinds.h"
22 #include "clang/AST/Stmt.h"
23 #include "clang/AST/TemplateBase.h"
24 #include "clang/AST/Type.h"
25 #include "clang/Basic/CharInfo.h"
26 #include "clang/Basic/TypeTraits.h"
27 #include "llvm/ADT/APFloat.h"
28 #include "llvm/ADT/APSInt.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/StringRef.h"
31 #include "llvm/Support/Compiler.h"
32
33 namespace clang {
34 class APValue;
35 class ASTContext;
36 class BlockDecl;
37 class CXXBaseSpecifier;
38 class CXXMemberCallExpr;
39 class CXXOperatorCallExpr;
40 class CastExpr;
41 class Decl;
42 class IdentifierInfo;
43 class MaterializeTemporaryExpr;
44 class NamedDecl;
45 class ObjCPropertyRefExpr;
46 class OpaqueValueExpr;
47 class ParmVarDecl;
48 class StringLiteral;
49 class TargetInfo;
50 class ValueDecl;
51
52 /// \brief A simple array of base specifiers.
53 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
54
55 /// \brief An adjustment to be made to the temporary created when emitting a
56 /// reference binding, which accesses a particular subobject of that temporary.
57 struct SubobjectAdjustment {
58 enum {
59 DerivedToBaseAdjustment,
60 FieldAdjustment,
61 MemberPointerAdjustment
62 } Kind;
63
64
65 struct DTB {
66 const CastExpr *BasePath;
67 const CXXRecordDecl *DerivedClass;
68 };
69
70 struct P {
71 const MemberPointerType *MPT;
72 Expr *RHS;
73 };
74
75 union {
76 struct DTB DerivedToBase;
77 FieldDecl *Field;
78 struct P Ptr;
79 };
80
SubobjectAdjustmentSubobjectAdjustment81 SubobjectAdjustment(const CastExpr *BasePath,
82 const CXXRecordDecl *DerivedClass)
83 : Kind(DerivedToBaseAdjustment) {
84 DerivedToBase.BasePath = BasePath;
85 DerivedToBase.DerivedClass = DerivedClass;
86 }
87
SubobjectAdjustmentSubobjectAdjustment88 SubobjectAdjustment(FieldDecl *Field)
89 : Kind(FieldAdjustment) {
90 this->Field = Field;
91 }
92
SubobjectAdjustmentSubobjectAdjustment93 SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS)
94 : Kind(MemberPointerAdjustment) {
95 this->Ptr.MPT = MPT;
96 this->Ptr.RHS = RHS;
97 }
98 };
99
100 /// Expr - This represents one expression. Note that Expr's are subclasses of
101 /// Stmt. This allows an expression to be transparently used any place a Stmt
102 /// is required.
103 ///
104 class Expr : public Stmt {
105 QualType TR;
106
107 protected:
Expr(StmtClass SC,QualType T,ExprValueKind VK,ExprObjectKind OK,bool TD,bool VD,bool ID,bool ContainsUnexpandedParameterPack)108 Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK,
109 bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack)
110 : Stmt(SC)
111 {
112 ExprBits.TypeDependent = TD;
113 ExprBits.ValueDependent = VD;
114 ExprBits.InstantiationDependent = ID;
115 ExprBits.ValueKind = VK;
116 ExprBits.ObjectKind = OK;
117 ExprBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
118 setType(T);
119 }
120
121 /// \brief Construct an empty expression.
Expr(StmtClass SC,EmptyShell)122 explicit Expr(StmtClass SC, EmptyShell) : Stmt(SC) { }
123
124 public:
getType()125 QualType getType() const { return TR; }
setType(QualType t)126 void setType(QualType t) {
127 // In C++, the type of an expression is always adjusted so that it
128 // will not have reference type (C++ [expr]p6). Use
129 // QualType::getNonReferenceType() to retrieve the non-reference
130 // type. Additionally, inspect Expr::isLvalue to determine whether
131 // an expression that is adjusted in this manner should be
132 // considered an lvalue.
133 assert((t.isNull() || !t->isReferenceType()) &&
134 "Expressions can't have reference type");
135
136 TR = t;
137 }
138
139 /// isValueDependent - Determines whether this expression is
140 /// value-dependent (C++ [temp.dep.constexpr]). For example, the
141 /// array bound of "Chars" in the following example is
142 /// value-dependent.
143 /// @code
144 /// template<int Size, char (&Chars)[Size]> struct meta_string;
145 /// @endcode
isValueDependent()146 bool isValueDependent() const { return ExprBits.ValueDependent; }
147
148 /// \brief Set whether this expression is value-dependent or not.
setValueDependent(bool VD)149 void setValueDependent(bool VD) {
150 ExprBits.ValueDependent = VD;
151 if (VD)
152 ExprBits.InstantiationDependent = true;
153 }
154
155 /// isTypeDependent - Determines whether this expression is
156 /// type-dependent (C++ [temp.dep.expr]), which means that its type
157 /// could change from one template instantiation to the next. For
158 /// example, the expressions "x" and "x + y" are type-dependent in
159 /// the following code, but "y" is not type-dependent:
160 /// @code
161 /// template<typename T>
162 /// void add(T x, int y) {
163 /// x + y;
164 /// }
165 /// @endcode
isTypeDependent()166 bool isTypeDependent() const { return ExprBits.TypeDependent; }
167
168 /// \brief Set whether this expression is type-dependent or not.
setTypeDependent(bool TD)169 void setTypeDependent(bool TD) {
170 ExprBits.TypeDependent = TD;
171 if (TD)
172 ExprBits.InstantiationDependent = true;
173 }
174
175 /// \brief Whether this expression is instantiation-dependent, meaning that
176 /// it depends in some way on a template parameter, even if neither its type
177 /// nor (constant) value can change due to the template instantiation.
178 ///
179 /// In the following example, the expression \c sizeof(sizeof(T() + T())) is
180 /// instantiation-dependent (since it involves a template parameter \c T), but
181 /// is neither type- nor value-dependent, since the type of the inner
182 /// \c sizeof is known (\c std::size_t) and therefore the size of the outer
183 /// \c sizeof is known.
184 ///
185 /// \code
186 /// template<typename T>
187 /// void f(T x, T y) {
188 /// sizeof(sizeof(T() + T());
189 /// }
190 /// \endcode
191 ///
isInstantiationDependent()192 bool isInstantiationDependent() const {
193 return ExprBits.InstantiationDependent;
194 }
195
196 /// \brief Set whether this expression is instantiation-dependent or not.
setInstantiationDependent(bool ID)197 void setInstantiationDependent(bool ID) {
198 ExprBits.InstantiationDependent = ID;
199 }
200
201 /// \brief Whether this expression contains an unexpanded parameter
202 /// pack (for C++11 variadic templates).
203 ///
204 /// Given the following function template:
205 ///
206 /// \code
207 /// template<typename F, typename ...Types>
208 /// void forward(const F &f, Types &&...args) {
209 /// f(static_cast<Types&&>(args)...);
210 /// }
211 /// \endcode
212 ///
213 /// The expressions \c args and \c static_cast<Types&&>(args) both
214 /// contain parameter packs.
containsUnexpandedParameterPack()215 bool containsUnexpandedParameterPack() const {
216 return ExprBits.ContainsUnexpandedParameterPack;
217 }
218
219 /// \brief Set the bit that describes whether this expression
220 /// contains an unexpanded parameter pack.
221 void setContainsUnexpandedParameterPack(bool PP = true) {
222 ExprBits.ContainsUnexpandedParameterPack = PP;
223 }
224
225 /// getExprLoc - Return the preferred location for the arrow when diagnosing
226 /// a problem with a generic expression.
227 SourceLocation getExprLoc() const LLVM_READONLY;
228
229 /// isUnusedResultAWarning - Return true if this immediate expression should
230 /// be warned about if the result is unused. If so, fill in expr, location,
231 /// and ranges with expr to warn on and source locations/ranges appropriate
232 /// for a warning.
233 bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc,
234 SourceRange &R1, SourceRange &R2,
235 ASTContext &Ctx) const;
236
237 /// isLValue - True if this expression is an "l-value" according to
238 /// the rules of the current language. C and C++ give somewhat
239 /// different rules for this concept, but in general, the result of
240 /// an l-value expression identifies a specific object whereas the
241 /// result of an r-value expression is a value detached from any
242 /// specific storage.
243 ///
244 /// C++11 divides the concept of "r-value" into pure r-values
245 /// ("pr-values") and so-called expiring values ("x-values"), which
246 /// identify specific objects that can be safely cannibalized for
247 /// their resources. This is an unfortunate abuse of terminology on
248 /// the part of the C++ committee. In Clang, when we say "r-value",
249 /// we generally mean a pr-value.
isLValue()250 bool isLValue() const { return getValueKind() == VK_LValue; }
isRValue()251 bool isRValue() const { return getValueKind() == VK_RValue; }
isXValue()252 bool isXValue() const { return getValueKind() == VK_XValue; }
isGLValue()253 bool isGLValue() const { return getValueKind() != VK_RValue; }
254
255 enum LValueClassification {
256 LV_Valid,
257 LV_NotObjectType,
258 LV_IncompleteVoidType,
259 LV_DuplicateVectorComponents,
260 LV_InvalidExpression,
261 LV_InvalidMessageExpression,
262 LV_MemberFunction,
263 LV_SubObjCPropertySetting,
264 LV_ClassTemporary,
265 LV_ArrayTemporary
266 };
267 /// Reasons why an expression might not be an l-value.
268 LValueClassification ClassifyLValue(ASTContext &Ctx) const;
269
270 enum isModifiableLvalueResult {
271 MLV_Valid,
272 MLV_NotObjectType,
273 MLV_IncompleteVoidType,
274 MLV_DuplicateVectorComponents,
275 MLV_InvalidExpression,
276 MLV_LValueCast, // Specialized form of MLV_InvalidExpression.
277 MLV_IncompleteType,
278 MLV_ConstQualified,
279 MLV_ArrayType,
280 MLV_NoSetterProperty,
281 MLV_MemberFunction,
282 MLV_SubObjCPropertySetting,
283 MLV_InvalidMessageExpression,
284 MLV_ClassTemporary,
285 MLV_ArrayTemporary
286 };
287 /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
288 /// does not have an incomplete type, does not have a const-qualified type,
289 /// and if it is a structure or union, does not have any member (including,
290 /// recursively, any member or element of all contained aggregates or unions)
291 /// with a const-qualified type.
292 ///
293 /// \param Loc [in,out] - A source location which *may* be filled
294 /// in with the location of the expression making this a
295 /// non-modifiable lvalue, if specified.
296 isModifiableLvalueResult
297 isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const;
298
299 /// \brief The return type of classify(). Represents the C++11 expression
300 /// taxonomy.
301 class Classification {
302 public:
303 /// \brief The various classification results. Most of these mean prvalue.
304 enum Kinds {
305 CL_LValue,
306 CL_XValue,
307 CL_Function, // Functions cannot be lvalues in C.
308 CL_Void, // Void cannot be an lvalue in C.
309 CL_AddressableVoid, // Void expression whose address can be taken in C.
310 CL_DuplicateVectorComponents, // A vector shuffle with dupes.
311 CL_MemberFunction, // An expression referring to a member function
312 CL_SubObjCPropertySetting,
313 CL_ClassTemporary, // A temporary of class type, or subobject thereof.
314 CL_ArrayTemporary, // A temporary of array type.
315 CL_ObjCMessageRValue, // ObjC message is an rvalue
316 CL_PRValue // A prvalue for any other reason, of any other type
317 };
318 /// \brief The results of modification testing.
319 enum ModifiableType {
320 CM_Untested, // testModifiable was false.
321 CM_Modifiable,
322 CM_RValue, // Not modifiable because it's an rvalue
323 CM_Function, // Not modifiable because it's a function; C++ only
324 CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
325 CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
326 CM_ConstQualified,
327 CM_ArrayType,
328 CM_IncompleteType
329 };
330
331 private:
332 friend class Expr;
333
334 unsigned short Kind;
335 unsigned short Modifiable;
336
Classification(Kinds k,ModifiableType m)337 explicit Classification(Kinds k, ModifiableType m)
338 : Kind(k), Modifiable(m)
339 {}
340
341 public:
Classification()342 Classification() {}
343
getKind()344 Kinds getKind() const { return static_cast<Kinds>(Kind); }
getModifiable()345 ModifiableType getModifiable() const {
346 assert(Modifiable != CM_Untested && "Did not test for modifiability.");
347 return static_cast<ModifiableType>(Modifiable);
348 }
isLValue()349 bool isLValue() const { return Kind == CL_LValue; }
isXValue()350 bool isXValue() const { return Kind == CL_XValue; }
isGLValue()351 bool isGLValue() const { return Kind <= CL_XValue; }
isPRValue()352 bool isPRValue() const { return Kind >= CL_Function; }
isRValue()353 bool isRValue() const { return Kind >= CL_XValue; }
isModifiable()354 bool isModifiable() const { return getModifiable() == CM_Modifiable; }
355
356 /// \brief Create a simple, modifiably lvalue
makeSimpleLValue()357 static Classification makeSimpleLValue() {
358 return Classification(CL_LValue, CM_Modifiable);
359 }
360
361 };
362 /// \brief Classify - Classify this expression according to the C++11
363 /// expression taxonomy.
364 ///
365 /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the
366 /// old lvalue vs rvalue. This function determines the type of expression this
367 /// is. There are three expression types:
368 /// - lvalues are classical lvalues as in C++03.
369 /// - prvalues are equivalent to rvalues in C++03.
370 /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
371 /// function returning an rvalue reference.
372 /// lvalues and xvalues are collectively referred to as glvalues, while
373 /// prvalues and xvalues together form rvalues.
Classify(ASTContext & Ctx)374 Classification Classify(ASTContext &Ctx) const {
375 return ClassifyImpl(Ctx, nullptr);
376 }
377
378 /// \brief ClassifyModifiable - Classify this expression according to the
379 /// C++11 expression taxonomy, and see if it is valid on the left side
380 /// of an assignment.
381 ///
382 /// This function extends classify in that it also tests whether the
383 /// expression is modifiable (C99 6.3.2.1p1).
384 /// \param Loc A source location that might be filled with a relevant location
385 /// if the expression is not modifiable.
ClassifyModifiable(ASTContext & Ctx,SourceLocation & Loc)386 Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
387 return ClassifyImpl(Ctx, &Loc);
388 }
389
390 /// getValueKindForType - Given a formal return or parameter type,
391 /// give its value kind.
getValueKindForType(QualType T)392 static ExprValueKind getValueKindForType(QualType T) {
393 if (const ReferenceType *RT = T->getAs<ReferenceType>())
394 return (isa<LValueReferenceType>(RT)
395 ? VK_LValue
396 : (RT->getPointeeType()->isFunctionType()
397 ? VK_LValue : VK_XValue));
398 return VK_RValue;
399 }
400
401 /// getValueKind - The value kind that this expression produces.
getValueKind()402 ExprValueKind getValueKind() const {
403 return static_cast<ExprValueKind>(ExprBits.ValueKind);
404 }
405
406 /// getObjectKind - The object kind that this expression produces.
407 /// Object kinds are meaningful only for expressions that yield an
408 /// l-value or x-value.
getObjectKind()409 ExprObjectKind getObjectKind() const {
410 return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
411 }
412
isOrdinaryOrBitFieldObject()413 bool isOrdinaryOrBitFieldObject() const {
414 ExprObjectKind OK = getObjectKind();
415 return (OK == OK_Ordinary || OK == OK_BitField);
416 }
417
418 /// setValueKind - Set the value kind produced by this expression.
setValueKind(ExprValueKind Cat)419 void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
420
421 /// setObjectKind - Set the object kind produced by this expression.
setObjectKind(ExprObjectKind Cat)422 void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
423
424 private:
425 Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
426
427 public:
428
429 /// \brief Returns true if this expression is a gl-value that
430 /// potentially refers to a bit-field.
431 ///
432 /// In C++, whether a gl-value refers to a bitfield is essentially
433 /// an aspect of the value-kind type system.
refersToBitField()434 bool refersToBitField() const { return getObjectKind() == OK_BitField; }
435
436 /// \brief If this expression refers to a bit-field, retrieve the
437 /// declaration of that bit-field.
438 ///
439 /// Note that this returns a non-null pointer in subtly different
440 /// places than refersToBitField returns true. In particular, this can
441 /// return a non-null pointer even for r-values loaded from
442 /// bit-fields, but it will return null for a conditional bit-field.
443 FieldDecl *getSourceBitField();
444
getSourceBitField()445 const FieldDecl *getSourceBitField() const {
446 return const_cast<Expr*>(this)->getSourceBitField();
447 }
448
449 /// \brief If this expression is an l-value for an Objective C
450 /// property, find the underlying property reference expression.
451 const ObjCPropertyRefExpr *getObjCProperty() const;
452
453 /// \brief Check if this expression is the ObjC 'self' implicit parameter.
454 bool isObjCSelfExpr() const;
455
456 /// \brief Returns whether this expression refers to a vector element.
457 bool refersToVectorElement() const;
458
459 /// \brief Returns whether this expression has a placeholder type.
hasPlaceholderType()460 bool hasPlaceholderType() const {
461 return getType()->isPlaceholderType();
462 }
463
464 /// \brief Returns whether this expression has a specific placeholder type.
hasPlaceholderType(BuiltinType::Kind K)465 bool hasPlaceholderType(BuiltinType::Kind K) const {
466 assert(BuiltinType::isPlaceholderTypeKind(K));
467 if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType()))
468 return BT->getKind() == K;
469 return false;
470 }
471
472 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
473 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
474 /// but also int expressions which are produced by things like comparisons in
475 /// C.
476 bool isKnownToHaveBooleanValue() const;
477
478 /// isIntegerConstantExpr - Return true if this expression is a valid integer
479 /// constant expression, and, if so, return its value in Result. If not a
480 /// valid i-c-e, return false and fill in Loc (if specified) with the location
481 /// of the invalid expression.
482 ///
483 /// Note: This does not perform the implicit conversions required by C++11
484 /// [expr.const]p5.
485 bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx,
486 SourceLocation *Loc = nullptr,
487 bool isEvaluated = true) const;
488 bool isIntegerConstantExpr(const ASTContext &Ctx,
489 SourceLocation *Loc = nullptr) const;
490
491 /// isCXX98IntegralConstantExpr - Return true if this expression is an
492 /// integral constant expression in C++98. Can only be used in C++.
493 bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const;
494
495 /// isCXX11ConstantExpr - Return true if this expression is a constant
496 /// expression in C++11. Can only be used in C++.
497 ///
498 /// Note: This does not perform the implicit conversions required by C++11
499 /// [expr.const]p5.
500 bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr,
501 SourceLocation *Loc = nullptr) const;
502
503 /// isPotentialConstantExpr - Return true if this function's definition
504 /// might be usable in a constant expression in C++11, if it were marked
505 /// constexpr. Return false if the function can never produce a constant
506 /// expression, along with diagnostics describing why not.
507 static bool isPotentialConstantExpr(const FunctionDecl *FD,
508 SmallVectorImpl<
509 PartialDiagnosticAt> &Diags);
510
511 /// isPotentialConstantExprUnevaluted - Return true if this expression might
512 /// be usable in a constant expression in C++11 in an unevaluated context, if
513 /// it were in function FD marked constexpr. Return false if the function can
514 /// never produce a constant expression, along with diagnostics describing
515 /// why not.
516 static bool isPotentialConstantExprUnevaluated(Expr *E,
517 const FunctionDecl *FD,
518 SmallVectorImpl<
519 PartialDiagnosticAt> &Diags);
520
521 /// isConstantInitializer - Returns true if this expression can be emitted to
522 /// IR as a constant, and thus can be used as a constant initializer in C.
523 /// If this expression is not constant and Culprit is non-null,
524 /// it is used to store the address of first non constant expr.
525 bool isConstantInitializer(ASTContext &Ctx, bool ForRef,
526 const Expr **Culprit = nullptr) const;
527
528 /// EvalStatus is a struct with detailed info about an evaluation in progress.
529 struct EvalStatus {
530 /// HasSideEffects - Whether the evaluated expression has side effects.
531 /// For example, (f() && 0) can be folded, but it still has side effects.
532 bool HasSideEffects;
533
534 /// Diag - If this is non-null, it will be filled in with a stack of notes
535 /// indicating why evaluation failed (or why it failed to produce a constant
536 /// expression).
537 /// If the expression is unfoldable, the notes will indicate why it's not
538 /// foldable. If the expression is foldable, but not a constant expression,
539 /// the notes will describes why it isn't a constant expression. If the
540 /// expression *is* a constant expression, no notes will be produced.
541 SmallVectorImpl<PartialDiagnosticAt> *Diag;
542
EvalStatusEvalStatus543 EvalStatus() : HasSideEffects(false), Diag(nullptr) {}
544
545 // hasSideEffects - Return true if the evaluated expression has
546 // side effects.
hasSideEffectsEvalStatus547 bool hasSideEffects() const {
548 return HasSideEffects;
549 }
550 };
551
552 /// EvalResult is a struct with detailed info about an evaluated expression.
553 struct EvalResult : EvalStatus {
554 /// Val - This is the value the expression can be folded to.
555 APValue Val;
556
557 // isGlobalLValue - Return true if the evaluated lvalue expression
558 // is global.
559 bool isGlobalLValue() const;
560 };
561
562 /// EvaluateAsRValue - Return true if this is a constant which we can fold to
563 /// an rvalue using any crazy technique (that has nothing to do with language
564 /// standards) that we want to, even if the expression has side-effects. If
565 /// this function returns true, it returns the folded constant in Result. If
566 /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
567 /// applied.
568 bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const;
569
570 /// EvaluateAsBooleanCondition - Return true if this is a constant
571 /// which we we can fold and convert to a boolean condition using
572 /// any crazy technique that we want to, even if the expression has
573 /// side-effects.
574 bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const;
575
576 enum SideEffectsKind { SE_NoSideEffects, SE_AllowSideEffects };
577
578 /// EvaluateAsInt - Return true if this is a constant which we can fold and
579 /// convert to an integer, using any crazy technique that we want to.
580 bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx,
581 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
582
583 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
584 /// constant folded without side-effects, but discard the result.
585 bool isEvaluatable(const ASTContext &Ctx) const;
586
587 /// HasSideEffects - This routine returns true for all those expressions
588 /// which have any effect other than producing a value. Example is a function
589 /// call, volatile variable read, or throwing an exception. If
590 /// IncludePossibleEffects is false, this call treats certain expressions with
591 /// potential side effects (such as function call-like expressions,
592 /// instantiation-dependent expressions, or invocations from a macro) as not
593 /// having side effects.
594 bool HasSideEffects(const ASTContext &Ctx,
595 bool IncludePossibleEffects = true) const;
596
597 /// \brief Determine whether this expression involves a call to any function
598 /// that is not trivial.
599 bool hasNonTrivialCall(ASTContext &Ctx);
600
601 /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
602 /// integer. This must be called on an expression that constant folds to an
603 /// integer.
604 llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx,
605 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
606
607 void EvaluateForOverflow(const ASTContext &Ctx) const;
608
609 /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
610 /// lvalue with link time known address, with no side-effects.
611 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const;
612
613 /// EvaluateAsInitializer - Evaluate an expression as if it were the
614 /// initializer of the given declaration. Returns true if the initializer
615 /// can be folded to a constant, and produces any relevant notes. In C++11,
616 /// notes will be produced if the expression is not a constant expression.
617 bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx,
618 const VarDecl *VD,
619 SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
620
621 /// EvaluateWithSubstitution - Evaluate an expression as if from the context
622 /// of a call to the given function with the given arguments, inside an
623 /// unevaluated context. Returns true if the expression could be folded to a
624 /// constant.
625 bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
626 const FunctionDecl *Callee,
627 ArrayRef<const Expr*> Args) const;
628
629 /// \brief Enumeration used to describe the kind of Null pointer constant
630 /// returned from \c isNullPointerConstant().
631 enum NullPointerConstantKind {
632 /// \brief Expression is not a Null pointer constant.
633 NPCK_NotNull = 0,
634
635 /// \brief Expression is a Null pointer constant built from a zero integer
636 /// expression that is not a simple, possibly parenthesized, zero literal.
637 /// C++ Core Issue 903 will classify these expressions as "not pointers"
638 /// once it is adopted.
639 /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
640 NPCK_ZeroExpression,
641
642 /// \brief Expression is a Null pointer constant built from a literal zero.
643 NPCK_ZeroLiteral,
644
645 /// \brief Expression is a C++11 nullptr.
646 NPCK_CXX11_nullptr,
647
648 /// \brief Expression is a GNU-style __null constant.
649 NPCK_GNUNull
650 };
651
652 /// \brief Enumeration used to describe how \c isNullPointerConstant()
653 /// should cope with value-dependent expressions.
654 enum NullPointerConstantValueDependence {
655 /// \brief Specifies that the expression should never be value-dependent.
656 NPC_NeverValueDependent = 0,
657
658 /// \brief Specifies that a value-dependent expression of integral or
659 /// dependent type should be considered a null pointer constant.
660 NPC_ValueDependentIsNull,
661
662 /// \brief Specifies that a value-dependent expression should be considered
663 /// to never be a null pointer constant.
664 NPC_ValueDependentIsNotNull
665 };
666
667 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
668 /// a Null pointer constant. The return value can further distinguish the
669 /// kind of NULL pointer constant that was detected.
670 NullPointerConstantKind isNullPointerConstant(
671 ASTContext &Ctx,
672 NullPointerConstantValueDependence NPC) const;
673
674 /// isOBJCGCCandidate - Return true if this expression may be used in a read/
675 /// write barrier.
676 bool isOBJCGCCandidate(ASTContext &Ctx) const;
677
678 /// \brief Returns true if this expression is a bound member function.
679 bool isBoundMemberFunction(ASTContext &Ctx) const;
680
681 /// \brief Given an expression of bound-member type, find the type
682 /// of the member. Returns null if this is an *overloaded* bound
683 /// member expression.
684 static QualType findBoundMemberType(const Expr *expr);
685
686 /// IgnoreImpCasts - Skip past any implicit casts which might
687 /// surround this expression. Only skips ImplicitCastExprs.
688 Expr *IgnoreImpCasts() LLVM_READONLY;
689
690 /// IgnoreImplicit - Skip past any implicit AST nodes which might
691 /// surround this expression.
IgnoreImplicit()692 Expr *IgnoreImplicit() LLVM_READONLY {
693 return cast<Expr>(Stmt::IgnoreImplicit());
694 }
695
IgnoreImplicit()696 const Expr *IgnoreImplicit() const LLVM_READONLY {
697 return const_cast<Expr*>(this)->IgnoreImplicit();
698 }
699
700 /// IgnoreParens - Ignore parentheses. If this Expr is a ParenExpr, return
701 /// its subexpression. If that subexpression is also a ParenExpr,
702 /// then this method recursively returns its subexpression, and so forth.
703 /// Otherwise, the method returns the current Expr.
704 Expr *IgnoreParens() LLVM_READONLY;
705
706 /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
707 /// or CastExprs, returning their operand.
708 Expr *IgnoreParenCasts() LLVM_READONLY;
709
710 /// Ignore casts. Strip off any CastExprs, returning their operand.
711 Expr *IgnoreCasts() LLVM_READONLY;
712
713 /// IgnoreParenImpCasts - Ignore parentheses and implicit casts. Strip off
714 /// any ParenExpr or ImplicitCastExprs, returning their operand.
715 Expr *IgnoreParenImpCasts() LLVM_READONLY;
716
717 /// IgnoreConversionOperator - Ignore conversion operator. If this Expr is a
718 /// call to a conversion operator, return the argument.
719 Expr *IgnoreConversionOperator() LLVM_READONLY;
720
IgnoreConversionOperator()721 const Expr *IgnoreConversionOperator() const LLVM_READONLY {
722 return const_cast<Expr*>(this)->IgnoreConversionOperator();
723 }
724
IgnoreParenImpCasts()725 const Expr *IgnoreParenImpCasts() const LLVM_READONLY {
726 return const_cast<Expr*>(this)->IgnoreParenImpCasts();
727 }
728
729 /// Ignore parentheses and lvalue casts. Strip off any ParenExpr and
730 /// CastExprs that represent lvalue casts, returning their operand.
731 Expr *IgnoreParenLValueCasts() LLVM_READONLY;
732
IgnoreParenLValueCasts()733 const Expr *IgnoreParenLValueCasts() const LLVM_READONLY {
734 return const_cast<Expr*>(this)->IgnoreParenLValueCasts();
735 }
736
737 /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
738 /// value (including ptr->int casts of the same size). Strip off any
739 /// ParenExpr or CastExprs, returning their operand.
740 Expr *IgnoreParenNoopCasts(ASTContext &Ctx) LLVM_READONLY;
741
742 /// Ignore parentheses and derived-to-base casts.
743 Expr *ignoreParenBaseCasts() LLVM_READONLY;
744
ignoreParenBaseCasts()745 const Expr *ignoreParenBaseCasts() const LLVM_READONLY {
746 return const_cast<Expr*>(this)->ignoreParenBaseCasts();
747 }
748
749 /// \brief Determine whether this expression is a default function argument.
750 ///
751 /// Default arguments are implicitly generated in the abstract syntax tree
752 /// by semantic analysis for function calls, object constructions, etc. in
753 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
754 /// this routine also looks through any implicit casts to determine whether
755 /// the expression is a default argument.
756 bool isDefaultArgument() const;
757
758 /// \brief Determine whether the result of this expression is a
759 /// temporary object of the given class type.
760 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
761
762 /// \brief Whether this expression is an implicit reference to 'this' in C++.
763 bool isImplicitCXXThis() const;
764
IgnoreImpCasts()765 const Expr *IgnoreImpCasts() const LLVM_READONLY {
766 return const_cast<Expr*>(this)->IgnoreImpCasts();
767 }
IgnoreParens()768 const Expr *IgnoreParens() const LLVM_READONLY {
769 return const_cast<Expr*>(this)->IgnoreParens();
770 }
IgnoreParenCasts()771 const Expr *IgnoreParenCasts() const LLVM_READONLY {
772 return const_cast<Expr*>(this)->IgnoreParenCasts();
773 }
774 /// Strip off casts, but keep parentheses.
IgnoreCasts()775 const Expr *IgnoreCasts() const LLVM_READONLY {
776 return const_cast<Expr*>(this)->IgnoreCasts();
777 }
778
IgnoreParenNoopCasts(ASTContext & Ctx)779 const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const LLVM_READONLY {
780 return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx);
781 }
782
783 static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs);
784
785 /// \brief For an expression of class type or pointer to class type,
786 /// return the most derived class decl the expression is known to refer to.
787 ///
788 /// If this expression is a cast, this method looks through it to find the
789 /// most derived decl that can be inferred from the expression.
790 /// This is valid because derived-to-base conversions have undefined
791 /// behavior if the object isn't dynamically of the derived type.
792 const CXXRecordDecl *getBestDynamicClassType() const;
793
794 /// Walk outwards from an expression we want to bind a reference to and
795 /// find the expression whose lifetime needs to be extended. Record
796 /// the LHSs of comma expressions and adjustments needed along the path.
797 const Expr *skipRValueSubobjectAdjustments(
798 SmallVectorImpl<const Expr *> &CommaLHS,
799 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
800
classof(const Stmt * T)801 static bool classof(const Stmt *T) {
802 return T->getStmtClass() >= firstExprConstant &&
803 T->getStmtClass() <= lastExprConstant;
804 }
805 };
806
807
808 //===----------------------------------------------------------------------===//
809 // Primary Expressions.
810 //===----------------------------------------------------------------------===//
811
812 /// OpaqueValueExpr - An expression referring to an opaque object of a
813 /// fixed type and value class. These don't correspond to concrete
814 /// syntax; instead they're used to express operations (usually copy
815 /// operations) on values whose source is generally obvious from
816 /// context.
817 class OpaqueValueExpr : public Expr {
818 friend class ASTStmtReader;
819 Expr *SourceExpr;
820 SourceLocation Loc;
821
822 public:
823 OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
824 ExprObjectKind OK = OK_Ordinary,
825 Expr *SourceExpr = nullptr)
826 : Expr(OpaqueValueExprClass, T, VK, OK,
827 T->isDependentType(),
828 T->isDependentType() ||
829 (SourceExpr && SourceExpr->isValueDependent()),
830 T->isInstantiationDependentType(),
831 false),
832 SourceExpr(SourceExpr), Loc(Loc) {
833 }
834
835 /// Given an expression which invokes a copy constructor --- i.e. a
836 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
837 /// find the OpaqueValueExpr that's the source of the construction.
838 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
839
OpaqueValueExpr(EmptyShell Empty)840 explicit OpaqueValueExpr(EmptyShell Empty)
841 : Expr(OpaqueValueExprClass, Empty) { }
842
843 /// \brief Retrieve the location of this expression.
getLocation()844 SourceLocation getLocation() const { return Loc; }
845
getLocStart()846 SourceLocation getLocStart() const LLVM_READONLY {
847 return SourceExpr ? SourceExpr->getLocStart() : Loc;
848 }
getLocEnd()849 SourceLocation getLocEnd() const LLVM_READONLY {
850 return SourceExpr ? SourceExpr->getLocEnd() : Loc;
851 }
getExprLoc()852 SourceLocation getExprLoc() const LLVM_READONLY {
853 if (SourceExpr) return SourceExpr->getExprLoc();
854 return Loc;
855 }
856
children()857 child_range children() { return child_range(); }
858
859 /// The source expression of an opaque value expression is the
860 /// expression which originally generated the value. This is
861 /// provided as a convenience for analyses that don't wish to
862 /// precisely model the execution behavior of the program.
863 ///
864 /// The source expression is typically set when building the
865 /// expression which binds the opaque value expression in the first
866 /// place.
getSourceExpr()867 Expr *getSourceExpr() const { return SourceExpr; }
868
classof(const Stmt * T)869 static bool classof(const Stmt *T) {
870 return T->getStmtClass() == OpaqueValueExprClass;
871 }
872 };
873
874 /// \brief A reference to a declared variable, function, enum, etc.
875 /// [C99 6.5.1p2]
876 ///
877 /// This encodes all the information about how a declaration is referenced
878 /// within an expression.
879 ///
880 /// There are several optional constructs attached to DeclRefExprs only when
881 /// they apply in order to conserve memory. These are laid out past the end of
882 /// the object, and flags in the DeclRefExprBitfield track whether they exist:
883 ///
884 /// DeclRefExprBits.HasQualifier:
885 /// Specifies when this declaration reference expression has a C++
886 /// nested-name-specifier.
887 /// DeclRefExprBits.HasFoundDecl:
888 /// Specifies when this declaration reference expression has a record of
889 /// a NamedDecl (different from the referenced ValueDecl) which was found
890 /// during name lookup and/or overload resolution.
891 /// DeclRefExprBits.HasTemplateKWAndArgsInfo:
892 /// Specifies when this declaration reference expression has an explicit
893 /// C++ template keyword and/or template argument list.
894 /// DeclRefExprBits.RefersToEnclosingVariableOrCapture
895 /// Specifies when this declaration reference expression (validly)
896 /// refers to an enclosed local or a captured variable.
897 class DeclRefExpr : public Expr {
898 /// \brief The declaration that we are referencing.
899 ValueDecl *D;
900
901 /// \brief The location of the declaration name itself.
902 SourceLocation Loc;
903
904 /// \brief Provides source/type location info for the declaration name
905 /// embedded in D.
906 DeclarationNameLoc DNLoc;
907
908 /// \brief Helper to retrieve the optional NestedNameSpecifierLoc.
getInternalQualifierLoc()909 NestedNameSpecifierLoc &getInternalQualifierLoc() {
910 assert(hasQualifier());
911 return *reinterpret_cast<NestedNameSpecifierLoc *>(this + 1);
912 }
913
914 /// \brief Helper to retrieve the optional NestedNameSpecifierLoc.
getInternalQualifierLoc()915 const NestedNameSpecifierLoc &getInternalQualifierLoc() const {
916 return const_cast<DeclRefExpr *>(this)->getInternalQualifierLoc();
917 }
918
919 /// \brief Test whether there is a distinct FoundDecl attached to the end of
920 /// this DRE.
hasFoundDecl()921 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
922
923 /// \brief Helper to retrieve the optional NamedDecl through which this
924 /// reference occurred.
getInternalFoundDecl()925 NamedDecl *&getInternalFoundDecl() {
926 assert(hasFoundDecl());
927 if (hasQualifier())
928 return *reinterpret_cast<NamedDecl **>(&getInternalQualifierLoc() + 1);
929 return *reinterpret_cast<NamedDecl **>(this + 1);
930 }
931
932 /// \brief Helper to retrieve the optional NamedDecl through which this
933 /// reference occurred.
getInternalFoundDecl()934 NamedDecl *getInternalFoundDecl() const {
935 return const_cast<DeclRefExpr *>(this)->getInternalFoundDecl();
936 }
937
938 DeclRefExpr(const ASTContext &Ctx,
939 NestedNameSpecifierLoc QualifierLoc,
940 SourceLocation TemplateKWLoc,
941 ValueDecl *D, bool RefersToEnlosingVariableOrCapture,
942 const DeclarationNameInfo &NameInfo,
943 NamedDecl *FoundD,
944 const TemplateArgumentListInfo *TemplateArgs,
945 QualType T, ExprValueKind VK);
946
947 /// \brief Construct an empty declaration reference expression.
DeclRefExpr(EmptyShell Empty)948 explicit DeclRefExpr(EmptyShell Empty)
949 : Expr(DeclRefExprClass, Empty) { }
950
951 /// \brief Computes the type- and value-dependence flags for this
952 /// declaration reference expression.
953 void computeDependence(const ASTContext &C);
954
955 public:
956 DeclRefExpr(ValueDecl *D, bool RefersToEnclosingVariableOrCapture, QualType T,
957 ExprValueKind VK, SourceLocation L,
958 const DeclarationNameLoc &LocInfo = DeclarationNameLoc())
Expr(DeclRefExprClass,T,VK,OK_Ordinary,false,false,false,false)959 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
960 D(D), Loc(L), DNLoc(LocInfo) {
961 DeclRefExprBits.HasQualifier = 0;
962 DeclRefExprBits.HasTemplateKWAndArgsInfo = 0;
963 DeclRefExprBits.HasFoundDecl = 0;
964 DeclRefExprBits.HadMultipleCandidates = 0;
965 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
966 RefersToEnclosingVariableOrCapture;
967 computeDependence(D->getASTContext());
968 }
969
970 static DeclRefExpr *
971 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
972 SourceLocation TemplateKWLoc, ValueDecl *D,
973 bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc,
974 QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr,
975 const TemplateArgumentListInfo *TemplateArgs = nullptr);
976
977 static DeclRefExpr *
978 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
979 SourceLocation TemplateKWLoc, ValueDecl *D,
980 bool RefersToEnclosingVariableOrCapture,
981 const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
982 NamedDecl *FoundD = nullptr,
983 const TemplateArgumentListInfo *TemplateArgs = nullptr);
984
985 /// \brief Construct an empty declaration reference expression.
986 static DeclRefExpr *CreateEmpty(const ASTContext &Context,
987 bool HasQualifier,
988 bool HasFoundDecl,
989 bool HasTemplateKWAndArgsInfo,
990 unsigned NumTemplateArgs);
991
getDecl()992 ValueDecl *getDecl() { return D; }
getDecl()993 const ValueDecl *getDecl() const { return D; }
setDecl(ValueDecl * NewD)994 void setDecl(ValueDecl *NewD) { D = NewD; }
995
getNameInfo()996 DeclarationNameInfo getNameInfo() const {
997 return DeclarationNameInfo(getDecl()->getDeclName(), Loc, DNLoc);
998 }
999
getLocation()1000 SourceLocation getLocation() const { return Loc; }
setLocation(SourceLocation L)1001 void setLocation(SourceLocation L) { Loc = L; }
1002 SourceLocation getLocStart() const LLVM_READONLY;
1003 SourceLocation getLocEnd() const LLVM_READONLY;
1004
1005 /// \brief Determine whether this declaration reference was preceded by a
1006 /// C++ nested-name-specifier, e.g., \c N::foo.
hasQualifier()1007 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
1008
1009 /// \brief If the name was qualified, retrieves the nested-name-specifier
1010 /// that precedes the name. Otherwise, returns NULL.
getQualifier()1011 NestedNameSpecifier *getQualifier() const {
1012 if (!hasQualifier())
1013 return nullptr;
1014
1015 return getInternalQualifierLoc().getNestedNameSpecifier();
1016 }
1017
1018 /// \brief If the name was qualified, retrieves the nested-name-specifier
1019 /// that precedes the name, with source-location information.
getQualifierLoc()1020 NestedNameSpecifierLoc getQualifierLoc() const {
1021 if (!hasQualifier())
1022 return NestedNameSpecifierLoc();
1023
1024 return getInternalQualifierLoc();
1025 }
1026
1027 /// \brief Get the NamedDecl through which this reference occurred.
1028 ///
1029 /// This Decl may be different from the ValueDecl actually referred to in the
1030 /// presence of using declarations, etc. It always returns non-NULL, and may
1031 /// simple return the ValueDecl when appropriate.
getFoundDecl()1032 NamedDecl *getFoundDecl() {
1033 return hasFoundDecl() ? getInternalFoundDecl() : D;
1034 }
1035
1036 /// \brief Get the NamedDecl through which this reference occurred.
1037 /// See non-const variant.
getFoundDecl()1038 const NamedDecl *getFoundDecl() const {
1039 return hasFoundDecl() ? getInternalFoundDecl() : D;
1040 }
1041
hasTemplateKWAndArgsInfo()1042 bool hasTemplateKWAndArgsInfo() const {
1043 return DeclRefExprBits.HasTemplateKWAndArgsInfo;
1044 }
1045
1046 /// \brief Return the optional template keyword and arguments info.
getTemplateKWAndArgsInfo()1047 ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() {
1048 if (!hasTemplateKWAndArgsInfo())
1049 return nullptr;
1050
1051 if (hasFoundDecl())
1052 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(
1053 &getInternalFoundDecl() + 1);
1054
1055 if (hasQualifier())
1056 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(
1057 &getInternalQualifierLoc() + 1);
1058
1059 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(this + 1);
1060 }
1061
1062 /// \brief Return the optional template keyword and arguments info.
getTemplateKWAndArgsInfo()1063 const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const {
1064 return const_cast<DeclRefExpr*>(this)->getTemplateKWAndArgsInfo();
1065 }
1066
1067 /// \brief Retrieve the location of the template keyword preceding
1068 /// this name, if any.
getTemplateKeywordLoc()1069 SourceLocation getTemplateKeywordLoc() const {
1070 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1071 return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc();
1072 }
1073
1074 /// \brief Retrieve the location of the left angle bracket starting the
1075 /// explicit template argument list following the name, if any.
getLAngleLoc()1076 SourceLocation getLAngleLoc() const {
1077 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1078 return getTemplateKWAndArgsInfo()->LAngleLoc;
1079 }
1080
1081 /// \brief Retrieve the location of the right angle bracket ending the
1082 /// explicit template argument list following the name, if any.
getRAngleLoc()1083 SourceLocation getRAngleLoc() const {
1084 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1085 return getTemplateKWAndArgsInfo()->RAngleLoc;
1086 }
1087
1088 /// \brief Determines whether the name in this declaration reference
1089 /// was preceded by the template keyword.
hasTemplateKeyword()1090 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
1091
1092 /// \brief Determines whether this declaration reference was followed by an
1093 /// explicit template argument list.
hasExplicitTemplateArgs()1094 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
1095
1096 /// \brief Retrieve the explicit template argument list that followed the
1097 /// member template name.
getExplicitTemplateArgs()1098 ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
1099 assert(hasExplicitTemplateArgs());
1100 return *getTemplateKWAndArgsInfo();
1101 }
1102
1103 /// \brief Retrieve the explicit template argument list that followed the
1104 /// member template name.
getExplicitTemplateArgs()1105 const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
1106 return const_cast<DeclRefExpr *>(this)->getExplicitTemplateArgs();
1107 }
1108
1109 /// \brief Retrieves the optional explicit template arguments.
1110 /// This points to the same data as getExplicitTemplateArgs(), but
1111 /// returns null if there are no explicit template arguments.
getOptionalExplicitTemplateArgs()1112 const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const {
1113 if (!hasExplicitTemplateArgs()) return nullptr;
1114 return &getExplicitTemplateArgs();
1115 }
1116
1117 /// \brief Copies the template arguments (if present) into the given
1118 /// structure.
copyTemplateArgumentsInto(TemplateArgumentListInfo & List)1119 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1120 if (hasExplicitTemplateArgs())
1121 getExplicitTemplateArgs().copyInto(List);
1122 }
1123
1124 /// \brief Retrieve the template arguments provided as part of this
1125 /// template-id.
getTemplateArgs()1126 const TemplateArgumentLoc *getTemplateArgs() const {
1127 if (!hasExplicitTemplateArgs())
1128 return nullptr;
1129
1130 return getExplicitTemplateArgs().getTemplateArgs();
1131 }
1132
1133 /// \brief Retrieve the number of template arguments provided as part of this
1134 /// template-id.
getNumTemplateArgs()1135 unsigned getNumTemplateArgs() const {
1136 if (!hasExplicitTemplateArgs())
1137 return 0;
1138
1139 return getExplicitTemplateArgs().NumTemplateArgs;
1140 }
1141
1142 /// \brief Returns true if this expression refers to a function that
1143 /// was resolved from an overloaded set having size greater than 1.
hadMultipleCandidates()1144 bool hadMultipleCandidates() const {
1145 return DeclRefExprBits.HadMultipleCandidates;
1146 }
1147 /// \brief Sets the flag telling whether this expression refers to
1148 /// a function that was resolved from an overloaded set having size
1149 /// greater than 1.
1150 void setHadMultipleCandidates(bool V = true) {
1151 DeclRefExprBits.HadMultipleCandidates = V;
1152 }
1153
1154 /// \brief Does this DeclRefExpr refer to an enclosing local or a captured
1155 /// variable?
refersToEnclosingVariableOrCapture()1156 bool refersToEnclosingVariableOrCapture() const {
1157 return DeclRefExprBits.RefersToEnclosingVariableOrCapture;
1158 }
1159
classof(const Stmt * T)1160 static bool classof(const Stmt *T) {
1161 return T->getStmtClass() == DeclRefExprClass;
1162 }
1163
1164 // Iterators
children()1165 child_range children() { return child_range(); }
1166
1167 friend class ASTStmtReader;
1168 friend class ASTStmtWriter;
1169 };
1170
1171 /// \brief [C99 6.4.2.2] - A predefined identifier such as __func__.
1172 class PredefinedExpr : public Expr {
1173 public:
1174 enum IdentType {
1175 Func,
1176 Function,
1177 LFunction, // Same as Function, but as wide string.
1178 FuncDName,
1179 FuncSig,
1180 PrettyFunction,
1181 /// \brief The same as PrettyFunction, except that the
1182 /// 'virtual' keyword is omitted for virtual member functions.
1183 PrettyFunctionNoVirtual
1184 };
1185
1186 private:
1187 SourceLocation Loc;
1188 IdentType Type;
1189 Stmt *FnName;
1190
1191 public:
1192 PredefinedExpr(SourceLocation L, QualType FNTy, IdentType IT,
1193 StringLiteral *SL);
1194
1195 /// \brief Construct an empty predefined expression.
PredefinedExpr(EmptyShell Empty)1196 explicit PredefinedExpr(EmptyShell Empty)
1197 : Expr(PredefinedExprClass, Empty), Loc(), Type(Func), FnName(nullptr) {}
1198
getIdentType()1199 IdentType getIdentType() const { return Type; }
1200
getLocation()1201 SourceLocation getLocation() const { return Loc; }
setLocation(SourceLocation L)1202 void setLocation(SourceLocation L) { Loc = L; }
1203
1204 StringLiteral *getFunctionName();
getFunctionName()1205 const StringLiteral *getFunctionName() const {
1206 return const_cast<PredefinedExpr *>(this)->getFunctionName();
1207 }
1208
1209 static StringRef getIdentTypeName(IdentType IT);
1210 static std::string ComputeName(IdentType IT, const Decl *CurrentDecl);
1211
getLocStart()1212 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
getLocEnd()1213 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1214
classof(const Stmt * T)1215 static bool classof(const Stmt *T) {
1216 return T->getStmtClass() == PredefinedExprClass;
1217 }
1218
1219 // Iterators
children()1220 child_range children() { return child_range(&FnName, &FnName + 1); }
1221
1222 friend class ASTStmtReader;
1223 };
1224
1225 /// \brief Used by IntegerLiteral/FloatingLiteral to store the numeric without
1226 /// leaking memory.
1227 ///
1228 /// For large floats/integers, APFloat/APInt will allocate memory from the heap
1229 /// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator
1230 /// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
1231 /// the APFloat/APInt values will never get freed. APNumericStorage uses
1232 /// ASTContext's allocator for memory allocation.
1233 class APNumericStorage {
1234 union {
1235 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
1236 uint64_t *pVal; ///< Used to store the >64 bits integer value.
1237 };
1238 unsigned BitWidth;
1239
hasAllocation()1240 bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
1241
1242 APNumericStorage(const APNumericStorage &) LLVM_DELETED_FUNCTION;
1243 void operator=(const APNumericStorage &) LLVM_DELETED_FUNCTION;
1244
1245 protected:
APNumericStorage()1246 APNumericStorage() : VAL(0), BitWidth(0) { }
1247
getIntValue()1248 llvm::APInt getIntValue() const {
1249 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1250 if (NumWords > 1)
1251 return llvm::APInt(BitWidth, NumWords, pVal);
1252 else
1253 return llvm::APInt(BitWidth, VAL);
1254 }
1255 void setIntValue(const ASTContext &C, const llvm::APInt &Val);
1256 };
1257
1258 class APIntStorage : private APNumericStorage {
1259 public:
getValue()1260 llvm::APInt getValue() const { return getIntValue(); }
setValue(const ASTContext & C,const llvm::APInt & Val)1261 void setValue(const ASTContext &C, const llvm::APInt &Val) {
1262 setIntValue(C, Val);
1263 }
1264 };
1265
1266 class APFloatStorage : private APNumericStorage {
1267 public:
getValue(const llvm::fltSemantics & Semantics)1268 llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const {
1269 return llvm::APFloat(Semantics, getIntValue());
1270 }
setValue(const ASTContext & C,const llvm::APFloat & Val)1271 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1272 setIntValue(C, Val.bitcastToAPInt());
1273 }
1274 };
1275
1276 class IntegerLiteral : public Expr, public APIntStorage {
1277 SourceLocation Loc;
1278
1279 /// \brief Construct an empty integer literal.
IntegerLiteral(EmptyShell Empty)1280 explicit IntegerLiteral(EmptyShell Empty)
1281 : Expr(IntegerLiteralClass, Empty) { }
1282
1283 public:
1284 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1285 // or UnsignedLongLongTy
1286 IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1287 SourceLocation l);
1288
1289 /// \brief Returns a new integer literal with value 'V' and type 'type'.
1290 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1291 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1292 /// \param V - the value that the returned integer literal contains.
1293 static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V,
1294 QualType type, SourceLocation l);
1295 /// \brief Returns a new empty integer literal.
1296 static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty);
1297
getLocStart()1298 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
getLocEnd()1299 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1300
1301 /// \brief Retrieve the location of the literal.
getLocation()1302 SourceLocation getLocation() const { return Loc; }
1303
setLocation(SourceLocation Location)1304 void setLocation(SourceLocation Location) { Loc = Location; }
1305
classof(const Stmt * T)1306 static bool classof(const Stmt *T) {
1307 return T->getStmtClass() == IntegerLiteralClass;
1308 }
1309
1310 // Iterators
children()1311 child_range children() { return child_range(); }
1312 };
1313
1314 class CharacterLiteral : public Expr {
1315 public:
1316 enum CharacterKind {
1317 Ascii,
1318 Wide,
1319 UTF16,
1320 UTF32
1321 };
1322
1323 private:
1324 unsigned Value;
1325 SourceLocation Loc;
1326 public:
1327 // type should be IntTy
CharacterLiteral(unsigned value,CharacterKind kind,QualType type,SourceLocation l)1328 CharacterLiteral(unsigned value, CharacterKind kind, QualType type,
1329 SourceLocation l)
1330 : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
1331 false, false),
1332 Value(value), Loc(l) {
1333 CharacterLiteralBits.Kind = kind;
1334 }
1335
1336 /// \brief Construct an empty character literal.
CharacterLiteral(EmptyShell Empty)1337 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1338
getLocation()1339 SourceLocation getLocation() const { return Loc; }
getKind()1340 CharacterKind getKind() const {
1341 return static_cast<CharacterKind>(CharacterLiteralBits.Kind);
1342 }
1343
getLocStart()1344 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
getLocEnd()1345 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1346
getValue()1347 unsigned getValue() const { return Value; }
1348
setLocation(SourceLocation Location)1349 void setLocation(SourceLocation Location) { Loc = Location; }
setKind(CharacterKind kind)1350 void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; }
setValue(unsigned Val)1351 void setValue(unsigned Val) { Value = Val; }
1352
classof(const Stmt * T)1353 static bool classof(const Stmt *T) {
1354 return T->getStmtClass() == CharacterLiteralClass;
1355 }
1356
1357 // Iterators
children()1358 child_range children() { return child_range(); }
1359 };
1360
1361 class FloatingLiteral : public Expr, private APFloatStorage {
1362 SourceLocation Loc;
1363
1364 FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
1365 QualType Type, SourceLocation L);
1366
1367 /// \brief Construct an empty floating-point literal.
1368 explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
1369
1370 public:
1371 static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
1372 bool isexact, QualType Type, SourceLocation L);
1373 static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
1374
getValue()1375 llvm::APFloat getValue() const {
1376 return APFloatStorage::getValue(getSemantics());
1377 }
setValue(const ASTContext & C,const llvm::APFloat & Val)1378 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1379 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics");
1380 APFloatStorage::setValue(C, Val);
1381 }
1382
1383 /// Get a raw enumeration value representing the floating-point semantics of
1384 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
getRawSemantics()1385 APFloatSemantics getRawSemantics() const {
1386 return static_cast<APFloatSemantics>(FloatingLiteralBits.Semantics);
1387 }
1388
1389 /// Set the raw enumeration value representing the floating-point semantics of
1390 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
setRawSemantics(APFloatSemantics Sem)1391 void setRawSemantics(APFloatSemantics Sem) {
1392 FloatingLiteralBits.Semantics = Sem;
1393 }
1394
1395 /// Return the APFloat semantics this literal uses.
1396 const llvm::fltSemantics &getSemantics() const;
1397
1398 /// Set the APFloat semantics this literal uses.
1399 void setSemantics(const llvm::fltSemantics &Sem);
1400
isExact()1401 bool isExact() const { return FloatingLiteralBits.IsExact; }
setExact(bool E)1402 void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
1403
1404 /// getValueAsApproximateDouble - This returns the value as an inaccurate
1405 /// double. Note that this may cause loss of precision, but is useful for
1406 /// debugging dumps, etc.
1407 double getValueAsApproximateDouble() const;
1408
getLocation()1409 SourceLocation getLocation() const { return Loc; }
setLocation(SourceLocation L)1410 void setLocation(SourceLocation L) { Loc = L; }
1411
getLocStart()1412 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
getLocEnd()1413 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1414
classof(const Stmt * T)1415 static bool classof(const Stmt *T) {
1416 return T->getStmtClass() == FloatingLiteralClass;
1417 }
1418
1419 // Iterators
children()1420 child_range children() { return child_range(); }
1421 };
1422
1423 /// ImaginaryLiteral - We support imaginary integer and floating point literals,
1424 /// like "1.0i". We represent these as a wrapper around FloatingLiteral and
1425 /// IntegerLiteral classes. Instances of this class always have a Complex type
1426 /// whose element type matches the subexpression.
1427 ///
1428 class ImaginaryLiteral : public Expr {
1429 Stmt *Val;
1430 public:
ImaginaryLiteral(Expr * val,QualType Ty)1431 ImaginaryLiteral(Expr *val, QualType Ty)
1432 : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false,
1433 false, false),
1434 Val(val) {}
1435
1436 /// \brief Build an empty imaginary literal.
ImaginaryLiteral(EmptyShell Empty)1437 explicit ImaginaryLiteral(EmptyShell Empty)
1438 : Expr(ImaginaryLiteralClass, Empty) { }
1439
getSubExpr()1440 const Expr *getSubExpr() const { return cast<Expr>(Val); }
getSubExpr()1441 Expr *getSubExpr() { return cast<Expr>(Val); }
setSubExpr(Expr * E)1442 void setSubExpr(Expr *E) { Val = E; }
1443
getLocStart()1444 SourceLocation getLocStart() const LLVM_READONLY { return Val->getLocStart(); }
getLocEnd()1445 SourceLocation getLocEnd() const LLVM_READONLY { return Val->getLocEnd(); }
1446
classof(const Stmt * T)1447 static bool classof(const Stmt *T) {
1448 return T->getStmtClass() == ImaginaryLiteralClass;
1449 }
1450
1451 // Iterators
children()1452 child_range children() { return child_range(&Val, &Val+1); }
1453 };
1454
1455 /// StringLiteral - This represents a string literal expression, e.g. "foo"
1456 /// or L"bar" (wide strings). The actual string is returned by getBytes()
1457 /// is NOT null-terminated, and the length of the string is determined by
1458 /// calling getByteLength(). The C type for a string is always a
1459 /// ConstantArrayType. In C++, the char type is const qualified, in C it is
1460 /// not.
1461 ///
1462 /// Note that strings in C can be formed by concatenation of multiple string
1463 /// literal pptokens in translation phase #6. This keeps track of the locations
1464 /// of each of these pieces.
1465 ///
1466 /// Strings in C can also be truncated and extended by assigning into arrays,
1467 /// e.g. with constructs like:
1468 /// char X[2] = "foobar";
1469 /// In this case, getByteLength() will return 6, but the string literal will
1470 /// have type "char[2]".
1471 class StringLiteral : public Expr {
1472 public:
1473 enum StringKind {
1474 Ascii,
1475 Wide,
1476 UTF8,
1477 UTF16,
1478 UTF32
1479 };
1480
1481 private:
1482 friend class ASTStmtReader;
1483
1484 union {
1485 const char *asChar;
1486 const uint16_t *asUInt16;
1487 const uint32_t *asUInt32;
1488 } StrData;
1489 unsigned Length;
1490 unsigned CharByteWidth : 4;
1491 unsigned Kind : 3;
1492 unsigned IsPascal : 1;
1493 unsigned NumConcatenated;
1494 SourceLocation TokLocs[1];
1495
StringLiteral(QualType Ty)1496 StringLiteral(QualType Ty) :
1497 Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
1498 false) {}
1499
1500 static int mapCharByteWidth(TargetInfo const &target,StringKind k);
1501
1502 public:
1503 /// This is the "fully general" constructor that allows representation of
1504 /// strings formed from multiple concatenated tokens.
1505 static StringLiteral *Create(const ASTContext &C, StringRef Str,
1506 StringKind Kind, bool Pascal, QualType Ty,
1507 const SourceLocation *Loc, unsigned NumStrs);
1508
1509 /// Simple constructor for string literals made from one token.
Create(const ASTContext & C,StringRef Str,StringKind Kind,bool Pascal,QualType Ty,SourceLocation Loc)1510 static StringLiteral *Create(const ASTContext &C, StringRef Str,
1511 StringKind Kind, bool Pascal, QualType Ty,
1512 SourceLocation Loc) {
1513 return Create(C, Str, Kind, Pascal, Ty, &Loc, 1);
1514 }
1515
1516 /// \brief Construct an empty string literal.
1517 static StringLiteral *CreateEmpty(const ASTContext &C, unsigned NumStrs);
1518
getString()1519 StringRef getString() const {
1520 assert(CharByteWidth==1
1521 && "This function is used in places that assume strings use char");
1522 return StringRef(StrData.asChar, getByteLength());
1523 }
1524
1525 /// Allow access to clients that need the byte representation, such as
1526 /// ASTWriterStmt::VisitStringLiteral().
getBytes()1527 StringRef getBytes() const {
1528 // FIXME: StringRef may not be the right type to use as a result for this.
1529 if (CharByteWidth == 1)
1530 return StringRef(StrData.asChar, getByteLength());
1531 if (CharByteWidth == 4)
1532 return StringRef(reinterpret_cast<const char*>(StrData.asUInt32),
1533 getByteLength());
1534 assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1535 return StringRef(reinterpret_cast<const char*>(StrData.asUInt16),
1536 getByteLength());
1537 }
1538
1539 void outputString(raw_ostream &OS) const;
1540
getCodeUnit(size_t i)1541 uint32_t getCodeUnit(size_t i) const {
1542 assert(i < Length && "out of bounds access");
1543 if (CharByteWidth == 1)
1544 return static_cast<unsigned char>(StrData.asChar[i]);
1545 if (CharByteWidth == 4)
1546 return StrData.asUInt32[i];
1547 assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1548 return StrData.asUInt16[i];
1549 }
1550
getByteLength()1551 unsigned getByteLength() const { return CharByteWidth*Length; }
getLength()1552 unsigned getLength() const { return Length; }
getCharByteWidth()1553 unsigned getCharByteWidth() const { return CharByteWidth; }
1554
1555 /// \brief Sets the string data to the given string data.
1556 void setString(const ASTContext &C, StringRef Str,
1557 StringKind Kind, bool IsPascal);
1558
getKind()1559 StringKind getKind() const { return static_cast<StringKind>(Kind); }
1560
1561
isAscii()1562 bool isAscii() const { return Kind == Ascii; }
isWide()1563 bool isWide() const { return Kind == Wide; }
isUTF8()1564 bool isUTF8() const { return Kind == UTF8; }
isUTF16()1565 bool isUTF16() const { return Kind == UTF16; }
isUTF32()1566 bool isUTF32() const { return Kind == UTF32; }
isPascal()1567 bool isPascal() const { return IsPascal; }
1568
containsNonAsciiOrNull()1569 bool containsNonAsciiOrNull() const {
1570 StringRef Str = getString();
1571 for (unsigned i = 0, e = Str.size(); i != e; ++i)
1572 if (!isASCII(Str[i]) || !Str[i])
1573 return true;
1574 return false;
1575 }
1576
1577 /// getNumConcatenated - Get the number of string literal tokens that were
1578 /// concatenated in translation phase #6 to form this string literal.
getNumConcatenated()1579 unsigned getNumConcatenated() const { return NumConcatenated; }
1580
getStrTokenLoc(unsigned TokNum)1581 SourceLocation getStrTokenLoc(unsigned TokNum) const {
1582 assert(TokNum < NumConcatenated && "Invalid tok number");
1583 return TokLocs[TokNum];
1584 }
setStrTokenLoc(unsigned TokNum,SourceLocation L)1585 void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1586 assert(TokNum < NumConcatenated && "Invalid tok number");
1587 TokLocs[TokNum] = L;
1588 }
1589
1590 /// getLocationOfByte - Return a source location that points to the specified
1591 /// byte of this string literal.
1592 ///
1593 /// Strings are amazingly complex. They can be formed from multiple tokens
1594 /// and can have escape sequences in them in addition to the usual trigraph
1595 /// and escaped newline business. This routine handles this complexity.
1596 ///
1597 SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1598 const LangOptions &Features,
1599 const TargetInfo &Target) const;
1600
1601 typedef const SourceLocation *tokloc_iterator;
tokloc_begin()1602 tokloc_iterator tokloc_begin() const { return TokLocs; }
tokloc_end()1603 tokloc_iterator tokloc_end() const { return TokLocs+NumConcatenated; }
1604
getLocStart()1605 SourceLocation getLocStart() const LLVM_READONLY { return TokLocs[0]; }
getLocEnd()1606 SourceLocation getLocEnd() const LLVM_READONLY {
1607 return TokLocs[NumConcatenated - 1];
1608 }
1609
classof(const Stmt * T)1610 static bool classof(const Stmt *T) {
1611 return T->getStmtClass() == StringLiteralClass;
1612 }
1613
1614 // Iterators
children()1615 child_range children() { return child_range(); }
1616 };
1617
1618 /// ParenExpr - This represents a parethesized expression, e.g. "(1)". This
1619 /// AST node is only formed if full location information is requested.
1620 class ParenExpr : public Expr {
1621 SourceLocation L, R;
1622 Stmt *Val;
1623 public:
ParenExpr(SourceLocation l,SourceLocation r,Expr * val)1624 ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
1625 : Expr(ParenExprClass, val->getType(),
1626 val->getValueKind(), val->getObjectKind(),
1627 val->isTypeDependent(), val->isValueDependent(),
1628 val->isInstantiationDependent(),
1629 val->containsUnexpandedParameterPack()),
1630 L(l), R(r), Val(val) {}
1631
1632 /// \brief Construct an empty parenthesized expression.
ParenExpr(EmptyShell Empty)1633 explicit ParenExpr(EmptyShell Empty)
1634 : Expr(ParenExprClass, Empty) { }
1635
getSubExpr()1636 const Expr *getSubExpr() const { return cast<Expr>(Val); }
getSubExpr()1637 Expr *getSubExpr() { return cast<Expr>(Val); }
setSubExpr(Expr * E)1638 void setSubExpr(Expr *E) { Val = E; }
1639
getLocStart()1640 SourceLocation getLocStart() const LLVM_READONLY { return L; }
getLocEnd()1641 SourceLocation getLocEnd() const LLVM_READONLY { return R; }
1642
1643 /// \brief Get the location of the left parentheses '('.
getLParen()1644 SourceLocation getLParen() const { return L; }
setLParen(SourceLocation Loc)1645 void setLParen(SourceLocation Loc) { L = Loc; }
1646
1647 /// \brief Get the location of the right parentheses ')'.
getRParen()1648 SourceLocation getRParen() const { return R; }
setRParen(SourceLocation Loc)1649 void setRParen(SourceLocation Loc) { R = Loc; }
1650
classof(const Stmt * T)1651 static bool classof(const Stmt *T) {
1652 return T->getStmtClass() == ParenExprClass;
1653 }
1654
1655 // Iterators
children()1656 child_range children() { return child_range(&Val, &Val+1); }
1657 };
1658
1659
1660 /// UnaryOperator - This represents the unary-expression's (except sizeof and
1661 /// alignof), the postinc/postdec operators from postfix-expression, and various
1662 /// extensions.
1663 ///
1664 /// Notes on various nodes:
1665 ///
1666 /// Real/Imag - These return the real/imag part of a complex operand. If
1667 /// applied to a non-complex value, the former returns its operand and the
1668 /// later returns zero in the type of the operand.
1669 ///
1670 class UnaryOperator : public Expr {
1671 public:
1672 typedef UnaryOperatorKind Opcode;
1673
1674 private:
1675 unsigned Opc : 5;
1676 SourceLocation Loc;
1677 Stmt *Val;
1678 public:
1679
UnaryOperator(Expr * input,Opcode opc,QualType type,ExprValueKind VK,ExprObjectKind OK,SourceLocation l)1680 UnaryOperator(Expr *input, Opcode opc, QualType type,
1681 ExprValueKind VK, ExprObjectKind OK, SourceLocation l)
1682 : Expr(UnaryOperatorClass, type, VK, OK,
1683 input->isTypeDependent() || type->isDependentType(),
1684 input->isValueDependent(),
1685 (input->isInstantiationDependent() ||
1686 type->isInstantiationDependentType()),
1687 input->containsUnexpandedParameterPack()),
1688 Opc(opc), Loc(l), Val(input) {}
1689
1690 /// \brief Build an empty unary operator.
UnaryOperator(EmptyShell Empty)1691 explicit UnaryOperator(EmptyShell Empty)
1692 : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) { }
1693
getOpcode()1694 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
setOpcode(Opcode O)1695 void setOpcode(Opcode O) { Opc = O; }
1696
getSubExpr()1697 Expr *getSubExpr() const { return cast<Expr>(Val); }
setSubExpr(Expr * E)1698 void setSubExpr(Expr *E) { Val = E; }
1699
1700 /// getOperatorLoc - Return the location of the operator.
getOperatorLoc()1701 SourceLocation getOperatorLoc() const { return Loc; }
setOperatorLoc(SourceLocation L)1702 void setOperatorLoc(SourceLocation L) { Loc = L; }
1703
1704 /// isPostfix - Return true if this is a postfix operation, like x++.
isPostfix(Opcode Op)1705 static bool isPostfix(Opcode Op) {
1706 return Op == UO_PostInc || Op == UO_PostDec;
1707 }
1708
1709 /// isPrefix - Return true if this is a prefix operation, like --x.
isPrefix(Opcode Op)1710 static bool isPrefix(Opcode Op) {
1711 return Op == UO_PreInc || Op == UO_PreDec;
1712 }
1713
isPrefix()1714 bool isPrefix() const { return isPrefix(getOpcode()); }
isPostfix()1715 bool isPostfix() const { return isPostfix(getOpcode()); }
1716
isIncrementOp(Opcode Op)1717 static bool isIncrementOp(Opcode Op) {
1718 return Op == UO_PreInc || Op == UO_PostInc;
1719 }
isIncrementOp()1720 bool isIncrementOp() const {
1721 return isIncrementOp(getOpcode());
1722 }
1723
isDecrementOp(Opcode Op)1724 static bool isDecrementOp(Opcode Op) {
1725 return Op == UO_PreDec || Op == UO_PostDec;
1726 }
isDecrementOp()1727 bool isDecrementOp() const {
1728 return isDecrementOp(getOpcode());
1729 }
1730
isIncrementDecrementOp(Opcode Op)1731 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
isIncrementDecrementOp()1732 bool isIncrementDecrementOp() const {
1733 return isIncrementDecrementOp(getOpcode());
1734 }
1735
isArithmeticOp(Opcode Op)1736 static bool isArithmeticOp(Opcode Op) {
1737 return Op >= UO_Plus && Op <= UO_LNot;
1738 }
isArithmeticOp()1739 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
1740
1741 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1742 /// corresponds to, e.g. "sizeof" or "[pre]++"
1743 static StringRef getOpcodeStr(Opcode Op);
1744
1745 /// \brief Retrieve the unary opcode that corresponds to the given
1746 /// overloaded operator.
1747 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
1748
1749 /// \brief Retrieve the overloaded operator kind that corresponds to
1750 /// the given unary opcode.
1751 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
1752
getLocStart()1753 SourceLocation getLocStart() const LLVM_READONLY {
1754 return isPostfix() ? Val->getLocStart() : Loc;
1755 }
getLocEnd()1756 SourceLocation getLocEnd() const LLVM_READONLY {
1757 return isPostfix() ? Loc : Val->getLocEnd();
1758 }
getExprLoc()1759 SourceLocation getExprLoc() const LLVM_READONLY { return Loc; }
1760
classof(const Stmt * T)1761 static bool classof(const Stmt *T) {
1762 return T->getStmtClass() == UnaryOperatorClass;
1763 }
1764
1765 // Iterators
children()1766 child_range children() { return child_range(&Val, &Val+1); }
1767 };
1768
1769 /// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
1770 /// offsetof(record-type, member-designator). For example, given:
1771 /// @code
1772 /// struct S {
1773 /// float f;
1774 /// double d;
1775 /// };
1776 /// struct T {
1777 /// int i;
1778 /// struct S s[10];
1779 /// };
1780 /// @endcode
1781 /// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
1782
1783 class OffsetOfExpr : public Expr {
1784 public:
1785 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
1786 class OffsetOfNode {
1787 public:
1788 /// \brief The kind of offsetof node we have.
1789 enum Kind {
1790 /// \brief An index into an array.
1791 Array = 0x00,
1792 /// \brief A field.
1793 Field = 0x01,
1794 /// \brief A field in a dependent type, known only by its name.
1795 Identifier = 0x02,
1796 /// \brief An implicit indirection through a C++ base class, when the
1797 /// field found is in a base class.
1798 Base = 0x03
1799 };
1800
1801 private:
1802 enum { MaskBits = 2, Mask = 0x03 };
1803
1804 /// \brief The source range that covers this part of the designator.
1805 SourceRange Range;
1806
1807 /// \brief The data describing the designator, which comes in three
1808 /// different forms, depending on the lower two bits.
1809 /// - An unsigned index into the array of Expr*'s stored after this node
1810 /// in memory, for [constant-expression] designators.
1811 /// - A FieldDecl*, for references to a known field.
1812 /// - An IdentifierInfo*, for references to a field with a given name
1813 /// when the class type is dependent.
1814 /// - A CXXBaseSpecifier*, for references that look at a field in a
1815 /// base class.
1816 uintptr_t Data;
1817
1818 public:
1819 /// \brief Create an offsetof node that refers to an array element.
OffsetOfNode(SourceLocation LBracketLoc,unsigned Index,SourceLocation RBracketLoc)1820 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
1821 SourceLocation RBracketLoc)
1822 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) { }
1823
1824 /// \brief Create an offsetof node that refers to a field.
OffsetOfNode(SourceLocation DotLoc,FieldDecl * Field,SourceLocation NameLoc)1825 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field,
1826 SourceLocation NameLoc)
1827 : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
1828 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) { }
1829
1830 /// \brief Create an offsetof node that refers to an identifier.
OffsetOfNode(SourceLocation DotLoc,IdentifierInfo * Name,SourceLocation NameLoc)1831 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
1832 SourceLocation NameLoc)
1833 : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
1834 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) { }
1835
1836 /// \brief Create an offsetof node that refers into a C++ base class.
OffsetOfNode(const CXXBaseSpecifier * Base)1837 explicit OffsetOfNode(const CXXBaseSpecifier *Base)
1838 : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
1839
1840 /// \brief Determine what kind of offsetof node this is.
getKind()1841 Kind getKind() const {
1842 return static_cast<Kind>(Data & Mask);
1843 }
1844
1845 /// \brief For an array element node, returns the index into the array
1846 /// of expressions.
getArrayExprIndex()1847 unsigned getArrayExprIndex() const {
1848 assert(getKind() == Array);
1849 return Data >> 2;
1850 }
1851
1852 /// \brief For a field offsetof node, returns the field.
getField()1853 FieldDecl *getField() const {
1854 assert(getKind() == Field);
1855 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
1856 }
1857
1858 /// \brief For a field or identifier offsetof node, returns the name of
1859 /// the field.
1860 IdentifierInfo *getFieldName() const;
1861
1862 /// \brief For a base class node, returns the base specifier.
getBase()1863 CXXBaseSpecifier *getBase() const {
1864 assert(getKind() == Base);
1865 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
1866 }
1867
1868 /// \brief Retrieve the source range that covers this offsetof node.
1869 ///
1870 /// For an array element node, the source range contains the locations of
1871 /// the square brackets. For a field or identifier node, the source range
1872 /// contains the location of the period (if there is one) and the
1873 /// identifier.
getSourceRange()1874 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
getLocStart()1875 SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
getLocEnd()1876 SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
1877 };
1878
1879 private:
1880
1881 SourceLocation OperatorLoc, RParenLoc;
1882 // Base type;
1883 TypeSourceInfo *TSInfo;
1884 // Number of sub-components (i.e. instances of OffsetOfNode).
1885 unsigned NumComps;
1886 // Number of sub-expressions (i.e. array subscript expressions).
1887 unsigned NumExprs;
1888
1889 OffsetOfExpr(const ASTContext &C, QualType type,
1890 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1891 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
1892 SourceLocation RParenLoc);
1893
OffsetOfExpr(unsigned numComps,unsigned numExprs)1894 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
1895 : Expr(OffsetOfExprClass, EmptyShell()),
1896 TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {}
1897
1898 public:
1899
1900 static OffsetOfExpr *Create(const ASTContext &C, QualType type,
1901 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1902 ArrayRef<OffsetOfNode> comps,
1903 ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
1904
1905 static OffsetOfExpr *CreateEmpty(const ASTContext &C,
1906 unsigned NumComps, unsigned NumExprs);
1907
1908 /// getOperatorLoc - Return the location of the operator.
getOperatorLoc()1909 SourceLocation getOperatorLoc() const { return OperatorLoc; }
setOperatorLoc(SourceLocation L)1910 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
1911
1912 /// \brief Return the location of the right parentheses.
getRParenLoc()1913 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation R)1914 void setRParenLoc(SourceLocation R) { RParenLoc = R; }
1915
getTypeSourceInfo()1916 TypeSourceInfo *getTypeSourceInfo() const {
1917 return TSInfo;
1918 }
setTypeSourceInfo(TypeSourceInfo * tsi)1919 void setTypeSourceInfo(TypeSourceInfo *tsi) {
1920 TSInfo = tsi;
1921 }
1922
getComponent(unsigned Idx)1923 const OffsetOfNode &getComponent(unsigned Idx) const {
1924 assert(Idx < NumComps && "Subscript out of range");
1925 return reinterpret_cast<const OffsetOfNode *> (this + 1)[Idx];
1926 }
1927
setComponent(unsigned Idx,OffsetOfNode ON)1928 void setComponent(unsigned Idx, OffsetOfNode ON) {
1929 assert(Idx < NumComps && "Subscript out of range");
1930 reinterpret_cast<OffsetOfNode *> (this + 1)[Idx] = ON;
1931 }
1932
getNumComponents()1933 unsigned getNumComponents() const {
1934 return NumComps;
1935 }
1936
getIndexExpr(unsigned Idx)1937 Expr* getIndexExpr(unsigned Idx) {
1938 assert(Idx < NumExprs && "Subscript out of range");
1939 return reinterpret_cast<Expr **>(
1940 reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx];
1941 }
getIndexExpr(unsigned Idx)1942 const Expr *getIndexExpr(unsigned Idx) const {
1943 return const_cast<OffsetOfExpr*>(this)->getIndexExpr(Idx);
1944 }
1945
setIndexExpr(unsigned Idx,Expr * E)1946 void setIndexExpr(unsigned Idx, Expr* E) {
1947 assert(Idx < NumComps && "Subscript out of range");
1948 reinterpret_cast<Expr **>(
1949 reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx] = E;
1950 }
1951
getNumExpressions()1952 unsigned getNumExpressions() const {
1953 return NumExprs;
1954 }
1955
getLocStart()1956 SourceLocation getLocStart() const LLVM_READONLY { return OperatorLoc; }
getLocEnd()1957 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
1958
classof(const Stmt * T)1959 static bool classof(const Stmt *T) {
1960 return T->getStmtClass() == OffsetOfExprClass;
1961 }
1962
1963 // Iterators
children()1964 child_range children() {
1965 Stmt **begin =
1966 reinterpret_cast<Stmt**>(reinterpret_cast<OffsetOfNode*>(this + 1)
1967 + NumComps);
1968 return child_range(begin, begin + NumExprs);
1969 }
1970 };
1971
1972 /// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
1973 /// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and
1974 /// vec_step (OpenCL 1.1 6.11.12).
1975 class UnaryExprOrTypeTraitExpr : public Expr {
1976 union {
1977 TypeSourceInfo *Ty;
1978 Stmt *Ex;
1979 } Argument;
1980 SourceLocation OpLoc, RParenLoc;
1981
1982 public:
UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind,TypeSourceInfo * TInfo,QualType resultType,SourceLocation op,SourceLocation rp)1983 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
1984 QualType resultType, SourceLocation op,
1985 SourceLocation rp) :
1986 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1987 false, // Never type-dependent (C++ [temp.dep.expr]p3).
1988 // Value-dependent if the argument is type-dependent.
1989 TInfo->getType()->isDependentType(),
1990 TInfo->getType()->isInstantiationDependentType(),
1991 TInfo->getType()->containsUnexpandedParameterPack()),
1992 OpLoc(op), RParenLoc(rp) {
1993 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1994 UnaryExprOrTypeTraitExprBits.IsType = true;
1995 Argument.Ty = TInfo;
1996 }
1997
UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind,Expr * E,QualType resultType,SourceLocation op,SourceLocation rp)1998 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
1999 QualType resultType, SourceLocation op,
2000 SourceLocation rp) :
2001 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
2002 false, // Never type-dependent (C++ [temp.dep.expr]p3).
2003 // Value-dependent if the argument is type-dependent.
2004 E->isTypeDependent(),
2005 E->isInstantiationDependent(),
2006 E->containsUnexpandedParameterPack()),
2007 OpLoc(op), RParenLoc(rp) {
2008 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
2009 UnaryExprOrTypeTraitExprBits.IsType = false;
2010 Argument.Ex = E;
2011 }
2012
2013 /// \brief Construct an empty sizeof/alignof expression.
UnaryExprOrTypeTraitExpr(EmptyShell Empty)2014 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
2015 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
2016
getKind()2017 UnaryExprOrTypeTrait getKind() const {
2018 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
2019 }
setKind(UnaryExprOrTypeTrait K)2020 void setKind(UnaryExprOrTypeTrait K) { UnaryExprOrTypeTraitExprBits.Kind = K;}
2021
isArgumentType()2022 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
getArgumentType()2023 QualType getArgumentType() const {
2024 return getArgumentTypeInfo()->getType();
2025 }
getArgumentTypeInfo()2026 TypeSourceInfo *getArgumentTypeInfo() const {
2027 assert(isArgumentType() && "calling getArgumentType() when arg is expr");
2028 return Argument.Ty;
2029 }
getArgumentExpr()2030 Expr *getArgumentExpr() {
2031 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
2032 return static_cast<Expr*>(Argument.Ex);
2033 }
getArgumentExpr()2034 const Expr *getArgumentExpr() const {
2035 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
2036 }
2037
setArgument(Expr * E)2038 void setArgument(Expr *E) {
2039 Argument.Ex = E;
2040 UnaryExprOrTypeTraitExprBits.IsType = false;
2041 }
setArgument(TypeSourceInfo * TInfo)2042 void setArgument(TypeSourceInfo *TInfo) {
2043 Argument.Ty = TInfo;
2044 UnaryExprOrTypeTraitExprBits.IsType = true;
2045 }
2046
2047 /// Gets the argument type, or the type of the argument expression, whichever
2048 /// is appropriate.
getTypeOfArgument()2049 QualType getTypeOfArgument() const {
2050 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
2051 }
2052
getOperatorLoc()2053 SourceLocation getOperatorLoc() const { return OpLoc; }
setOperatorLoc(SourceLocation L)2054 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2055
getRParenLoc()2056 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)2057 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2058
getLocStart()2059 SourceLocation getLocStart() const LLVM_READONLY { return OpLoc; }
getLocEnd()2060 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
2061
classof(const Stmt * T)2062 static bool classof(const Stmt *T) {
2063 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2064 }
2065
2066 // Iterators
2067 child_range children();
2068 };
2069
2070 //===----------------------------------------------------------------------===//
2071 // Postfix Operators.
2072 //===----------------------------------------------------------------------===//
2073
2074 /// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2075 class ArraySubscriptExpr : public Expr {
2076 enum { LHS, RHS, END_EXPR=2 };
2077 Stmt* SubExprs[END_EXPR];
2078 SourceLocation RBracketLoc;
2079 public:
ArraySubscriptExpr(Expr * lhs,Expr * rhs,QualType t,ExprValueKind VK,ExprObjectKind OK,SourceLocation rbracketloc)2080 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
2081 ExprValueKind VK, ExprObjectKind OK,
2082 SourceLocation rbracketloc)
2083 : Expr(ArraySubscriptExprClass, t, VK, OK,
2084 lhs->isTypeDependent() || rhs->isTypeDependent(),
2085 lhs->isValueDependent() || rhs->isValueDependent(),
2086 (lhs->isInstantiationDependent() ||
2087 rhs->isInstantiationDependent()),
2088 (lhs->containsUnexpandedParameterPack() ||
2089 rhs->containsUnexpandedParameterPack())),
2090 RBracketLoc(rbracketloc) {
2091 SubExprs[LHS] = lhs;
2092 SubExprs[RHS] = rhs;
2093 }
2094
2095 /// \brief Create an empty array subscript expression.
ArraySubscriptExpr(EmptyShell Shell)2096 explicit ArraySubscriptExpr(EmptyShell Shell)
2097 : Expr(ArraySubscriptExprClass, Shell) { }
2098
2099 /// An array access can be written A[4] or 4[A] (both are equivalent).
2100 /// - getBase() and getIdx() always present the normalized view: A[4].
2101 /// In this case getBase() returns "A" and getIdx() returns "4".
2102 /// - getLHS() and getRHS() present the syntactic view. e.g. for
2103 /// 4[A] getLHS() returns "4".
2104 /// Note: Because vector element access is also written A[4] we must
2105 /// predicate the format conversion in getBase and getIdx only on the
2106 /// the type of the RHS, as it is possible for the LHS to be a vector of
2107 /// integer type
getLHS()2108 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
getLHS()2109 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
setLHS(Expr * E)2110 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2111
getRHS()2112 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
getRHS()2113 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
setRHS(Expr * E)2114 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2115
getBase()2116 Expr *getBase() {
2117 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
2118 }
2119
getBase()2120 const Expr *getBase() const {
2121 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
2122 }
2123
getIdx()2124 Expr *getIdx() {
2125 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
2126 }
2127
getIdx()2128 const Expr *getIdx() const {
2129 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
2130 }
2131
getLocStart()2132 SourceLocation getLocStart() const LLVM_READONLY {
2133 return getLHS()->getLocStart();
2134 }
getLocEnd()2135 SourceLocation getLocEnd() const LLVM_READONLY { return RBracketLoc; }
2136
getRBracketLoc()2137 SourceLocation getRBracketLoc() const { return RBracketLoc; }
setRBracketLoc(SourceLocation L)2138 void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
2139
getExprLoc()2140 SourceLocation getExprLoc() const LLVM_READONLY {
2141 return getBase()->getExprLoc();
2142 }
2143
classof(const Stmt * T)2144 static bool classof(const Stmt *T) {
2145 return T->getStmtClass() == ArraySubscriptExprClass;
2146 }
2147
2148 // Iterators
children()2149 child_range children() {
2150 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2151 }
2152 };
2153
2154
2155 /// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2156 /// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2157 /// while its subclasses may represent alternative syntax that (semantically)
2158 /// results in a function call. For example, CXXOperatorCallExpr is
2159 /// a subclass for overloaded operator calls that use operator syntax, e.g.,
2160 /// "str1 + str2" to resolve to a function call.
2161 class CallExpr : public Expr {
2162 enum { FN=0, PREARGS_START=1 };
2163 Stmt **SubExprs;
2164 unsigned NumArgs;
2165 SourceLocation RParenLoc;
2166
2167 protected:
2168 // These versions of the constructor are for derived classes.
2169 CallExpr(const ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs,
2170 ArrayRef<Expr*> args, QualType t, ExprValueKind VK,
2171 SourceLocation rparenloc);
2172 CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs,
2173 EmptyShell Empty);
2174
getPreArg(unsigned i)2175 Stmt *getPreArg(unsigned i) {
2176 assert(i < getNumPreArgs() && "Prearg access out of range!");
2177 return SubExprs[PREARGS_START+i];
2178 }
getPreArg(unsigned i)2179 const Stmt *getPreArg(unsigned i) const {
2180 assert(i < getNumPreArgs() && "Prearg access out of range!");
2181 return SubExprs[PREARGS_START+i];
2182 }
setPreArg(unsigned i,Stmt * PreArg)2183 void setPreArg(unsigned i, Stmt *PreArg) {
2184 assert(i < getNumPreArgs() && "Prearg access out of range!");
2185 SubExprs[PREARGS_START+i] = PreArg;
2186 }
2187
getNumPreArgs()2188 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2189
2190 public:
2191 CallExpr(const ASTContext& C, Expr *fn, ArrayRef<Expr*> args, QualType t,
2192 ExprValueKind VK, SourceLocation rparenloc);
2193
2194 /// \brief Build an empty call expression.
2195 CallExpr(const ASTContext &C, StmtClass SC, EmptyShell Empty);
2196
getCallee()2197 const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
getCallee()2198 Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
setCallee(Expr * F)2199 void setCallee(Expr *F) { SubExprs[FN] = F; }
2200
2201 Decl *getCalleeDecl();
getCalleeDecl()2202 const Decl *getCalleeDecl() const {
2203 return const_cast<CallExpr*>(this)->getCalleeDecl();
2204 }
2205
2206 /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0.
2207 FunctionDecl *getDirectCallee();
getDirectCallee()2208 const FunctionDecl *getDirectCallee() const {
2209 return const_cast<CallExpr*>(this)->getDirectCallee();
2210 }
2211
2212 /// getNumArgs - Return the number of actual arguments to this call.
2213 ///
getNumArgs()2214 unsigned getNumArgs() const { return NumArgs; }
2215
2216 /// \brief Retrieve the call arguments.
getArgs()2217 Expr **getArgs() {
2218 return reinterpret_cast<Expr **>(SubExprs+getNumPreArgs()+PREARGS_START);
2219 }
getArgs()2220 const Expr *const *getArgs() const {
2221 return const_cast<CallExpr*>(this)->getArgs();
2222 }
2223
2224 /// getArg - Return the specified argument.
getArg(unsigned Arg)2225 Expr *getArg(unsigned Arg) {
2226 assert(Arg < NumArgs && "Arg access out of range!");
2227 return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2228 }
getArg(unsigned Arg)2229 const Expr *getArg(unsigned Arg) const {
2230 assert(Arg < NumArgs && "Arg access out of range!");
2231 return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2232 }
2233
2234 /// setArg - Set the specified argument.
setArg(unsigned Arg,Expr * ArgExpr)2235 void setArg(unsigned Arg, Expr *ArgExpr) {
2236 assert(Arg < NumArgs && "Arg access out of range!");
2237 SubExprs[Arg+getNumPreArgs()+PREARGS_START] = ArgExpr;
2238 }
2239
2240 /// setNumArgs - This changes the number of arguments present in this call.
2241 /// Any orphaned expressions are deleted by this, and any new operands are set
2242 /// to null.
2243 void setNumArgs(const ASTContext& C, unsigned NumArgs);
2244
2245 typedef ExprIterator arg_iterator;
2246 typedef ConstExprIterator const_arg_iterator;
2247 typedef llvm::iterator_range<arg_iterator> arg_range;
2248 typedef llvm::iterator_range<const_arg_iterator> arg_const_range;
2249
arguments()2250 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
arguments()2251 arg_const_range arguments() const {
2252 return arg_const_range(arg_begin(), arg_end());
2253 }
2254
arg_begin()2255 arg_iterator arg_begin() { return SubExprs+PREARGS_START+getNumPreArgs(); }
arg_end()2256 arg_iterator arg_end() {
2257 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2258 }
arg_begin()2259 const_arg_iterator arg_begin() const {
2260 return SubExprs+PREARGS_START+getNumPreArgs();
2261 }
arg_end()2262 const_arg_iterator arg_end() const {
2263 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2264 }
2265
2266 /// This method provides fast access to all the subexpressions of
2267 /// a CallExpr without going through the slower virtual child_iterator
2268 /// interface. This provides efficient reverse iteration of the
2269 /// subexpressions. This is currently used for CFG construction.
getRawSubExprs()2270 ArrayRef<Stmt*> getRawSubExprs() {
2271 return llvm::makeArrayRef(SubExprs,
2272 getNumPreArgs() + PREARGS_START + getNumArgs());
2273 }
2274
2275 /// getNumCommas - Return the number of commas that must have been present in
2276 /// this function call.
getNumCommas()2277 unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
2278
2279 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
2280 /// of the callee. If not, return 0.
2281 unsigned getBuiltinCallee() const;
2282
2283 /// \brief Returns \c true if this is a call to a builtin which does not
2284 /// evaluate side-effects within its arguments.
2285 bool isUnevaluatedBuiltinCall(ASTContext &Ctx) const;
2286
2287 /// getCallReturnType - Get the return type of the call expr. This is not
2288 /// always the type of the expr itself, if the return type is a reference
2289 /// type.
2290 QualType getCallReturnType() const;
2291
getRParenLoc()2292 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)2293 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2294
2295 SourceLocation getLocStart() const LLVM_READONLY;
2296 SourceLocation getLocEnd() const LLVM_READONLY;
2297
classof(const Stmt * T)2298 static bool classof(const Stmt *T) {
2299 return T->getStmtClass() >= firstCallExprConstant &&
2300 T->getStmtClass() <= lastCallExprConstant;
2301 }
2302
2303 // Iterators
children()2304 child_range children() {
2305 return child_range(&SubExprs[0],
2306 &SubExprs[0]+NumArgs+getNumPreArgs()+PREARGS_START);
2307 }
2308 };
2309
2310 /// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
2311 ///
2312 class MemberExpr : public Expr {
2313 /// Extra data stored in some member expressions.
2314 struct MemberNameQualifier {
2315 /// \brief The nested-name-specifier that qualifies the name, including
2316 /// source-location information.
2317 NestedNameSpecifierLoc QualifierLoc;
2318
2319 /// \brief The DeclAccessPair through which the MemberDecl was found due to
2320 /// name qualifiers.
2321 DeclAccessPair FoundDecl;
2322 };
2323
2324 /// Base - the expression for the base pointer or structure references. In
2325 /// X.F, this is "X".
2326 Stmt *Base;
2327
2328 /// MemberDecl - This is the decl being referenced by the field/member name.
2329 /// In X.F, this is the decl referenced by F.
2330 ValueDecl *MemberDecl;
2331
2332 /// MemberDNLoc - Provides source/type location info for the
2333 /// declaration name embedded in MemberDecl.
2334 DeclarationNameLoc MemberDNLoc;
2335
2336 /// MemberLoc - This is the location of the member name.
2337 SourceLocation MemberLoc;
2338
2339 /// IsArrow - True if this is "X->F", false if this is "X.F".
2340 bool IsArrow : 1;
2341
2342 /// \brief True if this member expression used a nested-name-specifier to
2343 /// refer to the member, e.g., "x->Base::f", or found its member via a using
2344 /// declaration. When true, a MemberNameQualifier
2345 /// structure is allocated immediately after the MemberExpr.
2346 bool HasQualifierOrFoundDecl : 1;
2347
2348 /// \brief True if this member expression specified a template keyword
2349 /// and/or a template argument list explicitly, e.g., x->f<int>,
2350 /// x->template f, x->template f<int>.
2351 /// When true, an ASTTemplateKWAndArgsInfo structure and its
2352 /// TemplateArguments (if any) are allocated immediately after
2353 /// the MemberExpr or, if the member expression also has a qualifier,
2354 /// after the MemberNameQualifier structure.
2355 bool HasTemplateKWAndArgsInfo : 1;
2356
2357 /// \brief True if this member expression refers to a method that
2358 /// was resolved from an overloaded set having size greater than 1.
2359 bool HadMultipleCandidates : 1;
2360
2361 /// \brief Retrieve the qualifier that preceded the member name, if any.
getMemberQualifier()2362 MemberNameQualifier *getMemberQualifier() {
2363 assert(HasQualifierOrFoundDecl);
2364 return reinterpret_cast<MemberNameQualifier *> (this + 1);
2365 }
2366
2367 /// \brief Retrieve the qualifier that preceded the member name, if any.
getMemberQualifier()2368 const MemberNameQualifier *getMemberQualifier() const {
2369 return const_cast<MemberExpr *>(this)->getMemberQualifier();
2370 }
2371
2372 public:
MemberExpr(Expr * base,bool isarrow,ValueDecl * memberdecl,const DeclarationNameInfo & NameInfo,QualType ty,ExprValueKind VK,ExprObjectKind OK)2373 MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl,
2374 const DeclarationNameInfo &NameInfo, QualType ty,
2375 ExprValueKind VK, ExprObjectKind OK)
2376 : Expr(MemberExprClass, ty, VK, OK,
2377 base->isTypeDependent(),
2378 base->isValueDependent(),
2379 base->isInstantiationDependent(),
2380 base->containsUnexpandedParameterPack()),
2381 Base(base), MemberDecl(memberdecl), MemberDNLoc(NameInfo.getInfo()),
2382 MemberLoc(NameInfo.getLoc()), IsArrow(isarrow),
2383 HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false),
2384 HadMultipleCandidates(false) {
2385 assert(memberdecl->getDeclName() == NameInfo.getName());
2386 }
2387
2388 // NOTE: this constructor should be used only when it is known that
2389 // the member name can not provide additional syntactic info
2390 // (i.e., source locations for C++ operator names or type source info
2391 // for constructors, destructors and conversion operators).
MemberExpr(Expr * base,bool isarrow,ValueDecl * memberdecl,SourceLocation l,QualType ty,ExprValueKind VK,ExprObjectKind OK)2392 MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl,
2393 SourceLocation l, QualType ty,
2394 ExprValueKind VK, ExprObjectKind OK)
2395 : Expr(MemberExprClass, ty, VK, OK,
2396 base->isTypeDependent(), base->isValueDependent(),
2397 base->isInstantiationDependent(),
2398 base->containsUnexpandedParameterPack()),
2399 Base(base), MemberDecl(memberdecl), MemberDNLoc(), MemberLoc(l),
2400 IsArrow(isarrow),
2401 HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false),
2402 HadMultipleCandidates(false) {}
2403
2404 static MemberExpr *Create(const ASTContext &C, Expr *base, bool isarrow,
2405 NestedNameSpecifierLoc QualifierLoc,
2406 SourceLocation TemplateKWLoc,
2407 ValueDecl *memberdecl, DeclAccessPair founddecl,
2408 DeclarationNameInfo MemberNameInfo,
2409 const TemplateArgumentListInfo *targs,
2410 QualType ty, ExprValueKind VK, ExprObjectKind OK);
2411
setBase(Expr * E)2412 void setBase(Expr *E) { Base = E; }
getBase()2413 Expr *getBase() const { return cast<Expr>(Base); }
2414
2415 /// \brief Retrieve the member declaration to which this expression refers.
2416 ///
2417 /// The returned declaration will either be a FieldDecl or (in C++)
2418 /// a CXXMethodDecl.
getMemberDecl()2419 ValueDecl *getMemberDecl() const { return MemberDecl; }
setMemberDecl(ValueDecl * D)2420 void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
2421
2422 /// \brief Retrieves the declaration found by lookup.
getFoundDecl()2423 DeclAccessPair getFoundDecl() const {
2424 if (!HasQualifierOrFoundDecl)
2425 return DeclAccessPair::make(getMemberDecl(),
2426 getMemberDecl()->getAccess());
2427 return getMemberQualifier()->FoundDecl;
2428 }
2429
2430 /// \brief Determines whether this member expression actually had
2431 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2432 /// x->Base::foo.
hasQualifier()2433 bool hasQualifier() const { return getQualifier() != nullptr; }
2434
2435 /// \brief If the member name was qualified, retrieves the
2436 /// nested-name-specifier that precedes the member name. Otherwise, returns
2437 /// NULL.
getQualifier()2438 NestedNameSpecifier *getQualifier() const {
2439 if (!HasQualifierOrFoundDecl)
2440 return nullptr;
2441
2442 return getMemberQualifier()->QualifierLoc.getNestedNameSpecifier();
2443 }
2444
2445 /// \brief If the member name was qualified, retrieves the
2446 /// nested-name-specifier that precedes the member name, with source-location
2447 /// information.
getQualifierLoc()2448 NestedNameSpecifierLoc getQualifierLoc() const {
2449 if (!hasQualifier())
2450 return NestedNameSpecifierLoc();
2451
2452 return getMemberQualifier()->QualifierLoc;
2453 }
2454
2455 /// \brief Return the optional template keyword and arguments info.
getTemplateKWAndArgsInfo()2456 ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() {
2457 if (!HasTemplateKWAndArgsInfo)
2458 return nullptr;
2459
2460 if (!HasQualifierOrFoundDecl)
2461 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(this + 1);
2462
2463 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(
2464 getMemberQualifier() + 1);
2465 }
2466
2467 /// \brief Return the optional template keyword and arguments info.
getTemplateKWAndArgsInfo()2468 const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const {
2469 return const_cast<MemberExpr*>(this)->getTemplateKWAndArgsInfo();
2470 }
2471
2472 /// \brief Retrieve the location of the template keyword preceding
2473 /// the member name, if any.
getTemplateKeywordLoc()2474 SourceLocation getTemplateKeywordLoc() const {
2475 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2476 return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc();
2477 }
2478
2479 /// \brief Retrieve the location of the left angle bracket starting the
2480 /// explicit template argument list following the member name, if any.
getLAngleLoc()2481 SourceLocation getLAngleLoc() const {
2482 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2483 return getTemplateKWAndArgsInfo()->LAngleLoc;
2484 }
2485
2486 /// \brief Retrieve the location of the right angle bracket ending the
2487 /// explicit template argument list following the member name, if any.
getRAngleLoc()2488 SourceLocation getRAngleLoc() const {
2489 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2490 return getTemplateKWAndArgsInfo()->RAngleLoc;
2491 }
2492
2493 /// Determines whether the member name was preceded by the template keyword.
hasTemplateKeyword()2494 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
2495
2496 /// \brief Determines whether the member name was followed by an
2497 /// explicit template argument list.
hasExplicitTemplateArgs()2498 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
2499
2500 /// \brief Copies the template arguments (if present) into the given
2501 /// structure.
copyTemplateArgumentsInto(TemplateArgumentListInfo & List)2502 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2503 if (hasExplicitTemplateArgs())
2504 getExplicitTemplateArgs().copyInto(List);
2505 }
2506
2507 /// \brief Retrieve the explicit template argument list that
2508 /// follow the member template name. This must only be called on an
2509 /// expression with explicit template arguments.
getExplicitTemplateArgs()2510 ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
2511 assert(hasExplicitTemplateArgs());
2512 return *getTemplateKWAndArgsInfo();
2513 }
2514
2515 /// \brief Retrieve the explicit template argument list that
2516 /// followed the member template name. This must only be called on
2517 /// an expression with explicit template arguments.
getExplicitTemplateArgs()2518 const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
2519 return const_cast<MemberExpr *>(this)->getExplicitTemplateArgs();
2520 }
2521
2522 /// \brief Retrieves the optional explicit template arguments.
2523 /// This points to the same data as getExplicitTemplateArgs(), but
2524 /// returns null if there are no explicit template arguments.
getOptionalExplicitTemplateArgs()2525 const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const {
2526 if (!hasExplicitTemplateArgs()) return nullptr;
2527 return &getExplicitTemplateArgs();
2528 }
2529
2530 /// \brief Retrieve the template arguments provided as part of this
2531 /// template-id.
getTemplateArgs()2532 const TemplateArgumentLoc *getTemplateArgs() const {
2533 if (!hasExplicitTemplateArgs())
2534 return nullptr;
2535
2536 return getExplicitTemplateArgs().getTemplateArgs();
2537 }
2538
2539 /// \brief Retrieve the number of template arguments provided as part of this
2540 /// template-id.
getNumTemplateArgs()2541 unsigned getNumTemplateArgs() const {
2542 if (!hasExplicitTemplateArgs())
2543 return 0;
2544
2545 return getExplicitTemplateArgs().NumTemplateArgs;
2546 }
2547
2548 /// \brief Retrieve the member declaration name info.
getMemberNameInfo()2549 DeclarationNameInfo getMemberNameInfo() const {
2550 return DeclarationNameInfo(MemberDecl->getDeclName(),
2551 MemberLoc, MemberDNLoc);
2552 }
2553
isArrow()2554 bool isArrow() const { return IsArrow; }
setArrow(bool A)2555 void setArrow(bool A) { IsArrow = A; }
2556
2557 /// getMemberLoc - Return the location of the "member", in X->F, it is the
2558 /// location of 'F'.
getMemberLoc()2559 SourceLocation getMemberLoc() const { return MemberLoc; }
setMemberLoc(SourceLocation L)2560 void setMemberLoc(SourceLocation L) { MemberLoc = L; }
2561
2562 SourceLocation getLocStart() const LLVM_READONLY;
2563 SourceLocation getLocEnd() const LLVM_READONLY;
2564
getExprLoc()2565 SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; }
2566
2567 /// \brief Determine whether the base of this explicit is implicit.
isImplicitAccess()2568 bool isImplicitAccess() const {
2569 return getBase() && getBase()->isImplicitCXXThis();
2570 }
2571
2572 /// \brief Returns true if this member expression refers to a method that
2573 /// was resolved from an overloaded set having size greater than 1.
hadMultipleCandidates()2574 bool hadMultipleCandidates() const {
2575 return HadMultipleCandidates;
2576 }
2577 /// \brief Sets the flag telling whether this expression refers to
2578 /// a method that was resolved from an overloaded set having size
2579 /// greater than 1.
2580 void setHadMultipleCandidates(bool V = true) {
2581 HadMultipleCandidates = V;
2582 }
2583
classof(const Stmt * T)2584 static bool classof(const Stmt *T) {
2585 return T->getStmtClass() == MemberExprClass;
2586 }
2587
2588 // Iterators
children()2589 child_range children() { return child_range(&Base, &Base+1); }
2590
2591 friend class ASTReader;
2592 friend class ASTStmtWriter;
2593 };
2594
2595 /// CompoundLiteralExpr - [C99 6.5.2.5]
2596 ///
2597 class CompoundLiteralExpr : public Expr {
2598 /// LParenLoc - If non-null, this is the location of the left paren in a
2599 /// compound literal like "(int){4}". This can be null if this is a
2600 /// synthesized compound expression.
2601 SourceLocation LParenLoc;
2602
2603 /// The type as written. This can be an incomplete array type, in
2604 /// which case the actual expression type will be different.
2605 /// The int part of the pair stores whether this expr is file scope.
2606 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
2607 Stmt *Init;
2608 public:
CompoundLiteralExpr(SourceLocation lparenloc,TypeSourceInfo * tinfo,QualType T,ExprValueKind VK,Expr * init,bool fileScope)2609 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
2610 QualType T, ExprValueKind VK, Expr *init, bool fileScope)
2611 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary,
2612 tinfo->getType()->isDependentType(),
2613 init->isValueDependent(),
2614 (init->isInstantiationDependent() ||
2615 tinfo->getType()->isInstantiationDependentType()),
2616 init->containsUnexpandedParameterPack()),
2617 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {}
2618
2619 /// \brief Construct an empty compound literal.
CompoundLiteralExpr(EmptyShell Empty)2620 explicit CompoundLiteralExpr(EmptyShell Empty)
2621 : Expr(CompoundLiteralExprClass, Empty) { }
2622
getInitializer()2623 const Expr *getInitializer() const { return cast<Expr>(Init); }
getInitializer()2624 Expr *getInitializer() { return cast<Expr>(Init); }
setInitializer(Expr * E)2625 void setInitializer(Expr *E) { Init = E; }
2626
isFileScope()2627 bool isFileScope() const { return TInfoAndScope.getInt(); }
setFileScope(bool FS)2628 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
2629
getLParenLoc()2630 SourceLocation getLParenLoc() const { return LParenLoc; }
setLParenLoc(SourceLocation L)2631 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2632
getTypeSourceInfo()2633 TypeSourceInfo *getTypeSourceInfo() const {
2634 return TInfoAndScope.getPointer();
2635 }
setTypeSourceInfo(TypeSourceInfo * tinfo)2636 void setTypeSourceInfo(TypeSourceInfo *tinfo) {
2637 TInfoAndScope.setPointer(tinfo);
2638 }
2639
getLocStart()2640 SourceLocation getLocStart() const LLVM_READONLY {
2641 // FIXME: Init should never be null.
2642 if (!Init)
2643 return SourceLocation();
2644 if (LParenLoc.isInvalid())
2645 return Init->getLocStart();
2646 return LParenLoc;
2647 }
getLocEnd()2648 SourceLocation getLocEnd() const LLVM_READONLY {
2649 // FIXME: Init should never be null.
2650 if (!Init)
2651 return SourceLocation();
2652 return Init->getLocEnd();
2653 }
2654
classof(const Stmt * T)2655 static bool classof(const Stmt *T) {
2656 return T->getStmtClass() == CompoundLiteralExprClass;
2657 }
2658
2659 // Iterators
children()2660 child_range children() { return child_range(&Init, &Init+1); }
2661 };
2662
2663 /// CastExpr - Base class for type casts, including both implicit
2664 /// casts (ImplicitCastExpr) and explicit casts that have some
2665 /// representation in the source code (ExplicitCastExpr's derived
2666 /// classes).
2667 class CastExpr : public Expr {
2668 private:
2669 Stmt *Op;
2670
2671 bool CastConsistency() const;
2672
path_buffer()2673 const CXXBaseSpecifier * const *path_buffer() const {
2674 return const_cast<CastExpr*>(this)->path_buffer();
2675 }
2676 CXXBaseSpecifier **path_buffer();
2677
setBasePathSize(unsigned basePathSize)2678 void setBasePathSize(unsigned basePathSize) {
2679 CastExprBits.BasePathSize = basePathSize;
2680 assert(CastExprBits.BasePathSize == basePathSize &&
2681 "basePathSize doesn't fit in bits of CastExprBits.BasePathSize!");
2682 }
2683
2684 protected:
CastExpr(StmtClass SC,QualType ty,ExprValueKind VK,const CastKind kind,Expr * op,unsigned BasePathSize)2685 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind,
2686 Expr *op, unsigned BasePathSize)
2687 : Expr(SC, ty, VK, OK_Ordinary,
2688 // Cast expressions are type-dependent if the type is
2689 // dependent (C++ [temp.dep.expr]p3).
2690 ty->isDependentType(),
2691 // Cast expressions are value-dependent if the type is
2692 // dependent or if the subexpression is value-dependent.
2693 ty->isDependentType() || (op && op->isValueDependent()),
2694 (ty->isInstantiationDependentType() ||
2695 (op && op->isInstantiationDependent())),
2696 // An implicit cast expression doesn't (lexically) contain an
2697 // unexpanded pack, even if its target type does.
2698 ((SC != ImplicitCastExprClass &&
2699 ty->containsUnexpandedParameterPack()) ||
2700 (op && op->containsUnexpandedParameterPack()))),
2701 Op(op) {
2702 assert(kind != CK_Invalid && "creating cast with invalid cast kind");
2703 CastExprBits.Kind = kind;
2704 setBasePathSize(BasePathSize);
2705 assert(CastConsistency());
2706 }
2707
2708 /// \brief Construct an empty cast.
CastExpr(StmtClass SC,EmptyShell Empty,unsigned BasePathSize)2709 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
2710 : Expr(SC, Empty) {
2711 setBasePathSize(BasePathSize);
2712 }
2713
2714 public:
getCastKind()2715 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
setCastKind(CastKind K)2716 void setCastKind(CastKind K) { CastExprBits.Kind = K; }
2717 const char *getCastKindName() const;
2718
getSubExpr()2719 Expr *getSubExpr() { return cast<Expr>(Op); }
getSubExpr()2720 const Expr *getSubExpr() const { return cast<Expr>(Op); }
setSubExpr(Expr * E)2721 void setSubExpr(Expr *E) { Op = E; }
2722
2723 /// \brief Retrieve the cast subexpression as it was written in the source
2724 /// code, looking through any implicit casts or other intermediate nodes
2725 /// introduced by semantic analysis.
2726 Expr *getSubExprAsWritten();
getSubExprAsWritten()2727 const Expr *getSubExprAsWritten() const {
2728 return const_cast<CastExpr *>(this)->getSubExprAsWritten();
2729 }
2730
2731 typedef CXXBaseSpecifier **path_iterator;
2732 typedef const CXXBaseSpecifier * const *path_const_iterator;
path_empty()2733 bool path_empty() const { return CastExprBits.BasePathSize == 0; }
path_size()2734 unsigned path_size() const { return CastExprBits.BasePathSize; }
path_begin()2735 path_iterator path_begin() { return path_buffer(); }
path_end()2736 path_iterator path_end() { return path_buffer() + path_size(); }
path_begin()2737 path_const_iterator path_begin() const { return path_buffer(); }
path_end()2738 path_const_iterator path_end() const { return path_buffer() + path_size(); }
2739
2740 void setCastPath(const CXXCastPath &Path);
2741
classof(const Stmt * T)2742 static bool classof(const Stmt *T) {
2743 return T->getStmtClass() >= firstCastExprConstant &&
2744 T->getStmtClass() <= lastCastExprConstant;
2745 }
2746
2747 // Iterators
children()2748 child_range children() { return child_range(&Op, &Op+1); }
2749 };
2750
2751 /// ImplicitCastExpr - Allows us to explicitly represent implicit type
2752 /// conversions, which have no direct representation in the original
2753 /// source code. For example: converting T[]->T*, void f()->void
2754 /// (*f)(), float->double, short->int, etc.
2755 ///
2756 /// In C, implicit casts always produce rvalues. However, in C++, an
2757 /// implicit cast whose result is being bound to a reference will be
2758 /// an lvalue or xvalue. For example:
2759 ///
2760 /// @code
2761 /// class Base { };
2762 /// class Derived : public Base { };
2763 /// Derived &&ref();
2764 /// void f(Derived d) {
2765 /// Base& b = d; // initializer is an ImplicitCastExpr
2766 /// // to an lvalue of type Base
2767 /// Base&& r = ref(); // initializer is an ImplicitCastExpr
2768 /// // to an xvalue of type Base
2769 /// }
2770 /// @endcode
2771 class ImplicitCastExpr : public CastExpr {
2772 private:
ImplicitCastExpr(QualType ty,CastKind kind,Expr * op,unsigned BasePathLength,ExprValueKind VK)2773 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
2774 unsigned BasePathLength, ExprValueKind VK)
2775 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) {
2776 }
2777
2778 /// \brief Construct an empty implicit cast.
ImplicitCastExpr(EmptyShell Shell,unsigned PathSize)2779 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize)
2780 : CastExpr(ImplicitCastExprClass, Shell, PathSize) { }
2781
2782 public:
2783 enum OnStack_t { OnStack };
ImplicitCastExpr(OnStack_t _,QualType ty,CastKind kind,Expr * op,ExprValueKind VK)2784 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
2785 ExprValueKind VK)
2786 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) {
2787 }
2788
2789 static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
2790 CastKind Kind, Expr *Operand,
2791 const CXXCastPath *BasePath,
2792 ExprValueKind Cat);
2793
2794 static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
2795 unsigned PathSize);
2796
getLocStart()2797 SourceLocation getLocStart() const LLVM_READONLY {
2798 return getSubExpr()->getLocStart();
2799 }
getLocEnd()2800 SourceLocation getLocEnd() const LLVM_READONLY {
2801 return getSubExpr()->getLocEnd();
2802 }
2803
classof(const Stmt * T)2804 static bool classof(const Stmt *T) {
2805 return T->getStmtClass() == ImplicitCastExprClass;
2806 }
2807 };
2808
IgnoreImpCasts()2809 inline Expr *Expr::IgnoreImpCasts() {
2810 Expr *e = this;
2811 while (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
2812 e = ice->getSubExpr();
2813 return e;
2814 }
2815
2816 /// ExplicitCastExpr - An explicit cast written in the source
2817 /// code.
2818 ///
2819 /// This class is effectively an abstract class, because it provides
2820 /// the basic representation of an explicitly-written cast without
2821 /// specifying which kind of cast (C cast, functional cast, static
2822 /// cast, etc.) was written; specific derived classes represent the
2823 /// particular style of cast and its location information.
2824 ///
2825 /// Unlike implicit casts, explicit cast nodes have two different
2826 /// types: the type that was written into the source code, and the
2827 /// actual type of the expression as determined by semantic
2828 /// analysis. These types may differ slightly. For example, in C++ one
2829 /// can cast to a reference type, which indicates that the resulting
2830 /// expression will be an lvalue or xvalue. The reference type, however,
2831 /// will not be used as the type of the expression.
2832 class ExplicitCastExpr : public CastExpr {
2833 /// TInfo - Source type info for the (written) type
2834 /// this expression is casting to.
2835 TypeSourceInfo *TInfo;
2836
2837 protected:
ExplicitCastExpr(StmtClass SC,QualType exprTy,ExprValueKind VK,CastKind kind,Expr * op,unsigned PathSize,TypeSourceInfo * writtenTy)2838 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
2839 CastKind kind, Expr *op, unsigned PathSize,
2840 TypeSourceInfo *writtenTy)
2841 : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {}
2842
2843 /// \brief Construct an empty explicit cast.
ExplicitCastExpr(StmtClass SC,EmptyShell Shell,unsigned PathSize)2844 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
2845 : CastExpr(SC, Shell, PathSize) { }
2846
2847 public:
2848 /// getTypeInfoAsWritten - Returns the type source info for the type
2849 /// that this expression is casting to.
getTypeInfoAsWritten()2850 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
setTypeInfoAsWritten(TypeSourceInfo * writtenTy)2851 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
2852
2853 /// getTypeAsWritten - Returns the type that this expression is
2854 /// casting to, as written in the source code.
getTypeAsWritten()2855 QualType getTypeAsWritten() const { return TInfo->getType(); }
2856
classof(const Stmt * T)2857 static bool classof(const Stmt *T) {
2858 return T->getStmtClass() >= firstExplicitCastExprConstant &&
2859 T->getStmtClass() <= lastExplicitCastExprConstant;
2860 }
2861 };
2862
2863 /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
2864 /// cast in C++ (C++ [expr.cast]), which uses the syntax
2865 /// (Type)expr. For example: @c (int)f.
2866 class CStyleCastExpr : public ExplicitCastExpr {
2867 SourceLocation LPLoc; // the location of the left paren
2868 SourceLocation RPLoc; // the location of the right paren
2869
CStyleCastExpr(QualType exprTy,ExprValueKind vk,CastKind kind,Expr * op,unsigned PathSize,TypeSourceInfo * writtenTy,SourceLocation l,SourceLocation r)2870 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
2871 unsigned PathSize, TypeSourceInfo *writtenTy,
2872 SourceLocation l, SourceLocation r)
2873 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
2874 writtenTy), LPLoc(l), RPLoc(r) {}
2875
2876 /// \brief Construct an empty C-style explicit cast.
CStyleCastExpr(EmptyShell Shell,unsigned PathSize)2877 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize)
2878 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { }
2879
2880 public:
2881 static CStyleCastExpr *Create(const ASTContext &Context, QualType T,
2882 ExprValueKind VK, CastKind K,
2883 Expr *Op, const CXXCastPath *BasePath,
2884 TypeSourceInfo *WrittenTy, SourceLocation L,
2885 SourceLocation R);
2886
2887 static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
2888 unsigned PathSize);
2889
getLParenLoc()2890 SourceLocation getLParenLoc() const { return LPLoc; }
setLParenLoc(SourceLocation L)2891 void setLParenLoc(SourceLocation L) { LPLoc = L; }
2892
getRParenLoc()2893 SourceLocation getRParenLoc() const { return RPLoc; }
setRParenLoc(SourceLocation L)2894 void setRParenLoc(SourceLocation L) { RPLoc = L; }
2895
getLocStart()2896 SourceLocation getLocStart() const LLVM_READONLY { return LPLoc; }
getLocEnd()2897 SourceLocation getLocEnd() const LLVM_READONLY {
2898 return getSubExpr()->getLocEnd();
2899 }
2900
classof(const Stmt * T)2901 static bool classof(const Stmt *T) {
2902 return T->getStmtClass() == CStyleCastExprClass;
2903 }
2904 };
2905
2906 /// \brief A builtin binary operation expression such as "x + y" or "x <= y".
2907 ///
2908 /// This expression node kind describes a builtin binary operation,
2909 /// such as "x + y" for integer values "x" and "y". The operands will
2910 /// already have been converted to appropriate types (e.g., by
2911 /// performing promotions or conversions).
2912 ///
2913 /// In C++, where operators may be overloaded, a different kind of
2914 /// expression node (CXXOperatorCallExpr) is used to express the
2915 /// invocation of an overloaded operator with operator syntax. Within
2916 /// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
2917 /// used to store an expression "x + y" depends on the subexpressions
2918 /// for x and y. If neither x or y is type-dependent, and the "+"
2919 /// operator resolves to a built-in operation, BinaryOperator will be
2920 /// used to express the computation (x and y may still be
2921 /// value-dependent). If either x or y is type-dependent, or if the
2922 /// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
2923 /// be used to express the computation.
2924 class BinaryOperator : public Expr {
2925 public:
2926 typedef BinaryOperatorKind Opcode;
2927
2928 private:
2929 unsigned Opc : 6;
2930
2931 // Records the FP_CONTRACT pragma status at the point that this binary
2932 // operator was parsed. This bit is only meaningful for operations on
2933 // floating point types. For all other types it should default to
2934 // false.
2935 unsigned FPContractable : 1;
2936 SourceLocation OpLoc;
2937
2938 enum { LHS, RHS, END_EXPR };
2939 Stmt* SubExprs[END_EXPR];
2940 public:
2941
BinaryOperator(Expr * lhs,Expr * rhs,Opcode opc,QualType ResTy,ExprValueKind VK,ExprObjectKind OK,SourceLocation opLoc,bool fpContractable)2942 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2943 ExprValueKind VK, ExprObjectKind OK,
2944 SourceLocation opLoc, bool fpContractable)
2945 : Expr(BinaryOperatorClass, ResTy, VK, OK,
2946 lhs->isTypeDependent() || rhs->isTypeDependent(),
2947 lhs->isValueDependent() || rhs->isValueDependent(),
2948 (lhs->isInstantiationDependent() ||
2949 rhs->isInstantiationDependent()),
2950 (lhs->containsUnexpandedParameterPack() ||
2951 rhs->containsUnexpandedParameterPack())),
2952 Opc(opc), FPContractable(fpContractable), OpLoc(opLoc) {
2953 SubExprs[LHS] = lhs;
2954 SubExprs[RHS] = rhs;
2955 assert(!isCompoundAssignmentOp() &&
2956 "Use CompoundAssignOperator for compound assignments");
2957 }
2958
2959 /// \brief Construct an empty binary operator.
BinaryOperator(EmptyShell Empty)2960 explicit BinaryOperator(EmptyShell Empty)
2961 : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { }
2962
getExprLoc()2963 SourceLocation getExprLoc() const LLVM_READONLY { return OpLoc; }
getOperatorLoc()2964 SourceLocation getOperatorLoc() const { return OpLoc; }
setOperatorLoc(SourceLocation L)2965 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2966
getOpcode()2967 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
setOpcode(Opcode O)2968 void setOpcode(Opcode O) { Opc = O; }
2969
getLHS()2970 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
setLHS(Expr * E)2971 void setLHS(Expr *E) { SubExprs[LHS] = E; }
getRHS()2972 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
setRHS(Expr * E)2973 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2974
getLocStart()2975 SourceLocation getLocStart() const LLVM_READONLY {
2976 return getLHS()->getLocStart();
2977 }
getLocEnd()2978 SourceLocation getLocEnd() const LLVM_READONLY {
2979 return getRHS()->getLocEnd();
2980 }
2981
2982 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2983 /// corresponds to, e.g. "<<=".
2984 static StringRef getOpcodeStr(Opcode Op);
2985
getOpcodeStr()2986 StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
2987
2988 /// \brief Retrieve the binary opcode that corresponds to the given
2989 /// overloaded operator.
2990 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
2991
2992 /// \brief Retrieve the overloaded operator kind that corresponds to
2993 /// the given binary opcode.
2994 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
2995
2996 /// predicates to categorize the respective opcodes.
isPtrMemOp()2997 bool isPtrMemOp() const { return Opc == BO_PtrMemD || Opc == BO_PtrMemI; }
isMultiplicativeOp()2998 bool isMultiplicativeOp() const { return Opc >= BO_Mul && Opc <= BO_Rem; }
isAdditiveOp(Opcode Opc)2999 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
isAdditiveOp()3000 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
isShiftOp(Opcode Opc)3001 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
isShiftOp()3002 bool isShiftOp() const { return isShiftOp(getOpcode()); }
3003
isBitwiseOp(Opcode Opc)3004 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
isBitwiseOp()3005 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
3006
isRelationalOp(Opcode Opc)3007 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
isRelationalOp()3008 bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
3009
isEqualityOp(Opcode Opc)3010 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
isEqualityOp()3011 bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
3012
isComparisonOp(Opcode Opc)3013 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_NE; }
isComparisonOp()3014 bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
3015
negateComparisonOp(Opcode Opc)3016 static Opcode negateComparisonOp(Opcode Opc) {
3017 switch (Opc) {
3018 default:
3019 llvm_unreachable("Not a comparsion operator.");
3020 case BO_LT: return BO_GE;
3021 case BO_GT: return BO_LE;
3022 case BO_LE: return BO_GT;
3023 case BO_GE: return BO_LT;
3024 case BO_EQ: return BO_NE;
3025 case BO_NE: return BO_EQ;
3026 }
3027 }
3028
reverseComparisonOp(Opcode Opc)3029 static Opcode reverseComparisonOp(Opcode Opc) {
3030 switch (Opc) {
3031 default:
3032 llvm_unreachable("Not a comparsion operator.");
3033 case BO_LT: return BO_GT;
3034 case BO_GT: return BO_LT;
3035 case BO_LE: return BO_GE;
3036 case BO_GE: return BO_LE;
3037 case BO_EQ:
3038 case BO_NE:
3039 return Opc;
3040 }
3041 }
3042
isLogicalOp(Opcode Opc)3043 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
isLogicalOp()3044 bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
3045
isAssignmentOp(Opcode Opc)3046 static bool isAssignmentOp(Opcode Opc) {
3047 return Opc >= BO_Assign && Opc <= BO_OrAssign;
3048 }
isAssignmentOp()3049 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
3050
isCompoundAssignmentOp(Opcode Opc)3051 static bool isCompoundAssignmentOp(Opcode Opc) {
3052 return Opc > BO_Assign && Opc <= BO_OrAssign;
3053 }
isCompoundAssignmentOp()3054 bool isCompoundAssignmentOp() const {
3055 return isCompoundAssignmentOp(getOpcode());
3056 }
getOpForCompoundAssignment(Opcode Opc)3057 static Opcode getOpForCompoundAssignment(Opcode Opc) {
3058 assert(isCompoundAssignmentOp(Opc));
3059 if (Opc >= BO_AndAssign)
3060 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
3061 else
3062 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
3063 }
3064
isShiftAssignOp(Opcode Opc)3065 static bool isShiftAssignOp(Opcode Opc) {
3066 return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
3067 }
isShiftAssignOp()3068 bool isShiftAssignOp() const {
3069 return isShiftAssignOp(getOpcode());
3070 }
3071
classof(const Stmt * S)3072 static bool classof(const Stmt *S) {
3073 return S->getStmtClass() >= firstBinaryOperatorConstant &&
3074 S->getStmtClass() <= lastBinaryOperatorConstant;
3075 }
3076
3077 // Iterators
children()3078 child_range children() {
3079 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3080 }
3081
3082 // Set the FP contractability status of this operator. Only meaningful for
3083 // operations on floating point types.
setFPContractable(bool FPC)3084 void setFPContractable(bool FPC) { FPContractable = FPC; }
3085
3086 // Get the FP contractability status of this operator. Only meaningful for
3087 // operations on floating point types.
isFPContractable()3088 bool isFPContractable() const { return FPContractable; }
3089
3090 protected:
BinaryOperator(Expr * lhs,Expr * rhs,Opcode opc,QualType ResTy,ExprValueKind VK,ExprObjectKind OK,SourceLocation opLoc,bool fpContractable,bool dead2)3091 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
3092 ExprValueKind VK, ExprObjectKind OK,
3093 SourceLocation opLoc, bool fpContractable, bool dead2)
3094 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK,
3095 lhs->isTypeDependent() || rhs->isTypeDependent(),
3096 lhs->isValueDependent() || rhs->isValueDependent(),
3097 (lhs->isInstantiationDependent() ||
3098 rhs->isInstantiationDependent()),
3099 (lhs->containsUnexpandedParameterPack() ||
3100 rhs->containsUnexpandedParameterPack())),
3101 Opc(opc), FPContractable(fpContractable), OpLoc(opLoc) {
3102 SubExprs[LHS] = lhs;
3103 SubExprs[RHS] = rhs;
3104 }
3105
BinaryOperator(StmtClass SC,EmptyShell Empty)3106 BinaryOperator(StmtClass SC, EmptyShell Empty)
3107 : Expr(SC, Empty), Opc(BO_MulAssign) { }
3108 };
3109
3110 /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
3111 /// track of the type the operation is performed in. Due to the semantics of
3112 /// these operators, the operands are promoted, the arithmetic performed, an
3113 /// implicit conversion back to the result type done, then the assignment takes
3114 /// place. This captures the intermediate type which the computation is done
3115 /// in.
3116 class CompoundAssignOperator : public BinaryOperator {
3117 QualType ComputationLHSType;
3118 QualType ComputationResultType;
3119 public:
CompoundAssignOperator(Expr * lhs,Expr * rhs,Opcode opc,QualType ResType,ExprValueKind VK,ExprObjectKind OK,QualType CompLHSType,QualType CompResultType,SourceLocation OpLoc,bool fpContractable)3120 CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType,
3121 ExprValueKind VK, ExprObjectKind OK,
3122 QualType CompLHSType, QualType CompResultType,
3123 SourceLocation OpLoc, bool fpContractable)
3124 : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, fpContractable,
3125 true),
3126 ComputationLHSType(CompLHSType),
3127 ComputationResultType(CompResultType) {
3128 assert(isCompoundAssignmentOp() &&
3129 "Only should be used for compound assignments");
3130 }
3131
3132 /// \brief Build an empty compound assignment operator expression.
CompoundAssignOperator(EmptyShell Empty)3133 explicit CompoundAssignOperator(EmptyShell Empty)
3134 : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
3135
3136 // The two computation types are the type the LHS is converted
3137 // to for the computation and the type of the result; the two are
3138 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
getComputationLHSType()3139 QualType getComputationLHSType() const { return ComputationLHSType; }
setComputationLHSType(QualType T)3140 void setComputationLHSType(QualType T) { ComputationLHSType = T; }
3141
getComputationResultType()3142 QualType getComputationResultType() const { return ComputationResultType; }
setComputationResultType(QualType T)3143 void setComputationResultType(QualType T) { ComputationResultType = T; }
3144
classof(const Stmt * S)3145 static bool classof(const Stmt *S) {
3146 return S->getStmtClass() == CompoundAssignOperatorClass;
3147 }
3148 };
3149
3150 /// AbstractConditionalOperator - An abstract base class for
3151 /// ConditionalOperator and BinaryConditionalOperator.
3152 class AbstractConditionalOperator : public Expr {
3153 SourceLocation QuestionLoc, ColonLoc;
3154 friend class ASTStmtReader;
3155
3156 protected:
AbstractConditionalOperator(StmtClass SC,QualType T,ExprValueKind VK,ExprObjectKind OK,bool TD,bool VD,bool ID,bool ContainsUnexpandedParameterPack,SourceLocation qloc,SourceLocation cloc)3157 AbstractConditionalOperator(StmtClass SC, QualType T,
3158 ExprValueKind VK, ExprObjectKind OK,
3159 bool TD, bool VD, bool ID,
3160 bool ContainsUnexpandedParameterPack,
3161 SourceLocation qloc,
3162 SourceLocation cloc)
3163 : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack),
3164 QuestionLoc(qloc), ColonLoc(cloc) {}
3165
AbstractConditionalOperator(StmtClass SC,EmptyShell Empty)3166 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
3167 : Expr(SC, Empty) { }
3168
3169 public:
3170 // getCond - Return the expression representing the condition for
3171 // the ?: operator.
3172 Expr *getCond() const;
3173
3174 // getTrueExpr - Return the subexpression representing the value of
3175 // the expression if the condition evaluates to true.
3176 Expr *getTrueExpr() const;
3177
3178 // getFalseExpr - Return the subexpression representing the value of
3179 // the expression if the condition evaluates to false. This is
3180 // the same as getRHS.
3181 Expr *getFalseExpr() const;
3182
getQuestionLoc()3183 SourceLocation getQuestionLoc() const { return QuestionLoc; }
getColonLoc()3184 SourceLocation getColonLoc() const { return ColonLoc; }
3185
classof(const Stmt * T)3186 static bool classof(const Stmt *T) {
3187 return T->getStmtClass() == ConditionalOperatorClass ||
3188 T->getStmtClass() == BinaryConditionalOperatorClass;
3189 }
3190 };
3191
3192 /// ConditionalOperator - The ?: ternary operator. The GNU "missing
3193 /// middle" extension is a BinaryConditionalOperator.
3194 class ConditionalOperator : public AbstractConditionalOperator {
3195 enum { COND, LHS, RHS, END_EXPR };
3196 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3197
3198 friend class ASTStmtReader;
3199 public:
ConditionalOperator(Expr * cond,SourceLocation QLoc,Expr * lhs,SourceLocation CLoc,Expr * rhs,QualType t,ExprValueKind VK,ExprObjectKind OK)3200 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
3201 SourceLocation CLoc, Expr *rhs,
3202 QualType t, ExprValueKind VK, ExprObjectKind OK)
3203 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK,
3204 // FIXME: the type of the conditional operator doesn't
3205 // depend on the type of the conditional, but the standard
3206 // seems to imply that it could. File a bug!
3207 (lhs->isTypeDependent() || rhs->isTypeDependent()),
3208 (cond->isValueDependent() || lhs->isValueDependent() ||
3209 rhs->isValueDependent()),
3210 (cond->isInstantiationDependent() ||
3211 lhs->isInstantiationDependent() ||
3212 rhs->isInstantiationDependent()),
3213 (cond->containsUnexpandedParameterPack() ||
3214 lhs->containsUnexpandedParameterPack() ||
3215 rhs->containsUnexpandedParameterPack()),
3216 QLoc, CLoc) {
3217 SubExprs[COND] = cond;
3218 SubExprs[LHS] = lhs;
3219 SubExprs[RHS] = rhs;
3220 }
3221
3222 /// \brief Build an empty conditional operator.
ConditionalOperator(EmptyShell Empty)3223 explicit ConditionalOperator(EmptyShell Empty)
3224 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
3225
3226 // getCond - Return the expression representing the condition for
3227 // the ?: operator.
getCond()3228 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3229
3230 // getTrueExpr - Return the subexpression representing the value of
3231 // the expression if the condition evaluates to true.
getTrueExpr()3232 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
3233
3234 // getFalseExpr - Return the subexpression representing the value of
3235 // the expression if the condition evaluates to false. This is
3236 // the same as getRHS.
getFalseExpr()3237 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
3238
getLHS()3239 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
getRHS()3240 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3241
getLocStart()3242 SourceLocation getLocStart() const LLVM_READONLY {
3243 return getCond()->getLocStart();
3244 }
getLocEnd()3245 SourceLocation getLocEnd() const LLVM_READONLY {
3246 return getRHS()->getLocEnd();
3247 }
3248
classof(const Stmt * T)3249 static bool classof(const Stmt *T) {
3250 return T->getStmtClass() == ConditionalOperatorClass;
3251 }
3252
3253 // Iterators
children()3254 child_range children() {
3255 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3256 }
3257 };
3258
3259 /// BinaryConditionalOperator - The GNU extension to the conditional
3260 /// operator which allows the middle operand to be omitted.
3261 ///
3262 /// This is a different expression kind on the assumption that almost
3263 /// every client ends up needing to know that these are different.
3264 class BinaryConditionalOperator : public AbstractConditionalOperator {
3265 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
3266
3267 /// - the common condition/left-hand-side expression, which will be
3268 /// evaluated as the opaque value
3269 /// - the condition, expressed in terms of the opaque value
3270 /// - the left-hand-side, expressed in terms of the opaque value
3271 /// - the right-hand-side
3272 Stmt *SubExprs[NUM_SUBEXPRS];
3273 OpaqueValueExpr *OpaqueValue;
3274
3275 friend class ASTStmtReader;
3276 public:
BinaryConditionalOperator(Expr * common,OpaqueValueExpr * opaqueValue,Expr * cond,Expr * lhs,Expr * rhs,SourceLocation qloc,SourceLocation cloc,QualType t,ExprValueKind VK,ExprObjectKind OK)3277 BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
3278 Expr *cond, Expr *lhs, Expr *rhs,
3279 SourceLocation qloc, SourceLocation cloc,
3280 QualType t, ExprValueKind VK, ExprObjectKind OK)
3281 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
3282 (common->isTypeDependent() || rhs->isTypeDependent()),
3283 (common->isValueDependent() || rhs->isValueDependent()),
3284 (common->isInstantiationDependent() ||
3285 rhs->isInstantiationDependent()),
3286 (common->containsUnexpandedParameterPack() ||
3287 rhs->containsUnexpandedParameterPack()),
3288 qloc, cloc),
3289 OpaqueValue(opaqueValue) {
3290 SubExprs[COMMON] = common;
3291 SubExprs[COND] = cond;
3292 SubExprs[LHS] = lhs;
3293 SubExprs[RHS] = rhs;
3294 assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value");
3295 }
3296
3297 /// \brief Build an empty conditional operator.
BinaryConditionalOperator(EmptyShell Empty)3298 explicit BinaryConditionalOperator(EmptyShell Empty)
3299 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
3300
3301 /// \brief getCommon - Return the common expression, written to the
3302 /// left of the condition. The opaque value will be bound to the
3303 /// result of this expression.
getCommon()3304 Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
3305
3306 /// \brief getOpaqueValue - Return the opaque value placeholder.
getOpaqueValue()3307 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
3308
3309 /// \brief getCond - Return the condition expression; this is defined
3310 /// in terms of the opaque value.
getCond()3311 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3312
3313 /// \brief getTrueExpr - Return the subexpression which will be
3314 /// evaluated if the condition evaluates to true; this is defined
3315 /// in terms of the opaque value.
getTrueExpr()3316 Expr *getTrueExpr() const {
3317 return cast<Expr>(SubExprs[LHS]);
3318 }
3319
3320 /// \brief getFalseExpr - Return the subexpression which will be
3321 /// evaluated if the condnition evaluates to false; this is
3322 /// defined in terms of the opaque value.
getFalseExpr()3323 Expr *getFalseExpr() const {
3324 return cast<Expr>(SubExprs[RHS]);
3325 }
3326
getLocStart()3327 SourceLocation getLocStart() const LLVM_READONLY {
3328 return getCommon()->getLocStart();
3329 }
getLocEnd()3330 SourceLocation getLocEnd() const LLVM_READONLY {
3331 return getFalseExpr()->getLocEnd();
3332 }
3333
classof(const Stmt * T)3334 static bool classof(const Stmt *T) {
3335 return T->getStmtClass() == BinaryConditionalOperatorClass;
3336 }
3337
3338 // Iterators
children()3339 child_range children() {
3340 return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
3341 }
3342 };
3343
getCond()3344 inline Expr *AbstractConditionalOperator::getCond() const {
3345 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3346 return co->getCond();
3347 return cast<BinaryConditionalOperator>(this)->getCond();
3348 }
3349
getTrueExpr()3350 inline Expr *AbstractConditionalOperator::getTrueExpr() const {
3351 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3352 return co->getTrueExpr();
3353 return cast<BinaryConditionalOperator>(this)->getTrueExpr();
3354 }
3355
getFalseExpr()3356 inline Expr *AbstractConditionalOperator::getFalseExpr() const {
3357 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3358 return co->getFalseExpr();
3359 return cast<BinaryConditionalOperator>(this)->getFalseExpr();
3360 }
3361
3362 /// AddrLabelExpr - The GNU address of label extension, representing &&label.
3363 class AddrLabelExpr : public Expr {
3364 SourceLocation AmpAmpLoc, LabelLoc;
3365 LabelDecl *Label;
3366 public:
AddrLabelExpr(SourceLocation AALoc,SourceLocation LLoc,LabelDecl * L,QualType t)3367 AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
3368 QualType t)
3369 : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false,
3370 false),
3371 AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
3372
3373 /// \brief Build an empty address of a label expression.
AddrLabelExpr(EmptyShell Empty)3374 explicit AddrLabelExpr(EmptyShell Empty)
3375 : Expr(AddrLabelExprClass, Empty) { }
3376
getAmpAmpLoc()3377 SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
setAmpAmpLoc(SourceLocation L)3378 void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
getLabelLoc()3379 SourceLocation getLabelLoc() const { return LabelLoc; }
setLabelLoc(SourceLocation L)3380 void setLabelLoc(SourceLocation L) { LabelLoc = L; }
3381
getLocStart()3382 SourceLocation getLocStart() const LLVM_READONLY { return AmpAmpLoc; }
getLocEnd()3383 SourceLocation getLocEnd() const LLVM_READONLY { return LabelLoc; }
3384
getLabel()3385 LabelDecl *getLabel() const { return Label; }
setLabel(LabelDecl * L)3386 void setLabel(LabelDecl *L) { Label = L; }
3387
classof(const Stmt * T)3388 static bool classof(const Stmt *T) {
3389 return T->getStmtClass() == AddrLabelExprClass;
3390 }
3391
3392 // Iterators
children()3393 child_range children() { return child_range(); }
3394 };
3395
3396 /// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
3397 /// The StmtExpr contains a single CompoundStmt node, which it evaluates and
3398 /// takes the value of the last subexpression.
3399 ///
3400 /// A StmtExpr is always an r-value; values "returned" out of a
3401 /// StmtExpr will be copied.
3402 class StmtExpr : public Expr {
3403 Stmt *SubStmt;
3404 SourceLocation LParenLoc, RParenLoc;
3405 public:
3406 // FIXME: Does type-dependence need to be computed differently?
3407 // FIXME: Do we need to compute instantiation instantiation-dependence for
3408 // statements? (ugh!)
StmtExpr(CompoundStmt * substmt,QualType T,SourceLocation lp,SourceLocation rp)3409 StmtExpr(CompoundStmt *substmt, QualType T,
3410 SourceLocation lp, SourceLocation rp) :
3411 Expr(StmtExprClass, T, VK_RValue, OK_Ordinary,
3412 T->isDependentType(), false, false, false),
3413 SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { }
3414
3415 /// \brief Build an empty statement expression.
StmtExpr(EmptyShell Empty)3416 explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
3417
getSubStmt()3418 CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
getSubStmt()3419 const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
setSubStmt(CompoundStmt * S)3420 void setSubStmt(CompoundStmt *S) { SubStmt = S; }
3421
getLocStart()3422 SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; }
getLocEnd()3423 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3424
getLParenLoc()3425 SourceLocation getLParenLoc() const { return LParenLoc; }
setLParenLoc(SourceLocation L)3426 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
getRParenLoc()3427 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)3428 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3429
classof(const Stmt * T)3430 static bool classof(const Stmt *T) {
3431 return T->getStmtClass() == StmtExprClass;
3432 }
3433
3434 // Iterators
children()3435 child_range children() { return child_range(&SubStmt, &SubStmt+1); }
3436 };
3437
3438
3439 /// ShuffleVectorExpr - clang-specific builtin-in function
3440 /// __builtin_shufflevector.
3441 /// This AST node represents a operator that does a constant
3442 /// shuffle, similar to LLVM's shufflevector instruction. It takes
3443 /// two vectors and a variable number of constant indices,
3444 /// and returns the appropriately shuffled vector.
3445 class ShuffleVectorExpr : public Expr {
3446 SourceLocation BuiltinLoc, RParenLoc;
3447
3448 // SubExprs - the list of values passed to the __builtin_shufflevector
3449 // function. The first two are vectors, and the rest are constant
3450 // indices. The number of values in this list is always
3451 // 2+the number of indices in the vector type.
3452 Stmt **SubExprs;
3453 unsigned NumExprs;
3454
3455 public:
3456 ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type,
3457 SourceLocation BLoc, SourceLocation RP);
3458
3459 /// \brief Build an empty vector-shuffle expression.
ShuffleVectorExpr(EmptyShell Empty)3460 explicit ShuffleVectorExpr(EmptyShell Empty)
3461 : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { }
3462
getBuiltinLoc()3463 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
setBuiltinLoc(SourceLocation L)3464 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3465
getRParenLoc()3466 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)3467 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3468
getLocStart()3469 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
getLocEnd()3470 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3471
classof(const Stmt * T)3472 static bool classof(const Stmt *T) {
3473 return T->getStmtClass() == ShuffleVectorExprClass;
3474 }
3475
3476 /// getNumSubExprs - Return the size of the SubExprs array. This includes the
3477 /// constant expression, the actual arguments passed in, and the function
3478 /// pointers.
getNumSubExprs()3479 unsigned getNumSubExprs() const { return NumExprs; }
3480
3481 /// \brief Retrieve the array of expressions.
getSubExprs()3482 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
3483
3484 /// getExpr - Return the Expr at the specified index.
getExpr(unsigned Index)3485 Expr *getExpr(unsigned Index) {
3486 assert((Index < NumExprs) && "Arg access out of range!");
3487 return cast<Expr>(SubExprs[Index]);
3488 }
getExpr(unsigned Index)3489 const Expr *getExpr(unsigned Index) const {
3490 assert((Index < NumExprs) && "Arg access out of range!");
3491 return cast<Expr>(SubExprs[Index]);
3492 }
3493
3494 void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs);
3495
getShuffleMaskIdx(const ASTContext & Ctx,unsigned N)3496 llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const {
3497 assert((N < NumExprs - 2) && "Shuffle idx out of range!");
3498 return getExpr(N+2)->EvaluateKnownConstInt(Ctx);
3499 }
3500
3501 // Iterators
children()3502 child_range children() {
3503 return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
3504 }
3505 };
3506
3507 /// ConvertVectorExpr - Clang builtin function __builtin_convertvector
3508 /// This AST node provides support for converting a vector type to another
3509 /// vector type of the same arity.
3510 class ConvertVectorExpr : public Expr {
3511 private:
3512 Stmt *SrcExpr;
3513 TypeSourceInfo *TInfo;
3514 SourceLocation BuiltinLoc, RParenLoc;
3515
3516 friend class ASTReader;
3517 friend class ASTStmtReader;
ConvertVectorExpr(EmptyShell Empty)3518 explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {}
3519
3520 public:
ConvertVectorExpr(Expr * SrcExpr,TypeSourceInfo * TI,QualType DstType,ExprValueKind VK,ExprObjectKind OK,SourceLocation BuiltinLoc,SourceLocation RParenLoc)3521 ConvertVectorExpr(Expr* SrcExpr, TypeSourceInfo *TI, QualType DstType,
3522 ExprValueKind VK, ExprObjectKind OK,
3523 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
3524 : Expr(ConvertVectorExprClass, DstType, VK, OK,
3525 DstType->isDependentType(),
3526 DstType->isDependentType() || SrcExpr->isValueDependent(),
3527 (DstType->isInstantiationDependentType() ||
3528 SrcExpr->isInstantiationDependent()),
3529 (DstType->containsUnexpandedParameterPack() ||
3530 SrcExpr->containsUnexpandedParameterPack())),
3531 SrcExpr(SrcExpr), TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
3532
3533 /// getSrcExpr - Return the Expr to be converted.
getSrcExpr()3534 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
3535
3536 /// getTypeSourceInfo - Return the destination type.
getTypeSourceInfo()3537 TypeSourceInfo *getTypeSourceInfo() const {
3538 return TInfo;
3539 }
setTypeSourceInfo(TypeSourceInfo * ti)3540 void setTypeSourceInfo(TypeSourceInfo *ti) {
3541 TInfo = ti;
3542 }
3543
3544 /// getBuiltinLoc - Return the location of the __builtin_convertvector token.
getBuiltinLoc()3545 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3546
3547 /// getRParenLoc - Return the location of final right parenthesis.
getRParenLoc()3548 SourceLocation getRParenLoc() const { return RParenLoc; }
3549
getLocStart()3550 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
getLocEnd()3551 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3552
classof(const Stmt * T)3553 static bool classof(const Stmt *T) {
3554 return T->getStmtClass() == ConvertVectorExprClass;
3555 }
3556
3557 // Iterators
children()3558 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
3559 };
3560
3561 /// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
3562 /// This AST node is similar to the conditional operator (?:) in C, with
3563 /// the following exceptions:
3564 /// - the test expression must be a integer constant expression.
3565 /// - the expression returned acts like the chosen subexpression in every
3566 /// visible way: the type is the same as that of the chosen subexpression,
3567 /// and all predicates (whether it's an l-value, whether it's an integer
3568 /// constant expression, etc.) return the same result as for the chosen
3569 /// sub-expression.
3570 class ChooseExpr : public Expr {
3571 enum { COND, LHS, RHS, END_EXPR };
3572 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3573 SourceLocation BuiltinLoc, RParenLoc;
3574 bool CondIsTrue;
3575 public:
ChooseExpr(SourceLocation BLoc,Expr * cond,Expr * lhs,Expr * rhs,QualType t,ExprValueKind VK,ExprObjectKind OK,SourceLocation RP,bool condIsTrue,bool TypeDependent,bool ValueDependent)3576 ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs,
3577 QualType t, ExprValueKind VK, ExprObjectKind OK,
3578 SourceLocation RP, bool condIsTrue,
3579 bool TypeDependent, bool ValueDependent)
3580 : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent,
3581 (cond->isInstantiationDependent() ||
3582 lhs->isInstantiationDependent() ||
3583 rhs->isInstantiationDependent()),
3584 (cond->containsUnexpandedParameterPack() ||
3585 lhs->containsUnexpandedParameterPack() ||
3586 rhs->containsUnexpandedParameterPack())),
3587 BuiltinLoc(BLoc), RParenLoc(RP), CondIsTrue(condIsTrue) {
3588 SubExprs[COND] = cond;
3589 SubExprs[LHS] = lhs;
3590 SubExprs[RHS] = rhs;
3591 }
3592
3593 /// \brief Build an empty __builtin_choose_expr.
ChooseExpr(EmptyShell Empty)3594 explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
3595
3596 /// isConditionTrue - Return whether the condition is true (i.e. not
3597 /// equal to zero).
isConditionTrue()3598 bool isConditionTrue() const {
3599 assert(!isConditionDependent() &&
3600 "Dependent condition isn't true or false");
3601 return CondIsTrue;
3602 }
setIsConditionTrue(bool isTrue)3603 void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; }
3604
isConditionDependent()3605 bool isConditionDependent() const {
3606 return getCond()->isTypeDependent() || getCond()->isValueDependent();
3607 }
3608
3609 /// getChosenSubExpr - Return the subexpression chosen according to the
3610 /// condition.
getChosenSubExpr()3611 Expr *getChosenSubExpr() const {
3612 return isConditionTrue() ? getLHS() : getRHS();
3613 }
3614
getCond()3615 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
setCond(Expr * E)3616 void setCond(Expr *E) { SubExprs[COND] = E; }
getLHS()3617 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
setLHS(Expr * E)3618 void setLHS(Expr *E) { SubExprs[LHS] = E; }
getRHS()3619 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
setRHS(Expr * E)3620 void setRHS(Expr *E) { SubExprs[RHS] = E; }
3621
getBuiltinLoc()3622 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
setBuiltinLoc(SourceLocation L)3623 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3624
getRParenLoc()3625 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)3626 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3627
getLocStart()3628 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
getLocEnd()3629 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3630
classof(const Stmt * T)3631 static bool classof(const Stmt *T) {
3632 return T->getStmtClass() == ChooseExprClass;
3633 }
3634
3635 // Iterators
children()3636 child_range children() {
3637 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3638 }
3639 };
3640
3641 /// GNUNullExpr - Implements the GNU __null extension, which is a name
3642 /// for a null pointer constant that has integral type (e.g., int or
3643 /// long) and is the same size and alignment as a pointer. The __null
3644 /// extension is typically only used by system headers, which define
3645 /// NULL as __null in C++ rather than using 0 (which is an integer
3646 /// that may not match the size of a pointer).
3647 class GNUNullExpr : public Expr {
3648 /// TokenLoc - The location of the __null keyword.
3649 SourceLocation TokenLoc;
3650
3651 public:
GNUNullExpr(QualType Ty,SourceLocation Loc)3652 GNUNullExpr(QualType Ty, SourceLocation Loc)
3653 : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false,
3654 false),
3655 TokenLoc(Loc) { }
3656
3657 /// \brief Build an empty GNU __null expression.
GNUNullExpr(EmptyShell Empty)3658 explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
3659
3660 /// getTokenLocation - The location of the __null token.
getTokenLocation()3661 SourceLocation getTokenLocation() const { return TokenLoc; }
setTokenLocation(SourceLocation L)3662 void setTokenLocation(SourceLocation L) { TokenLoc = L; }
3663
getLocStart()3664 SourceLocation getLocStart() const LLVM_READONLY { return TokenLoc; }
getLocEnd()3665 SourceLocation getLocEnd() const LLVM_READONLY { return TokenLoc; }
3666
classof(const Stmt * T)3667 static bool classof(const Stmt *T) {
3668 return T->getStmtClass() == GNUNullExprClass;
3669 }
3670
3671 // Iterators
children()3672 child_range children() { return child_range(); }
3673 };
3674
3675 /// VAArgExpr, used for the builtin function __builtin_va_arg.
3676 class VAArgExpr : public Expr {
3677 Stmt *Val;
3678 TypeSourceInfo *TInfo;
3679 SourceLocation BuiltinLoc, RParenLoc;
3680 public:
VAArgExpr(SourceLocation BLoc,Expr * e,TypeSourceInfo * TInfo,SourceLocation RPLoc,QualType t)3681 VAArgExpr(SourceLocation BLoc, Expr* e, TypeSourceInfo *TInfo,
3682 SourceLocation RPLoc, QualType t)
3683 : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary,
3684 t->isDependentType(), false,
3685 (TInfo->getType()->isInstantiationDependentType() ||
3686 e->isInstantiationDependent()),
3687 (TInfo->getType()->containsUnexpandedParameterPack() ||
3688 e->containsUnexpandedParameterPack())),
3689 Val(e), TInfo(TInfo),
3690 BuiltinLoc(BLoc),
3691 RParenLoc(RPLoc) { }
3692
3693 /// \brief Create an empty __builtin_va_arg expression.
VAArgExpr(EmptyShell Empty)3694 explicit VAArgExpr(EmptyShell Empty) : Expr(VAArgExprClass, Empty) { }
3695
getSubExpr()3696 const Expr *getSubExpr() const { return cast<Expr>(Val); }
getSubExpr()3697 Expr *getSubExpr() { return cast<Expr>(Val); }
setSubExpr(Expr * E)3698 void setSubExpr(Expr *E) { Val = E; }
3699
getWrittenTypeInfo()3700 TypeSourceInfo *getWrittenTypeInfo() const { return TInfo; }
setWrittenTypeInfo(TypeSourceInfo * TI)3701 void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo = TI; }
3702
getBuiltinLoc()3703 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
setBuiltinLoc(SourceLocation L)3704 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3705
getRParenLoc()3706 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)3707 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3708
getLocStart()3709 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
getLocEnd()3710 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3711
classof(const Stmt * T)3712 static bool classof(const Stmt *T) {
3713 return T->getStmtClass() == VAArgExprClass;
3714 }
3715
3716 // Iterators
children()3717 child_range children() { return child_range(&Val, &Val+1); }
3718 };
3719
3720 /// @brief Describes an C or C++ initializer list.
3721 ///
3722 /// InitListExpr describes an initializer list, which can be used to
3723 /// initialize objects of different types, including
3724 /// struct/class/union types, arrays, and vectors. For example:
3725 ///
3726 /// @code
3727 /// struct foo x = { 1, { 2, 3 } };
3728 /// @endcode
3729 ///
3730 /// Prior to semantic analysis, an initializer list will represent the
3731 /// initializer list as written by the user, but will have the
3732 /// placeholder type "void". This initializer list is called the
3733 /// syntactic form of the initializer, and may contain C99 designated
3734 /// initializers (represented as DesignatedInitExprs), initializations
3735 /// of subobject members without explicit braces, and so on. Clients
3736 /// interested in the original syntax of the initializer list should
3737 /// use the syntactic form of the initializer list.
3738 ///
3739 /// After semantic analysis, the initializer list will represent the
3740 /// semantic form of the initializer, where the initializations of all
3741 /// subobjects are made explicit with nested InitListExpr nodes and
3742 /// C99 designators have been eliminated by placing the designated
3743 /// initializations into the subobject they initialize. Additionally,
3744 /// any "holes" in the initialization, where no initializer has been
3745 /// specified for a particular subobject, will be replaced with
3746 /// implicitly-generated ImplicitValueInitExpr expressions that
3747 /// value-initialize the subobjects. Note, however, that the
3748 /// initializer lists may still have fewer initializers than there are
3749 /// elements to initialize within the object.
3750 ///
3751 /// After semantic analysis has completed, given an initializer list,
3752 /// method isSemanticForm() returns true if and only if this is the
3753 /// semantic form of the initializer list (note: the same AST node
3754 /// may at the same time be the syntactic form).
3755 /// Given the semantic form of the initializer list, one can retrieve
3756 /// the syntactic form of that initializer list (when different)
3757 /// using method getSyntacticForm(); the method returns null if applied
3758 /// to a initializer list which is already in syntactic form.
3759 /// Similarly, given the syntactic form (i.e., an initializer list such
3760 /// that isSemanticForm() returns false), one can retrieve the semantic
3761 /// form using method getSemanticForm().
3762 /// Since many initializer lists have the same syntactic and semantic forms,
3763 /// getSyntacticForm() may return NULL, indicating that the current
3764 /// semantic initializer list also serves as its syntactic form.
3765 class InitListExpr : public Expr {
3766 // FIXME: Eliminate this vector in favor of ASTContext allocation
3767 typedef ASTVector<Stmt *> InitExprsTy;
3768 InitExprsTy InitExprs;
3769 SourceLocation LBraceLoc, RBraceLoc;
3770
3771 /// The alternative form of the initializer list (if it exists).
3772 /// The int part of the pair stores whether this initializer list is
3773 /// in semantic form. If not null, the pointer points to:
3774 /// - the syntactic form, if this is in semantic form;
3775 /// - the semantic form, if this is in syntactic form.
3776 llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm;
3777
3778 /// \brief Either:
3779 /// If this initializer list initializes an array with more elements than
3780 /// there are initializers in the list, specifies an expression to be used
3781 /// for value initialization of the rest of the elements.
3782 /// Or
3783 /// If this initializer list initializes a union, specifies which
3784 /// field within the union will be initialized.
3785 llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
3786
3787 public:
3788 InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
3789 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc);
3790
3791 /// \brief Build an empty initializer list.
InitListExpr(EmptyShell Empty)3792 explicit InitListExpr(EmptyShell Empty)
3793 : Expr(InitListExprClass, Empty) { }
3794
getNumInits()3795 unsigned getNumInits() const { return InitExprs.size(); }
3796
3797 /// \brief Retrieve the set of initializers.
getInits()3798 Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
3799
getInit(unsigned Init)3800 const Expr *getInit(unsigned Init) const {
3801 assert(Init < getNumInits() && "Initializer access out of range!");
3802 return cast_or_null<Expr>(InitExprs[Init]);
3803 }
3804
getInit(unsigned Init)3805 Expr *getInit(unsigned Init) {
3806 assert(Init < getNumInits() && "Initializer access out of range!");
3807 return cast_or_null<Expr>(InitExprs[Init]);
3808 }
3809
setInit(unsigned Init,Expr * expr)3810 void setInit(unsigned Init, Expr *expr) {
3811 assert(Init < getNumInits() && "Initializer access out of range!");
3812 InitExprs[Init] = expr;
3813
3814 if (expr) {
3815 ExprBits.TypeDependent |= expr->isTypeDependent();
3816 ExprBits.ValueDependent |= expr->isValueDependent();
3817 ExprBits.InstantiationDependent |= expr->isInstantiationDependent();
3818 ExprBits.ContainsUnexpandedParameterPack |=
3819 expr->containsUnexpandedParameterPack();
3820 }
3821 }
3822
3823 /// \brief Reserve space for some number of initializers.
3824 void reserveInits(const ASTContext &C, unsigned NumInits);
3825
3826 /// @brief Specify the number of initializers
3827 ///
3828 /// If there are more than @p NumInits initializers, the remaining
3829 /// initializers will be destroyed. If there are fewer than @p
3830 /// NumInits initializers, NULL expressions will be added for the
3831 /// unknown initializers.
3832 void resizeInits(const ASTContext &Context, unsigned NumInits);
3833
3834 /// @brief Updates the initializer at index @p Init with the new
3835 /// expression @p expr, and returns the old expression at that
3836 /// location.
3837 ///
3838 /// When @p Init is out of range for this initializer list, the
3839 /// initializer list will be extended with NULL expressions to
3840 /// accommodate the new entry.
3841 Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr);
3842
3843 /// \brief If this initializer list initializes an array with more elements
3844 /// than there are initializers in the list, specifies an expression to be
3845 /// used for value initialization of the rest of the elements.
getArrayFiller()3846 Expr *getArrayFiller() {
3847 return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>();
3848 }
getArrayFiller()3849 const Expr *getArrayFiller() const {
3850 return const_cast<InitListExpr *>(this)->getArrayFiller();
3851 }
3852 void setArrayFiller(Expr *filler);
3853
3854 /// \brief Return true if this is an array initializer and its array "filler"
3855 /// has been set.
hasArrayFiller()3856 bool hasArrayFiller() const { return getArrayFiller(); }
3857
3858 /// \brief If this initializes a union, specifies which field in the
3859 /// union to initialize.
3860 ///
3861 /// Typically, this field is the first named field within the
3862 /// union. However, a designated initializer can specify the
3863 /// initialization of a different field within the union.
getInitializedFieldInUnion()3864 FieldDecl *getInitializedFieldInUnion() {
3865 return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>();
3866 }
getInitializedFieldInUnion()3867 const FieldDecl *getInitializedFieldInUnion() const {
3868 return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
3869 }
setInitializedFieldInUnion(FieldDecl * FD)3870 void setInitializedFieldInUnion(FieldDecl *FD) {
3871 assert((FD == nullptr
3872 || getInitializedFieldInUnion() == nullptr
3873 || getInitializedFieldInUnion() == FD)
3874 && "Only one field of a union may be initialized at a time!");
3875 ArrayFillerOrUnionFieldInit = FD;
3876 }
3877
3878 // Explicit InitListExpr's originate from source code (and have valid source
3879 // locations). Implicit InitListExpr's are created by the semantic analyzer.
isExplicit()3880 bool isExplicit() {
3881 return LBraceLoc.isValid() && RBraceLoc.isValid();
3882 }
3883
3884 // Is this an initializer for an array of characters, initialized by a string
3885 // literal or an @encode?
3886 bool isStringLiteralInit() const;
3887
getLBraceLoc()3888 SourceLocation getLBraceLoc() const { return LBraceLoc; }
setLBraceLoc(SourceLocation Loc)3889 void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
getRBraceLoc()3890 SourceLocation getRBraceLoc() const { return RBraceLoc; }
setRBraceLoc(SourceLocation Loc)3891 void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
3892
isSemanticForm()3893 bool isSemanticForm() const { return AltForm.getInt(); }
getSemanticForm()3894 InitListExpr *getSemanticForm() const {
3895 return isSemanticForm() ? nullptr : AltForm.getPointer();
3896 }
getSyntacticForm()3897 InitListExpr *getSyntacticForm() const {
3898 return isSemanticForm() ? AltForm.getPointer() : nullptr;
3899 }
3900
setSyntacticForm(InitListExpr * Init)3901 void setSyntacticForm(InitListExpr *Init) {
3902 AltForm.setPointer(Init);
3903 AltForm.setInt(true);
3904 Init->AltForm.setPointer(this);
3905 Init->AltForm.setInt(false);
3906 }
3907
hadArrayRangeDesignator()3908 bool hadArrayRangeDesignator() const {
3909 return InitListExprBits.HadArrayRangeDesignator != 0;
3910 }
3911 void sawArrayRangeDesignator(bool ARD = true) {
3912 InitListExprBits.HadArrayRangeDesignator = ARD;
3913 }
3914
3915 SourceLocation getLocStart() const LLVM_READONLY;
3916 SourceLocation getLocEnd() const LLVM_READONLY;
3917
classof(const Stmt * T)3918 static bool classof(const Stmt *T) {
3919 return T->getStmtClass() == InitListExprClass;
3920 }
3921
3922 // Iterators
children()3923 child_range children() {
3924 // FIXME: This does not include the array filler expression.
3925 if (InitExprs.empty()) return child_range();
3926 return child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
3927 }
3928
3929 typedef InitExprsTy::iterator iterator;
3930 typedef InitExprsTy::const_iterator const_iterator;
3931 typedef InitExprsTy::reverse_iterator reverse_iterator;
3932 typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
3933
begin()3934 iterator begin() { return InitExprs.begin(); }
begin()3935 const_iterator begin() const { return InitExprs.begin(); }
end()3936 iterator end() { return InitExprs.end(); }
end()3937 const_iterator end() const { return InitExprs.end(); }
rbegin()3938 reverse_iterator rbegin() { return InitExprs.rbegin(); }
rbegin()3939 const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
rend()3940 reverse_iterator rend() { return InitExprs.rend(); }
rend()3941 const_reverse_iterator rend() const { return InitExprs.rend(); }
3942
3943 friend class ASTStmtReader;
3944 friend class ASTStmtWriter;
3945 };
3946
3947 /// @brief Represents a C99 designated initializer expression.
3948 ///
3949 /// A designated initializer expression (C99 6.7.8) contains one or
3950 /// more designators (which can be field designators, array
3951 /// designators, or GNU array-range designators) followed by an
3952 /// expression that initializes the field or element(s) that the
3953 /// designators refer to. For example, given:
3954 ///
3955 /// @code
3956 /// struct point {
3957 /// double x;
3958 /// double y;
3959 /// };
3960 /// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
3961 /// @endcode
3962 ///
3963 /// The InitListExpr contains three DesignatedInitExprs, the first of
3964 /// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
3965 /// designators, one array designator for @c [2] followed by one field
3966 /// designator for @c .y. The initialization expression will be 1.0.
3967 class DesignatedInitExpr : public Expr {
3968 public:
3969 /// \brief Forward declaration of the Designator class.
3970 class Designator;
3971
3972 private:
3973 /// The location of the '=' or ':' prior to the actual initializer
3974 /// expression.
3975 SourceLocation EqualOrColonLoc;
3976
3977 /// Whether this designated initializer used the GNU deprecated
3978 /// syntax rather than the C99 '=' syntax.
3979 bool GNUSyntax : 1;
3980
3981 /// The number of designators in this initializer expression.
3982 unsigned NumDesignators : 15;
3983
3984 /// The number of subexpressions of this initializer expression,
3985 /// which contains both the initializer and any additional
3986 /// expressions used by array and array-range designators.
3987 unsigned NumSubExprs : 16;
3988
3989 /// \brief The designators in this designated initialization
3990 /// expression.
3991 Designator *Designators;
3992
3993
3994 DesignatedInitExpr(const ASTContext &C, QualType Ty, unsigned NumDesignators,
3995 const Designator *Designators,
3996 SourceLocation EqualOrColonLoc, bool GNUSyntax,
3997 ArrayRef<Expr*> IndexExprs, Expr *Init);
3998
DesignatedInitExpr(unsigned NumSubExprs)3999 explicit DesignatedInitExpr(unsigned NumSubExprs)
4000 : Expr(DesignatedInitExprClass, EmptyShell()),
4001 NumDesignators(0), NumSubExprs(NumSubExprs), Designators(nullptr) { }
4002
4003 public:
4004 /// A field designator, e.g., ".x".
4005 struct FieldDesignator {
4006 /// Refers to the field that is being initialized. The low bit
4007 /// of this field determines whether this is actually a pointer
4008 /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
4009 /// initially constructed, a field designator will store an
4010 /// IdentifierInfo*. After semantic analysis has resolved that
4011 /// name, the field designator will instead store a FieldDecl*.
4012 uintptr_t NameOrField;
4013
4014 /// The location of the '.' in the designated initializer.
4015 unsigned DotLoc;
4016
4017 /// The location of the field name in the designated initializer.
4018 unsigned FieldLoc;
4019 };
4020
4021 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
4022 struct ArrayOrRangeDesignator {
4023 /// Location of the first index expression within the designated
4024 /// initializer expression's list of subexpressions.
4025 unsigned Index;
4026 /// The location of the '[' starting the array range designator.
4027 unsigned LBracketLoc;
4028 /// The location of the ellipsis separating the start and end
4029 /// indices. Only valid for GNU array-range designators.
4030 unsigned EllipsisLoc;
4031 /// The location of the ']' terminating the array range designator.
4032 unsigned RBracketLoc;
4033 };
4034
4035 /// @brief Represents a single C99 designator.
4036 ///
4037 /// @todo This class is infuriatingly similar to clang::Designator,
4038 /// but minor differences (storing indices vs. storing pointers)
4039 /// keep us from reusing it. Try harder, later, to rectify these
4040 /// differences.
4041 class Designator {
4042 /// @brief The kind of designator this describes.
4043 enum {
4044 FieldDesignator,
4045 ArrayDesignator,
4046 ArrayRangeDesignator
4047 } Kind;
4048
4049 union {
4050 /// A field designator, e.g., ".x".
4051 struct FieldDesignator Field;
4052 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
4053 struct ArrayOrRangeDesignator ArrayOrRange;
4054 };
4055 friend class DesignatedInitExpr;
4056
4057 public:
Designator()4058 Designator() {}
4059
4060 /// @brief Initializes a field designator.
Designator(const IdentifierInfo * FieldName,SourceLocation DotLoc,SourceLocation FieldLoc)4061 Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
4062 SourceLocation FieldLoc)
4063 : Kind(FieldDesignator) {
4064 Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
4065 Field.DotLoc = DotLoc.getRawEncoding();
4066 Field.FieldLoc = FieldLoc.getRawEncoding();
4067 }
4068
4069 /// @brief Initializes an array designator.
Designator(unsigned Index,SourceLocation LBracketLoc,SourceLocation RBracketLoc)4070 Designator(unsigned Index, SourceLocation LBracketLoc,
4071 SourceLocation RBracketLoc)
4072 : Kind(ArrayDesignator) {
4073 ArrayOrRange.Index = Index;
4074 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4075 ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
4076 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4077 }
4078
4079 /// @brief Initializes a GNU array-range designator.
Designator(unsigned Index,SourceLocation LBracketLoc,SourceLocation EllipsisLoc,SourceLocation RBracketLoc)4080 Designator(unsigned Index, SourceLocation LBracketLoc,
4081 SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
4082 : Kind(ArrayRangeDesignator) {
4083 ArrayOrRange.Index = Index;
4084 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4085 ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
4086 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4087 }
4088
isFieldDesignator()4089 bool isFieldDesignator() const { return Kind == FieldDesignator; }
isArrayDesignator()4090 bool isArrayDesignator() const { return Kind == ArrayDesignator; }
isArrayRangeDesignator()4091 bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
4092
4093 IdentifierInfo *getFieldName() const;
4094
getField()4095 FieldDecl *getField() const {
4096 assert(Kind == FieldDesignator && "Only valid on a field designator");
4097 if (Field.NameOrField & 0x01)
4098 return nullptr;
4099 else
4100 return reinterpret_cast<FieldDecl *>(Field.NameOrField);
4101 }
4102
setField(FieldDecl * FD)4103 void setField(FieldDecl *FD) {
4104 assert(Kind == FieldDesignator && "Only valid on a field designator");
4105 Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
4106 }
4107
getDotLoc()4108 SourceLocation getDotLoc() const {
4109 assert(Kind == FieldDesignator && "Only valid on a field designator");
4110 return SourceLocation::getFromRawEncoding(Field.DotLoc);
4111 }
4112
getFieldLoc()4113 SourceLocation getFieldLoc() const {
4114 assert(Kind == FieldDesignator && "Only valid on a field designator");
4115 return SourceLocation::getFromRawEncoding(Field.FieldLoc);
4116 }
4117
getLBracketLoc()4118 SourceLocation getLBracketLoc() const {
4119 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4120 "Only valid on an array or array-range designator");
4121 return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
4122 }
4123
getRBracketLoc()4124 SourceLocation getRBracketLoc() const {
4125 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4126 "Only valid on an array or array-range designator");
4127 return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
4128 }
4129
getEllipsisLoc()4130 SourceLocation getEllipsisLoc() const {
4131 assert(Kind == ArrayRangeDesignator &&
4132 "Only valid on an array-range designator");
4133 return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
4134 }
4135
getFirstExprIndex()4136 unsigned getFirstExprIndex() const {
4137 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4138 "Only valid on an array or array-range designator");
4139 return ArrayOrRange.Index;
4140 }
4141
getLocStart()4142 SourceLocation getLocStart() const LLVM_READONLY {
4143 if (Kind == FieldDesignator)
4144 return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
4145 else
4146 return getLBracketLoc();
4147 }
getLocEnd()4148 SourceLocation getLocEnd() const LLVM_READONLY {
4149 return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc();
4150 }
getSourceRange()4151 SourceRange getSourceRange() const LLVM_READONLY {
4152 return SourceRange(getLocStart(), getLocEnd());
4153 }
4154 };
4155
4156 static DesignatedInitExpr *Create(const ASTContext &C,
4157 Designator *Designators,
4158 unsigned NumDesignators,
4159 ArrayRef<Expr*> IndexExprs,
4160 SourceLocation EqualOrColonLoc,
4161 bool GNUSyntax, Expr *Init);
4162
4163 static DesignatedInitExpr *CreateEmpty(const ASTContext &C,
4164 unsigned NumIndexExprs);
4165
4166 /// @brief Returns the number of designators in this initializer.
size()4167 unsigned size() const { return NumDesignators; }
4168
4169 // Iterator access to the designators.
4170 typedef Designator *designators_iterator;
designators_begin()4171 designators_iterator designators_begin() { return Designators; }
designators_end()4172 designators_iterator designators_end() {
4173 return Designators + NumDesignators;
4174 }
4175
4176 typedef const Designator *const_designators_iterator;
designators_begin()4177 const_designators_iterator designators_begin() const { return Designators; }
designators_end()4178 const_designators_iterator designators_end() const {
4179 return Designators + NumDesignators;
4180 }
4181
4182 typedef llvm::iterator_range<designators_iterator> designators_range;
designators()4183 designators_range designators() {
4184 return designators_range(designators_begin(), designators_end());
4185 }
4186
4187 typedef llvm::iterator_range<const_designators_iterator>
4188 designators_const_range;
designators()4189 designators_const_range designators() const {
4190 return designators_const_range(designators_begin(), designators_end());
4191 }
4192
4193 typedef std::reverse_iterator<designators_iterator>
4194 reverse_designators_iterator;
designators_rbegin()4195 reverse_designators_iterator designators_rbegin() {
4196 return reverse_designators_iterator(designators_end());
4197 }
designators_rend()4198 reverse_designators_iterator designators_rend() {
4199 return reverse_designators_iterator(designators_begin());
4200 }
4201
4202 typedef std::reverse_iterator<const_designators_iterator>
4203 const_reverse_designators_iterator;
designators_rbegin()4204 const_reverse_designators_iterator designators_rbegin() const {
4205 return const_reverse_designators_iterator(designators_end());
4206 }
designators_rend()4207 const_reverse_designators_iterator designators_rend() const {
4208 return const_reverse_designators_iterator(designators_begin());
4209 }
4210
getDesignator(unsigned Idx)4211 Designator *getDesignator(unsigned Idx) { return &designators_begin()[Idx]; }
4212
4213 void setDesignators(const ASTContext &C, const Designator *Desigs,
4214 unsigned NumDesigs);
4215
4216 Expr *getArrayIndex(const Designator &D) const;
4217 Expr *getArrayRangeStart(const Designator &D) const;
4218 Expr *getArrayRangeEnd(const Designator &D) const;
4219
4220 /// @brief Retrieve the location of the '=' that precedes the
4221 /// initializer value itself, if present.
getEqualOrColonLoc()4222 SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
setEqualOrColonLoc(SourceLocation L)4223 void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
4224
4225 /// @brief Determines whether this designated initializer used the
4226 /// deprecated GNU syntax for designated initializers.
usesGNUSyntax()4227 bool usesGNUSyntax() const { return GNUSyntax; }
setGNUSyntax(bool GNU)4228 void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
4229
4230 /// @brief Retrieve the initializer value.
getInit()4231 Expr *getInit() const {
4232 return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
4233 }
4234
setInit(Expr * init)4235 void setInit(Expr *init) {
4236 *child_begin() = init;
4237 }
4238
4239 /// \brief Retrieve the total number of subexpressions in this
4240 /// designated initializer expression, including the actual
4241 /// initialized value and any expressions that occur within array
4242 /// and array-range designators.
getNumSubExprs()4243 unsigned getNumSubExprs() const { return NumSubExprs; }
4244
getSubExpr(unsigned Idx)4245 Expr *getSubExpr(unsigned Idx) const {
4246 assert(Idx < NumSubExprs && "Subscript out of range");
4247 return cast<Expr>(reinterpret_cast<Stmt *const *>(this + 1)[Idx]);
4248 }
4249
setSubExpr(unsigned Idx,Expr * E)4250 void setSubExpr(unsigned Idx, Expr *E) {
4251 assert(Idx < NumSubExprs && "Subscript out of range");
4252 reinterpret_cast<Stmt **>(this + 1)[Idx] = E;
4253 }
4254
4255 /// \brief Replaces the designator at index @p Idx with the series
4256 /// of designators in [First, Last).
4257 void ExpandDesignator(const ASTContext &C, unsigned Idx,
4258 const Designator *First, const Designator *Last);
4259
4260 SourceRange getDesignatorsSourceRange() const;
4261
4262 SourceLocation getLocStart() const LLVM_READONLY;
4263 SourceLocation getLocEnd() const LLVM_READONLY;
4264
classof(const Stmt * T)4265 static bool classof(const Stmt *T) {
4266 return T->getStmtClass() == DesignatedInitExprClass;
4267 }
4268
4269 // Iterators
children()4270 child_range children() {
4271 Stmt **begin = reinterpret_cast<Stmt**>(this + 1);
4272 return child_range(begin, begin + NumSubExprs);
4273 }
4274 };
4275
4276 /// \brief Represents an implicitly-generated value initialization of
4277 /// an object of a given type.
4278 ///
4279 /// Implicit value initializations occur within semantic initializer
4280 /// list expressions (InitListExpr) as placeholders for subobject
4281 /// initializations not explicitly specified by the user.
4282 ///
4283 /// \see InitListExpr
4284 class ImplicitValueInitExpr : public Expr {
4285 public:
ImplicitValueInitExpr(QualType ty)4286 explicit ImplicitValueInitExpr(QualType ty)
4287 : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary,
4288 false, false, ty->isInstantiationDependentType(), false) { }
4289
4290 /// \brief Construct an empty implicit value initialization.
ImplicitValueInitExpr(EmptyShell Empty)4291 explicit ImplicitValueInitExpr(EmptyShell Empty)
4292 : Expr(ImplicitValueInitExprClass, Empty) { }
4293
classof(const Stmt * T)4294 static bool classof(const Stmt *T) {
4295 return T->getStmtClass() == ImplicitValueInitExprClass;
4296 }
4297
getLocStart()4298 SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
getLocEnd()4299 SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4300
4301 // Iterators
children()4302 child_range children() { return child_range(); }
4303 };
4304
4305
4306 class ParenListExpr : public Expr {
4307 Stmt **Exprs;
4308 unsigned NumExprs;
4309 SourceLocation LParenLoc, RParenLoc;
4310
4311 public:
4312 ParenListExpr(const ASTContext& C, SourceLocation lparenloc,
4313 ArrayRef<Expr*> exprs, SourceLocation rparenloc);
4314
4315 /// \brief Build an empty paren list.
ParenListExpr(EmptyShell Empty)4316 explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { }
4317
getNumExprs()4318 unsigned getNumExprs() const { return NumExprs; }
4319
getExpr(unsigned Init)4320 const Expr* getExpr(unsigned Init) const {
4321 assert(Init < getNumExprs() && "Initializer access out of range!");
4322 return cast_or_null<Expr>(Exprs[Init]);
4323 }
4324
getExpr(unsigned Init)4325 Expr* getExpr(unsigned Init) {
4326 assert(Init < getNumExprs() && "Initializer access out of range!");
4327 return cast_or_null<Expr>(Exprs[Init]);
4328 }
4329
getExprs()4330 Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); }
4331
getLParenLoc()4332 SourceLocation getLParenLoc() const { return LParenLoc; }
getRParenLoc()4333 SourceLocation getRParenLoc() const { return RParenLoc; }
4334
getLocStart()4335 SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; }
getLocEnd()4336 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4337
classof(const Stmt * T)4338 static bool classof(const Stmt *T) {
4339 return T->getStmtClass() == ParenListExprClass;
4340 }
4341
4342 // Iterators
children()4343 child_range children() {
4344 return child_range(&Exprs[0], &Exprs[0]+NumExprs);
4345 }
4346
4347 friend class ASTStmtReader;
4348 friend class ASTStmtWriter;
4349 };
4350
4351
4352 /// \brief Represents a C11 generic selection.
4353 ///
4354 /// A generic selection (C11 6.5.1.1) contains an unevaluated controlling
4355 /// expression, followed by one or more generic associations. Each generic
4356 /// association specifies a type name and an expression, or "default" and an
4357 /// expression (in which case it is known as a default generic association).
4358 /// The type and value of the generic selection are identical to those of its
4359 /// result expression, which is defined as the expression in the generic
4360 /// association with a type name that is compatible with the type of the
4361 /// controlling expression, or the expression in the default generic association
4362 /// if no types are compatible. For example:
4363 ///
4364 /// @code
4365 /// _Generic(X, double: 1, float: 2, default: 3)
4366 /// @endcode
4367 ///
4368 /// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f
4369 /// or 3 if "hello".
4370 ///
4371 /// As an extension, generic selections are allowed in C++, where the following
4372 /// additional semantics apply:
4373 ///
4374 /// Any generic selection whose controlling expression is type-dependent or
4375 /// which names a dependent type in its association list is result-dependent,
4376 /// which means that the choice of result expression is dependent.
4377 /// Result-dependent generic associations are both type- and value-dependent.
4378 class GenericSelectionExpr : public Expr {
4379 enum { CONTROLLING, END_EXPR };
4380 TypeSourceInfo **AssocTypes;
4381 Stmt **SubExprs;
4382 unsigned NumAssocs, ResultIndex;
4383 SourceLocation GenericLoc, DefaultLoc, RParenLoc;
4384
4385 public:
4386 GenericSelectionExpr(const ASTContext &Context,
4387 SourceLocation GenericLoc, Expr *ControllingExpr,
4388 ArrayRef<TypeSourceInfo*> AssocTypes,
4389 ArrayRef<Expr*> AssocExprs,
4390 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4391 bool ContainsUnexpandedParameterPack,
4392 unsigned ResultIndex);
4393
4394 /// This constructor is used in the result-dependent case.
4395 GenericSelectionExpr(const ASTContext &Context,
4396 SourceLocation GenericLoc, Expr *ControllingExpr,
4397 ArrayRef<TypeSourceInfo*> AssocTypes,
4398 ArrayRef<Expr*> AssocExprs,
4399 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4400 bool ContainsUnexpandedParameterPack);
4401
GenericSelectionExpr(EmptyShell Empty)4402 explicit GenericSelectionExpr(EmptyShell Empty)
4403 : Expr(GenericSelectionExprClass, Empty) { }
4404
getNumAssocs()4405 unsigned getNumAssocs() const { return NumAssocs; }
4406
getGenericLoc()4407 SourceLocation getGenericLoc() const { return GenericLoc; }
getDefaultLoc()4408 SourceLocation getDefaultLoc() const { return DefaultLoc; }
getRParenLoc()4409 SourceLocation getRParenLoc() const { return RParenLoc; }
4410
getAssocExpr(unsigned i)4411 const Expr *getAssocExpr(unsigned i) const {
4412 return cast<Expr>(SubExprs[END_EXPR+i]);
4413 }
getAssocExpr(unsigned i)4414 Expr *getAssocExpr(unsigned i) { return cast<Expr>(SubExprs[END_EXPR+i]); }
4415
getAssocTypeSourceInfo(unsigned i)4416 const TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) const {
4417 return AssocTypes[i];
4418 }
getAssocTypeSourceInfo(unsigned i)4419 TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) { return AssocTypes[i]; }
4420
getAssocType(unsigned i)4421 QualType getAssocType(unsigned i) const {
4422 if (const TypeSourceInfo *TS = getAssocTypeSourceInfo(i))
4423 return TS->getType();
4424 else
4425 return QualType();
4426 }
4427
getControllingExpr()4428 const Expr *getControllingExpr() const {
4429 return cast<Expr>(SubExprs[CONTROLLING]);
4430 }
getControllingExpr()4431 Expr *getControllingExpr() { return cast<Expr>(SubExprs[CONTROLLING]); }
4432
4433 /// Whether this generic selection is result-dependent.
isResultDependent()4434 bool isResultDependent() const { return ResultIndex == -1U; }
4435
4436 /// The zero-based index of the result expression's generic association in
4437 /// the generic selection's association list. Defined only if the
4438 /// generic selection is not result-dependent.
getResultIndex()4439 unsigned getResultIndex() const {
4440 assert(!isResultDependent() && "Generic selection is result-dependent");
4441 return ResultIndex;
4442 }
4443
4444 /// The generic selection's result expression. Defined only if the
4445 /// generic selection is not result-dependent.
getResultExpr()4446 const Expr *getResultExpr() const { return getAssocExpr(getResultIndex()); }
getResultExpr()4447 Expr *getResultExpr() { return getAssocExpr(getResultIndex()); }
4448
getLocStart()4449 SourceLocation getLocStart() const LLVM_READONLY { return GenericLoc; }
getLocEnd()4450 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4451
classof(const Stmt * T)4452 static bool classof(const Stmt *T) {
4453 return T->getStmtClass() == GenericSelectionExprClass;
4454 }
4455
children()4456 child_range children() {
4457 return child_range(SubExprs, SubExprs+END_EXPR+NumAssocs);
4458 }
4459
4460 friend class ASTStmtReader;
4461 };
4462
4463 //===----------------------------------------------------------------------===//
4464 // Clang Extensions
4465 //===----------------------------------------------------------------------===//
4466
4467
4468 /// ExtVectorElementExpr - This represents access to specific elements of a
4469 /// vector, and may occur on the left hand side or right hand side. For example
4470 /// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector.
4471 ///
4472 /// Note that the base may have either vector or pointer to vector type, just
4473 /// like a struct field reference.
4474 ///
4475 class ExtVectorElementExpr : public Expr {
4476 Stmt *Base;
4477 IdentifierInfo *Accessor;
4478 SourceLocation AccessorLoc;
4479 public:
ExtVectorElementExpr(QualType ty,ExprValueKind VK,Expr * base,IdentifierInfo & accessor,SourceLocation loc)4480 ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base,
4481 IdentifierInfo &accessor, SourceLocation loc)
4482 : Expr(ExtVectorElementExprClass, ty, VK,
4483 (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent),
4484 base->isTypeDependent(), base->isValueDependent(),
4485 base->isInstantiationDependent(),
4486 base->containsUnexpandedParameterPack()),
4487 Base(base), Accessor(&accessor), AccessorLoc(loc) {}
4488
4489 /// \brief Build an empty vector element expression.
ExtVectorElementExpr(EmptyShell Empty)4490 explicit ExtVectorElementExpr(EmptyShell Empty)
4491 : Expr(ExtVectorElementExprClass, Empty) { }
4492
getBase()4493 const Expr *getBase() const { return cast<Expr>(Base); }
getBase()4494 Expr *getBase() { return cast<Expr>(Base); }
setBase(Expr * E)4495 void setBase(Expr *E) { Base = E; }
4496
getAccessor()4497 IdentifierInfo &getAccessor() const { return *Accessor; }
setAccessor(IdentifierInfo * II)4498 void setAccessor(IdentifierInfo *II) { Accessor = II; }
4499
getAccessorLoc()4500 SourceLocation getAccessorLoc() const { return AccessorLoc; }
setAccessorLoc(SourceLocation L)4501 void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
4502
4503 /// getNumElements - Get the number of components being selected.
4504 unsigned getNumElements() const;
4505
4506 /// containsDuplicateElements - Return true if any element access is
4507 /// repeated.
4508 bool containsDuplicateElements() const;
4509
4510 /// getEncodedElementAccess - Encode the elements accessed into an llvm
4511 /// aggregate Constant of ConstantInt(s).
4512 void getEncodedElementAccess(SmallVectorImpl<unsigned> &Elts) const;
4513
getLocStart()4514 SourceLocation getLocStart() const LLVM_READONLY {
4515 return getBase()->getLocStart();
4516 }
getLocEnd()4517 SourceLocation getLocEnd() const LLVM_READONLY { return AccessorLoc; }
4518
4519 /// isArrow - Return true if the base expression is a pointer to vector,
4520 /// return false if the base expression is a vector.
4521 bool isArrow() const;
4522
classof(const Stmt * T)4523 static bool classof(const Stmt *T) {
4524 return T->getStmtClass() == ExtVectorElementExprClass;
4525 }
4526
4527 // Iterators
children()4528 child_range children() { return child_range(&Base, &Base+1); }
4529 };
4530
4531
4532 /// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
4533 /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
4534 class BlockExpr : public Expr {
4535 protected:
4536 BlockDecl *TheBlock;
4537 public:
BlockExpr(BlockDecl * BD,QualType ty)4538 BlockExpr(BlockDecl *BD, QualType ty)
4539 : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary,
4540 ty->isDependentType(), ty->isDependentType(),
4541 ty->isInstantiationDependentType() || BD->isDependentContext(),
4542 false),
4543 TheBlock(BD) {}
4544
4545 /// \brief Build an empty block expression.
BlockExpr(EmptyShell Empty)4546 explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
4547
getBlockDecl()4548 const BlockDecl *getBlockDecl() const { return TheBlock; }
getBlockDecl()4549 BlockDecl *getBlockDecl() { return TheBlock; }
setBlockDecl(BlockDecl * BD)4550 void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
4551
4552 // Convenience functions for probing the underlying BlockDecl.
4553 SourceLocation getCaretLocation() const;
4554 const Stmt *getBody() const;
4555 Stmt *getBody();
4556
getLocStart()4557 SourceLocation getLocStart() const LLVM_READONLY { return getCaretLocation(); }
getLocEnd()4558 SourceLocation getLocEnd() const LLVM_READONLY { return getBody()->getLocEnd(); }
4559
4560 /// getFunctionType - Return the underlying function type for this block.
4561 const FunctionProtoType *getFunctionType() const;
4562
classof(const Stmt * T)4563 static bool classof(const Stmt *T) {
4564 return T->getStmtClass() == BlockExprClass;
4565 }
4566
4567 // Iterators
children()4568 child_range children() { return child_range(); }
4569 };
4570
4571 /// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2]
4572 /// This AST node provides support for reinterpreting a type to another
4573 /// type of the same size.
4574 class AsTypeExpr : public Expr {
4575 private:
4576 Stmt *SrcExpr;
4577 SourceLocation BuiltinLoc, RParenLoc;
4578
4579 friend class ASTReader;
4580 friend class ASTStmtReader;
AsTypeExpr(EmptyShell Empty)4581 explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {}
4582
4583 public:
AsTypeExpr(Expr * SrcExpr,QualType DstType,ExprValueKind VK,ExprObjectKind OK,SourceLocation BuiltinLoc,SourceLocation RParenLoc)4584 AsTypeExpr(Expr* SrcExpr, QualType DstType,
4585 ExprValueKind VK, ExprObjectKind OK,
4586 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
4587 : Expr(AsTypeExprClass, DstType, VK, OK,
4588 DstType->isDependentType(),
4589 DstType->isDependentType() || SrcExpr->isValueDependent(),
4590 (DstType->isInstantiationDependentType() ||
4591 SrcExpr->isInstantiationDependent()),
4592 (DstType->containsUnexpandedParameterPack() ||
4593 SrcExpr->containsUnexpandedParameterPack())),
4594 SrcExpr(SrcExpr), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
4595
4596 /// getSrcExpr - Return the Expr to be converted.
getSrcExpr()4597 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
4598
4599 /// getBuiltinLoc - Return the location of the __builtin_astype token.
getBuiltinLoc()4600 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4601
4602 /// getRParenLoc - Return the location of final right parenthesis.
getRParenLoc()4603 SourceLocation getRParenLoc() const { return RParenLoc; }
4604
getLocStart()4605 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
getLocEnd()4606 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4607
classof(const Stmt * T)4608 static bool classof(const Stmt *T) {
4609 return T->getStmtClass() == AsTypeExprClass;
4610 }
4611
4612 // Iterators
children()4613 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
4614 };
4615
4616 /// PseudoObjectExpr - An expression which accesses a pseudo-object
4617 /// l-value. A pseudo-object is an abstract object, accesses to which
4618 /// are translated to calls. The pseudo-object expression has a
4619 /// syntactic form, which shows how the expression was actually
4620 /// written in the source code, and a semantic form, which is a series
4621 /// of expressions to be executed in order which detail how the
4622 /// operation is actually evaluated. Optionally, one of the semantic
4623 /// forms may also provide a result value for the expression.
4624 ///
4625 /// If any of the semantic-form expressions is an OpaqueValueExpr,
4626 /// that OVE is required to have a source expression, and it is bound
4627 /// to the result of that source expression. Such OVEs may appear
4628 /// only in subsequent semantic-form expressions and as
4629 /// sub-expressions of the syntactic form.
4630 ///
4631 /// PseudoObjectExpr should be used only when an operation can be
4632 /// usefully described in terms of fairly simple rewrite rules on
4633 /// objects and functions that are meant to be used by end-developers.
4634 /// For example, under the Itanium ABI, dynamic casts are implemented
4635 /// as a call to a runtime function called __dynamic_cast; using this
4636 /// class to describe that would be inappropriate because that call is
4637 /// not really part of the user-visible semantics, and instead the
4638 /// cast is properly reflected in the AST and IR-generation has been
4639 /// taught to generate the call as necessary. In contrast, an
4640 /// Objective-C property access is semantically defined to be
4641 /// equivalent to a particular message send, and this is very much
4642 /// part of the user model. The name of this class encourages this
4643 /// modelling design.
4644 class PseudoObjectExpr : public Expr {
4645 // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions.
4646 // Always at least two, because the first sub-expression is the
4647 // syntactic form.
4648
4649 // PseudoObjectExprBits.ResultIndex - The index of the
4650 // sub-expression holding the result. 0 means the result is void,
4651 // which is unambiguous because it's the index of the syntactic
4652 // form. Note that this is therefore 1 higher than the value passed
4653 // in to Create, which is an index within the semantic forms.
4654 // Note also that ASTStmtWriter assumes this encoding.
4655
getSubExprsBuffer()4656 Expr **getSubExprsBuffer() { return reinterpret_cast<Expr**>(this + 1); }
getSubExprsBuffer()4657 const Expr * const *getSubExprsBuffer() const {
4658 return reinterpret_cast<const Expr * const *>(this + 1);
4659 }
4660
4661 friend class ASTStmtReader;
4662
4663 PseudoObjectExpr(QualType type, ExprValueKind VK,
4664 Expr *syntactic, ArrayRef<Expr*> semantic,
4665 unsigned resultIndex);
4666
4667 PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs);
4668
getNumSubExprs()4669 unsigned getNumSubExprs() const {
4670 return PseudoObjectExprBits.NumSubExprs;
4671 }
4672
4673 public:
4674 /// NoResult - A value for the result index indicating that there is
4675 /// no semantic result.
4676 enum : unsigned { NoResult = ~0U };
4677
4678 static PseudoObjectExpr *Create(const ASTContext &Context, Expr *syntactic,
4679 ArrayRef<Expr*> semantic,
4680 unsigned resultIndex);
4681
4682 static PseudoObjectExpr *Create(const ASTContext &Context, EmptyShell shell,
4683 unsigned numSemanticExprs);
4684
4685 /// Return the syntactic form of this expression, i.e. the
4686 /// expression it actually looks like. Likely to be expressed in
4687 /// terms of OpaqueValueExprs bound in the semantic form.
getSyntacticForm()4688 Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; }
getSyntacticForm()4689 const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; }
4690
4691 /// Return the index of the result-bearing expression into the semantics
4692 /// expressions, or PseudoObjectExpr::NoResult if there is none.
getResultExprIndex()4693 unsigned getResultExprIndex() const {
4694 if (PseudoObjectExprBits.ResultIndex == 0) return NoResult;
4695 return PseudoObjectExprBits.ResultIndex - 1;
4696 }
4697
4698 /// Return the result-bearing expression, or null if there is none.
getResultExpr()4699 Expr *getResultExpr() {
4700 if (PseudoObjectExprBits.ResultIndex == 0)
4701 return nullptr;
4702 return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex];
4703 }
getResultExpr()4704 const Expr *getResultExpr() const {
4705 return const_cast<PseudoObjectExpr*>(this)->getResultExpr();
4706 }
4707
getNumSemanticExprs()4708 unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; }
4709
4710 typedef Expr * const *semantics_iterator;
4711 typedef const Expr * const *const_semantics_iterator;
semantics_begin()4712 semantics_iterator semantics_begin() {
4713 return getSubExprsBuffer() + 1;
4714 }
semantics_begin()4715 const_semantics_iterator semantics_begin() const {
4716 return getSubExprsBuffer() + 1;
4717 }
semantics_end()4718 semantics_iterator semantics_end() {
4719 return getSubExprsBuffer() + getNumSubExprs();
4720 }
semantics_end()4721 const_semantics_iterator semantics_end() const {
4722 return getSubExprsBuffer() + getNumSubExprs();
4723 }
getSemanticExpr(unsigned index)4724 Expr *getSemanticExpr(unsigned index) {
4725 assert(index + 1 < getNumSubExprs());
4726 return getSubExprsBuffer()[index + 1];
4727 }
getSemanticExpr(unsigned index)4728 const Expr *getSemanticExpr(unsigned index) const {
4729 return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index);
4730 }
4731
getExprLoc()4732 SourceLocation getExprLoc() const LLVM_READONLY {
4733 return getSyntacticForm()->getExprLoc();
4734 }
4735
getLocStart()4736 SourceLocation getLocStart() const LLVM_READONLY {
4737 return getSyntacticForm()->getLocStart();
4738 }
getLocEnd()4739 SourceLocation getLocEnd() const LLVM_READONLY {
4740 return getSyntacticForm()->getLocEnd();
4741 }
4742
children()4743 child_range children() {
4744 Stmt **cs = reinterpret_cast<Stmt**>(getSubExprsBuffer());
4745 return child_range(cs, cs + getNumSubExprs());
4746 }
4747
classof(const Stmt * T)4748 static bool classof(const Stmt *T) {
4749 return T->getStmtClass() == PseudoObjectExprClass;
4750 }
4751 };
4752
4753 /// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*,
4754 /// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the
4755 /// similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>.
4756 /// All of these instructions take one primary pointer and at least one memory
4757 /// order.
4758 class AtomicExpr : public Expr {
4759 public:
4760 enum AtomicOp {
4761 #define BUILTIN(ID, TYPE, ATTRS)
4762 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID,
4763 #include "clang/Basic/Builtins.def"
4764 // Avoid trailing comma
4765 BI_First = 0
4766 };
4767
4768 // The ABI values for various atomic memory orderings.
4769 enum AtomicOrderingKind {
4770 AO_ABI_memory_order_relaxed = 0,
4771 AO_ABI_memory_order_consume = 1,
4772 AO_ABI_memory_order_acquire = 2,
4773 AO_ABI_memory_order_release = 3,
4774 AO_ABI_memory_order_acq_rel = 4,
4775 AO_ABI_memory_order_seq_cst = 5
4776 };
4777
4778 private:
4779 enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR };
4780 Stmt* SubExprs[END_EXPR];
4781 unsigned NumSubExprs;
4782 SourceLocation BuiltinLoc, RParenLoc;
4783 AtomicOp Op;
4784
4785 friend class ASTStmtReader;
4786
4787 public:
4788 AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, QualType t,
4789 AtomicOp op, SourceLocation RP);
4790
4791 /// \brief Determine the number of arguments the specified atomic builtin
4792 /// should have.
4793 static unsigned getNumSubExprs(AtomicOp Op);
4794
4795 /// \brief Build an empty AtomicExpr.
AtomicExpr(EmptyShell Empty)4796 explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { }
4797
getPtr()4798 Expr *getPtr() const {
4799 return cast<Expr>(SubExprs[PTR]);
4800 }
getOrder()4801 Expr *getOrder() const {
4802 return cast<Expr>(SubExprs[ORDER]);
4803 }
getVal1()4804 Expr *getVal1() const {
4805 if (Op == AO__c11_atomic_init)
4806 return cast<Expr>(SubExprs[ORDER]);
4807 assert(NumSubExprs > VAL1);
4808 return cast<Expr>(SubExprs[VAL1]);
4809 }
getOrderFail()4810 Expr *getOrderFail() const {
4811 assert(NumSubExprs > ORDER_FAIL);
4812 return cast<Expr>(SubExprs[ORDER_FAIL]);
4813 }
getVal2()4814 Expr *getVal2() const {
4815 if (Op == AO__atomic_exchange)
4816 return cast<Expr>(SubExprs[ORDER_FAIL]);
4817 assert(NumSubExprs > VAL2);
4818 return cast<Expr>(SubExprs[VAL2]);
4819 }
getWeak()4820 Expr *getWeak() const {
4821 assert(NumSubExprs > WEAK);
4822 return cast<Expr>(SubExprs[WEAK]);
4823 }
4824
getOp()4825 AtomicOp getOp() const { return Op; }
getNumSubExprs()4826 unsigned getNumSubExprs() { return NumSubExprs; }
4827
getSubExprs()4828 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
4829
isVolatile()4830 bool isVolatile() const {
4831 return getPtr()->getType()->getPointeeType().isVolatileQualified();
4832 }
4833
isCmpXChg()4834 bool isCmpXChg() const {
4835 return getOp() == AO__c11_atomic_compare_exchange_strong ||
4836 getOp() == AO__c11_atomic_compare_exchange_weak ||
4837 getOp() == AO__atomic_compare_exchange ||
4838 getOp() == AO__atomic_compare_exchange_n;
4839 }
4840
getBuiltinLoc()4841 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
getRParenLoc()4842 SourceLocation getRParenLoc() const { return RParenLoc; }
4843
getLocStart()4844 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
getLocEnd()4845 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4846
classof(const Stmt * T)4847 static bool classof(const Stmt *T) {
4848 return T->getStmtClass() == AtomicExprClass;
4849 }
4850
4851 // Iterators
children()4852 child_range children() {
4853 return child_range(SubExprs, SubExprs+NumSubExprs);
4854 }
4855 };
4856
4857 /// TypoExpr - Internal placeholder for expressions where typo correction
4858 /// still needs to be performed and/or an error diagnostic emitted.
4859 class TypoExpr : public Expr {
4860 public:
TypoExpr(QualType T)4861 TypoExpr(QualType T)
4862 : Expr(TypoExprClass, T, VK_LValue, OK_Ordinary,
4863 /*isTypeDependent*/ true,
4864 /*isValueDependent*/ true,
4865 /*isInstantiationDependent*/ true,
4866 /*containsUnexpandedParameterPack*/ false) {
4867 assert(T->isDependentType() && "TypoExpr given a non-dependent type");
4868 }
4869
children()4870 child_range children() { return child_range(); }
getLocStart()4871 SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
getLocEnd()4872 SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4873 };
4874 } // end namespace clang
4875
4876 #endif
4877