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 &) = delete;
1243 void operator=(const APNumericStorage &) = delete;
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
1998 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
1999 QualType resultType, SourceLocation op,
2000 SourceLocation rp);
2001
2002 /// \brief Construct an empty sizeof/alignof expression.
UnaryExprOrTypeTraitExpr(EmptyShell Empty)2003 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
2004 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
2005
getKind()2006 UnaryExprOrTypeTrait getKind() const {
2007 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
2008 }
setKind(UnaryExprOrTypeTrait K)2009 void setKind(UnaryExprOrTypeTrait K) { UnaryExprOrTypeTraitExprBits.Kind = K;}
2010
isArgumentType()2011 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
getArgumentType()2012 QualType getArgumentType() const {
2013 return getArgumentTypeInfo()->getType();
2014 }
getArgumentTypeInfo()2015 TypeSourceInfo *getArgumentTypeInfo() const {
2016 assert(isArgumentType() && "calling getArgumentType() when arg is expr");
2017 return Argument.Ty;
2018 }
getArgumentExpr()2019 Expr *getArgumentExpr() {
2020 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
2021 return static_cast<Expr*>(Argument.Ex);
2022 }
getArgumentExpr()2023 const Expr *getArgumentExpr() const {
2024 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
2025 }
2026
setArgument(Expr * E)2027 void setArgument(Expr *E) {
2028 Argument.Ex = E;
2029 UnaryExprOrTypeTraitExprBits.IsType = false;
2030 }
setArgument(TypeSourceInfo * TInfo)2031 void setArgument(TypeSourceInfo *TInfo) {
2032 Argument.Ty = TInfo;
2033 UnaryExprOrTypeTraitExprBits.IsType = true;
2034 }
2035
2036 /// Gets the argument type, or the type of the argument expression, whichever
2037 /// is appropriate.
getTypeOfArgument()2038 QualType getTypeOfArgument() const {
2039 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
2040 }
2041
getOperatorLoc()2042 SourceLocation getOperatorLoc() const { return OpLoc; }
setOperatorLoc(SourceLocation L)2043 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2044
getRParenLoc()2045 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)2046 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2047
getLocStart()2048 SourceLocation getLocStart() const LLVM_READONLY { return OpLoc; }
getLocEnd()2049 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
2050
classof(const Stmt * T)2051 static bool classof(const Stmt *T) {
2052 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2053 }
2054
2055 // Iterators
2056 child_range children();
2057 };
2058
2059 //===----------------------------------------------------------------------===//
2060 // Postfix Operators.
2061 //===----------------------------------------------------------------------===//
2062
2063 /// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2064 class ArraySubscriptExpr : public Expr {
2065 enum { LHS, RHS, END_EXPR=2 };
2066 Stmt* SubExprs[END_EXPR];
2067 SourceLocation RBracketLoc;
2068 public:
ArraySubscriptExpr(Expr * lhs,Expr * rhs,QualType t,ExprValueKind VK,ExprObjectKind OK,SourceLocation rbracketloc)2069 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
2070 ExprValueKind VK, ExprObjectKind OK,
2071 SourceLocation rbracketloc)
2072 : Expr(ArraySubscriptExprClass, t, VK, OK,
2073 lhs->isTypeDependent() || rhs->isTypeDependent(),
2074 lhs->isValueDependent() || rhs->isValueDependent(),
2075 (lhs->isInstantiationDependent() ||
2076 rhs->isInstantiationDependent()),
2077 (lhs->containsUnexpandedParameterPack() ||
2078 rhs->containsUnexpandedParameterPack())),
2079 RBracketLoc(rbracketloc) {
2080 SubExprs[LHS] = lhs;
2081 SubExprs[RHS] = rhs;
2082 }
2083
2084 /// \brief Create an empty array subscript expression.
ArraySubscriptExpr(EmptyShell Shell)2085 explicit ArraySubscriptExpr(EmptyShell Shell)
2086 : Expr(ArraySubscriptExprClass, Shell) { }
2087
2088 /// An array access can be written A[4] or 4[A] (both are equivalent).
2089 /// - getBase() and getIdx() always present the normalized view: A[4].
2090 /// In this case getBase() returns "A" and getIdx() returns "4".
2091 /// - getLHS() and getRHS() present the syntactic view. e.g. for
2092 /// 4[A] getLHS() returns "4".
2093 /// Note: Because vector element access is also written A[4] we must
2094 /// predicate the format conversion in getBase and getIdx only on the
2095 /// the type of the RHS, as it is possible for the LHS to be a vector of
2096 /// integer type
getLHS()2097 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
getLHS()2098 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
setLHS(Expr * E)2099 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2100
getRHS()2101 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
getRHS()2102 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
setRHS(Expr * E)2103 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2104
getBase()2105 Expr *getBase() {
2106 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
2107 }
2108
getBase()2109 const Expr *getBase() const {
2110 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
2111 }
2112
getIdx()2113 Expr *getIdx() {
2114 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
2115 }
2116
getIdx()2117 const Expr *getIdx() const {
2118 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
2119 }
2120
getLocStart()2121 SourceLocation getLocStart() const LLVM_READONLY {
2122 return getLHS()->getLocStart();
2123 }
getLocEnd()2124 SourceLocation getLocEnd() const LLVM_READONLY { return RBracketLoc; }
2125
getRBracketLoc()2126 SourceLocation getRBracketLoc() const { return RBracketLoc; }
setRBracketLoc(SourceLocation L)2127 void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
2128
getExprLoc()2129 SourceLocation getExprLoc() const LLVM_READONLY {
2130 return getBase()->getExprLoc();
2131 }
2132
classof(const Stmt * T)2133 static bool classof(const Stmt *T) {
2134 return T->getStmtClass() == ArraySubscriptExprClass;
2135 }
2136
2137 // Iterators
children()2138 child_range children() {
2139 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2140 }
2141 };
2142
2143
2144 /// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2145 /// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2146 /// while its subclasses may represent alternative syntax that (semantically)
2147 /// results in a function call. For example, CXXOperatorCallExpr is
2148 /// a subclass for overloaded operator calls that use operator syntax, e.g.,
2149 /// "str1 + str2" to resolve to a function call.
2150 class CallExpr : public Expr {
2151 enum { FN=0, PREARGS_START=1 };
2152 Stmt **SubExprs;
2153 unsigned NumArgs;
2154 SourceLocation RParenLoc;
2155
2156 protected:
2157 // These versions of the constructor are for derived classes.
2158 CallExpr(const ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs,
2159 ArrayRef<Expr*> args, QualType t, ExprValueKind VK,
2160 SourceLocation rparenloc);
2161 CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs,
2162 EmptyShell Empty);
2163
getPreArg(unsigned i)2164 Stmt *getPreArg(unsigned i) {
2165 assert(i < getNumPreArgs() && "Prearg access out of range!");
2166 return SubExprs[PREARGS_START+i];
2167 }
getPreArg(unsigned i)2168 const Stmt *getPreArg(unsigned i) const {
2169 assert(i < getNumPreArgs() && "Prearg access out of range!");
2170 return SubExprs[PREARGS_START+i];
2171 }
setPreArg(unsigned i,Stmt * PreArg)2172 void setPreArg(unsigned i, Stmt *PreArg) {
2173 assert(i < getNumPreArgs() && "Prearg access out of range!");
2174 SubExprs[PREARGS_START+i] = PreArg;
2175 }
2176
getNumPreArgs()2177 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2178
2179 public:
2180 CallExpr(const ASTContext& C, Expr *fn, ArrayRef<Expr*> args, QualType t,
2181 ExprValueKind VK, SourceLocation rparenloc);
2182
2183 /// \brief Build an empty call expression.
2184 CallExpr(const ASTContext &C, StmtClass SC, EmptyShell Empty);
2185
getCallee()2186 const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
getCallee()2187 Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
setCallee(Expr * F)2188 void setCallee(Expr *F) { SubExprs[FN] = F; }
2189
2190 Decl *getCalleeDecl();
getCalleeDecl()2191 const Decl *getCalleeDecl() const {
2192 return const_cast<CallExpr*>(this)->getCalleeDecl();
2193 }
2194
2195 /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0.
2196 FunctionDecl *getDirectCallee();
getDirectCallee()2197 const FunctionDecl *getDirectCallee() const {
2198 return const_cast<CallExpr*>(this)->getDirectCallee();
2199 }
2200
2201 /// getNumArgs - Return the number of actual arguments to this call.
2202 ///
getNumArgs()2203 unsigned getNumArgs() const { return NumArgs; }
2204
2205 /// \brief Retrieve the call arguments.
getArgs()2206 Expr **getArgs() {
2207 return reinterpret_cast<Expr **>(SubExprs+getNumPreArgs()+PREARGS_START);
2208 }
getArgs()2209 const Expr *const *getArgs() const {
2210 return const_cast<CallExpr*>(this)->getArgs();
2211 }
2212
2213 /// getArg - Return the specified argument.
getArg(unsigned Arg)2214 Expr *getArg(unsigned Arg) {
2215 assert(Arg < NumArgs && "Arg access out of range!");
2216 return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2217 }
getArg(unsigned Arg)2218 const Expr *getArg(unsigned Arg) const {
2219 assert(Arg < NumArgs && "Arg access out of range!");
2220 return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2221 }
2222
2223 /// setArg - Set the specified argument.
setArg(unsigned Arg,Expr * ArgExpr)2224 void setArg(unsigned Arg, Expr *ArgExpr) {
2225 assert(Arg < NumArgs && "Arg access out of range!");
2226 SubExprs[Arg+getNumPreArgs()+PREARGS_START] = ArgExpr;
2227 }
2228
2229 /// setNumArgs - This changes the number of arguments present in this call.
2230 /// Any orphaned expressions are deleted by this, and any new operands are set
2231 /// to null.
2232 void setNumArgs(const ASTContext& C, unsigned NumArgs);
2233
2234 typedef ExprIterator arg_iterator;
2235 typedef ConstExprIterator const_arg_iterator;
2236 typedef llvm::iterator_range<arg_iterator> arg_range;
2237 typedef llvm::iterator_range<const_arg_iterator> arg_const_range;
2238
arguments()2239 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
arguments()2240 arg_const_range arguments() const {
2241 return arg_const_range(arg_begin(), arg_end());
2242 }
2243
arg_begin()2244 arg_iterator arg_begin() { return SubExprs+PREARGS_START+getNumPreArgs(); }
arg_end()2245 arg_iterator arg_end() {
2246 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2247 }
arg_begin()2248 const_arg_iterator arg_begin() const {
2249 return SubExprs+PREARGS_START+getNumPreArgs();
2250 }
arg_end()2251 const_arg_iterator arg_end() const {
2252 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2253 }
2254
2255 /// This method provides fast access to all the subexpressions of
2256 /// a CallExpr without going through the slower virtual child_iterator
2257 /// interface. This provides efficient reverse iteration of the
2258 /// subexpressions. This is currently used for CFG construction.
getRawSubExprs()2259 ArrayRef<Stmt*> getRawSubExprs() {
2260 return llvm::makeArrayRef(SubExprs,
2261 getNumPreArgs() + PREARGS_START + getNumArgs());
2262 }
2263
2264 /// getNumCommas - Return the number of commas that must have been present in
2265 /// this function call.
getNumCommas()2266 unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
2267
2268 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
2269 /// of the callee. If not, return 0.
2270 unsigned getBuiltinCallee() const;
2271
2272 /// \brief Returns \c true if this is a call to a builtin which does not
2273 /// evaluate side-effects within its arguments.
2274 bool isUnevaluatedBuiltinCall(ASTContext &Ctx) const;
2275
2276 /// getCallReturnType - Get the return type of the call expr. This is not
2277 /// always the type of the expr itself, if the return type is a reference
2278 /// type.
2279 QualType getCallReturnType(const ASTContext &Ctx) const;
2280
getRParenLoc()2281 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)2282 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2283
2284 SourceLocation getLocStart() const LLVM_READONLY;
2285 SourceLocation getLocEnd() const LLVM_READONLY;
2286
classof(const Stmt * T)2287 static bool classof(const Stmt *T) {
2288 return T->getStmtClass() >= firstCallExprConstant &&
2289 T->getStmtClass() <= lastCallExprConstant;
2290 }
2291
2292 // Iterators
children()2293 child_range children() {
2294 return child_range(&SubExprs[0],
2295 &SubExprs[0]+NumArgs+getNumPreArgs()+PREARGS_START);
2296 }
2297 };
2298
2299 /// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
2300 ///
2301 class MemberExpr : public Expr {
2302 /// Extra data stored in some member expressions.
2303 struct MemberNameQualifier {
2304 /// \brief The nested-name-specifier that qualifies the name, including
2305 /// source-location information.
2306 NestedNameSpecifierLoc QualifierLoc;
2307
2308 /// \brief The DeclAccessPair through which the MemberDecl was found due to
2309 /// name qualifiers.
2310 DeclAccessPair FoundDecl;
2311 };
2312
2313 /// Base - the expression for the base pointer or structure references. In
2314 /// X.F, this is "X".
2315 Stmt *Base;
2316
2317 /// MemberDecl - This is the decl being referenced by the field/member name.
2318 /// In X.F, this is the decl referenced by F.
2319 ValueDecl *MemberDecl;
2320
2321 /// MemberDNLoc - Provides source/type location info for the
2322 /// declaration name embedded in MemberDecl.
2323 DeclarationNameLoc MemberDNLoc;
2324
2325 /// MemberLoc - This is the location of the member name.
2326 SourceLocation MemberLoc;
2327
2328 /// This is the location of the -> or . in the expression.
2329 SourceLocation OperatorLoc;
2330
2331 /// IsArrow - True if this is "X->F", false if this is "X.F".
2332 bool IsArrow : 1;
2333
2334 /// \brief True if this member expression used a nested-name-specifier to
2335 /// refer to the member, e.g., "x->Base::f", or found its member via a using
2336 /// declaration. When true, a MemberNameQualifier
2337 /// structure is allocated immediately after the MemberExpr.
2338 bool HasQualifierOrFoundDecl : 1;
2339
2340 /// \brief True if this member expression specified a template keyword
2341 /// and/or a template argument list explicitly, e.g., x->f<int>,
2342 /// x->template f, x->template f<int>.
2343 /// When true, an ASTTemplateKWAndArgsInfo structure and its
2344 /// TemplateArguments (if any) are allocated immediately after
2345 /// the MemberExpr or, if the member expression also has a qualifier,
2346 /// after the MemberNameQualifier structure.
2347 bool HasTemplateKWAndArgsInfo : 1;
2348
2349 /// \brief True if this member expression refers to a method that
2350 /// was resolved from an overloaded set having size greater than 1.
2351 bool HadMultipleCandidates : 1;
2352
2353 /// \brief Retrieve the qualifier that preceded the member name, if any.
getMemberQualifier()2354 MemberNameQualifier *getMemberQualifier() {
2355 assert(HasQualifierOrFoundDecl);
2356 return reinterpret_cast<MemberNameQualifier *> (this + 1);
2357 }
2358
2359 /// \brief Retrieve the qualifier that preceded the member name, if any.
getMemberQualifier()2360 const MemberNameQualifier *getMemberQualifier() const {
2361 return const_cast<MemberExpr *>(this)->getMemberQualifier();
2362 }
2363
2364 public:
MemberExpr(Expr * base,bool isarrow,SourceLocation operatorloc,ValueDecl * memberdecl,const DeclarationNameInfo & NameInfo,QualType ty,ExprValueKind VK,ExprObjectKind OK)2365 MemberExpr(Expr *base, bool isarrow, SourceLocation operatorloc,
2366 ValueDecl *memberdecl, const DeclarationNameInfo &NameInfo,
2367 QualType ty, ExprValueKind VK, ExprObjectKind OK)
2368 : Expr(MemberExprClass, ty, VK, OK, base->isTypeDependent(),
2369 base->isValueDependent(), base->isInstantiationDependent(),
2370 base->containsUnexpandedParameterPack()),
2371 Base(base), MemberDecl(memberdecl), MemberDNLoc(NameInfo.getInfo()),
2372 MemberLoc(NameInfo.getLoc()), OperatorLoc(operatorloc),
2373 IsArrow(isarrow), HasQualifierOrFoundDecl(false),
2374 HasTemplateKWAndArgsInfo(false), HadMultipleCandidates(false) {
2375 assert(memberdecl->getDeclName() == NameInfo.getName());
2376 }
2377
2378 // NOTE: this constructor should be used only when it is known that
2379 // the member name can not provide additional syntactic info
2380 // (i.e., source locations for C++ operator names or type source info
2381 // for constructors, destructors and conversion operators).
MemberExpr(Expr * base,bool isarrow,SourceLocation operatorloc,ValueDecl * memberdecl,SourceLocation l,QualType ty,ExprValueKind VK,ExprObjectKind OK)2382 MemberExpr(Expr *base, bool isarrow, SourceLocation operatorloc,
2383 ValueDecl *memberdecl, SourceLocation l, QualType ty,
2384 ExprValueKind VK, ExprObjectKind OK)
2385 : Expr(MemberExprClass, ty, VK, OK, base->isTypeDependent(),
2386 base->isValueDependent(), base->isInstantiationDependent(),
2387 base->containsUnexpandedParameterPack()),
2388 Base(base), MemberDecl(memberdecl), MemberDNLoc(), MemberLoc(l),
2389 OperatorLoc(operatorloc), IsArrow(isarrow),
2390 HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false),
2391 HadMultipleCandidates(false) {}
2392
2393 static MemberExpr *Create(const ASTContext &C, Expr *base, bool isarrow,
2394 SourceLocation OperatorLoc,
2395 NestedNameSpecifierLoc QualifierLoc,
2396 SourceLocation TemplateKWLoc, ValueDecl *memberdecl,
2397 DeclAccessPair founddecl,
2398 DeclarationNameInfo MemberNameInfo,
2399 const TemplateArgumentListInfo *targs, QualType ty,
2400 ExprValueKind VK, ExprObjectKind OK);
2401
setBase(Expr * E)2402 void setBase(Expr *E) { Base = E; }
getBase()2403 Expr *getBase() const { return cast<Expr>(Base); }
2404
2405 /// \brief Retrieve the member declaration to which this expression refers.
2406 ///
2407 /// The returned declaration will either be a FieldDecl or (in C++)
2408 /// a CXXMethodDecl.
getMemberDecl()2409 ValueDecl *getMemberDecl() const { return MemberDecl; }
setMemberDecl(ValueDecl * D)2410 void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
2411
2412 /// \brief Retrieves the declaration found by lookup.
getFoundDecl()2413 DeclAccessPair getFoundDecl() const {
2414 if (!HasQualifierOrFoundDecl)
2415 return DeclAccessPair::make(getMemberDecl(),
2416 getMemberDecl()->getAccess());
2417 return getMemberQualifier()->FoundDecl;
2418 }
2419
2420 /// \brief Determines whether this member expression actually had
2421 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2422 /// x->Base::foo.
hasQualifier()2423 bool hasQualifier() const { return getQualifier() != nullptr; }
2424
2425 /// \brief If the member name was qualified, retrieves the
2426 /// nested-name-specifier that precedes the member name. Otherwise, returns
2427 /// NULL.
getQualifier()2428 NestedNameSpecifier *getQualifier() const {
2429 if (!HasQualifierOrFoundDecl)
2430 return nullptr;
2431
2432 return getMemberQualifier()->QualifierLoc.getNestedNameSpecifier();
2433 }
2434
2435 /// \brief If the member name was qualified, retrieves the
2436 /// nested-name-specifier that precedes the member name, with source-location
2437 /// information.
getQualifierLoc()2438 NestedNameSpecifierLoc getQualifierLoc() const {
2439 if (!hasQualifier())
2440 return NestedNameSpecifierLoc();
2441
2442 return getMemberQualifier()->QualifierLoc;
2443 }
2444
2445 /// \brief Return the optional template keyword and arguments info.
getTemplateKWAndArgsInfo()2446 ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() {
2447 if (!HasTemplateKWAndArgsInfo)
2448 return nullptr;
2449
2450 if (!HasQualifierOrFoundDecl)
2451 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(this + 1);
2452
2453 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(
2454 getMemberQualifier() + 1);
2455 }
2456
2457 /// \brief Return the optional template keyword and arguments info.
getTemplateKWAndArgsInfo()2458 const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const {
2459 return const_cast<MemberExpr*>(this)->getTemplateKWAndArgsInfo();
2460 }
2461
2462 /// \brief Retrieve the location of the template keyword preceding
2463 /// the member name, if any.
getTemplateKeywordLoc()2464 SourceLocation getTemplateKeywordLoc() const {
2465 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2466 return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc();
2467 }
2468
2469 /// \brief Retrieve the location of the left angle bracket starting the
2470 /// explicit template argument list following the member name, if any.
getLAngleLoc()2471 SourceLocation getLAngleLoc() const {
2472 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2473 return getTemplateKWAndArgsInfo()->LAngleLoc;
2474 }
2475
2476 /// \brief Retrieve the location of the right angle bracket ending the
2477 /// explicit template argument list following the member name, if any.
getRAngleLoc()2478 SourceLocation getRAngleLoc() const {
2479 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2480 return getTemplateKWAndArgsInfo()->RAngleLoc;
2481 }
2482
2483 /// Determines whether the member name was preceded by the template keyword.
hasTemplateKeyword()2484 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
2485
2486 /// \brief Determines whether the member name was followed by an
2487 /// explicit template argument list.
hasExplicitTemplateArgs()2488 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
2489
2490 /// \brief Copies the template arguments (if present) into the given
2491 /// structure.
copyTemplateArgumentsInto(TemplateArgumentListInfo & List)2492 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2493 if (hasExplicitTemplateArgs())
2494 getExplicitTemplateArgs().copyInto(List);
2495 }
2496
2497 /// \brief Retrieve the explicit template argument list that
2498 /// follow the member template name. This must only be called on an
2499 /// expression with explicit template arguments.
getExplicitTemplateArgs()2500 ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
2501 assert(hasExplicitTemplateArgs());
2502 return *getTemplateKWAndArgsInfo();
2503 }
2504
2505 /// \brief Retrieve the explicit template argument list that
2506 /// followed the member template name. This must only be called on
2507 /// an expression with explicit template arguments.
getExplicitTemplateArgs()2508 const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
2509 return const_cast<MemberExpr *>(this)->getExplicitTemplateArgs();
2510 }
2511
2512 /// \brief Retrieves the optional explicit template arguments.
2513 /// This points to the same data as getExplicitTemplateArgs(), but
2514 /// returns null if there are no explicit template arguments.
getOptionalExplicitTemplateArgs()2515 const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const {
2516 if (!hasExplicitTemplateArgs()) return nullptr;
2517 return &getExplicitTemplateArgs();
2518 }
2519
2520 /// \brief Retrieve the template arguments provided as part of this
2521 /// template-id.
getTemplateArgs()2522 const TemplateArgumentLoc *getTemplateArgs() const {
2523 if (!hasExplicitTemplateArgs())
2524 return nullptr;
2525
2526 return getExplicitTemplateArgs().getTemplateArgs();
2527 }
2528
2529 /// \brief Retrieve the number of template arguments provided as part of this
2530 /// template-id.
getNumTemplateArgs()2531 unsigned getNumTemplateArgs() const {
2532 if (!hasExplicitTemplateArgs())
2533 return 0;
2534
2535 return getExplicitTemplateArgs().NumTemplateArgs;
2536 }
2537
2538 /// \brief Retrieve the member declaration name info.
getMemberNameInfo()2539 DeclarationNameInfo getMemberNameInfo() const {
2540 return DeclarationNameInfo(MemberDecl->getDeclName(),
2541 MemberLoc, MemberDNLoc);
2542 }
2543
getOperatorLoc()2544 SourceLocation getOperatorLoc() const LLVM_READONLY { return OperatorLoc; }
2545
isArrow()2546 bool isArrow() const { return IsArrow; }
setArrow(bool A)2547 void setArrow(bool A) { IsArrow = A; }
2548
2549 /// getMemberLoc - Return the location of the "member", in X->F, it is the
2550 /// location of 'F'.
getMemberLoc()2551 SourceLocation getMemberLoc() const { return MemberLoc; }
setMemberLoc(SourceLocation L)2552 void setMemberLoc(SourceLocation L) { MemberLoc = L; }
2553
2554 SourceLocation getLocStart() const LLVM_READONLY;
2555 SourceLocation getLocEnd() const LLVM_READONLY;
2556
getExprLoc()2557 SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; }
2558
2559 /// \brief Determine whether the base of this explicit is implicit.
isImplicitAccess()2560 bool isImplicitAccess() const {
2561 return getBase() && getBase()->isImplicitCXXThis();
2562 }
2563
2564 /// \brief Returns true if this member expression refers to a method that
2565 /// was resolved from an overloaded set having size greater than 1.
hadMultipleCandidates()2566 bool hadMultipleCandidates() const {
2567 return HadMultipleCandidates;
2568 }
2569 /// \brief Sets the flag telling whether this expression refers to
2570 /// a method that was resolved from an overloaded set having size
2571 /// greater than 1.
2572 void setHadMultipleCandidates(bool V = true) {
2573 HadMultipleCandidates = V;
2574 }
2575
classof(const Stmt * T)2576 static bool classof(const Stmt *T) {
2577 return T->getStmtClass() == MemberExprClass;
2578 }
2579
2580 // Iterators
children()2581 child_range children() { return child_range(&Base, &Base+1); }
2582
2583 friend class ASTReader;
2584 friend class ASTStmtWriter;
2585 };
2586
2587 /// CompoundLiteralExpr - [C99 6.5.2.5]
2588 ///
2589 class CompoundLiteralExpr : public Expr {
2590 /// LParenLoc - If non-null, this is the location of the left paren in a
2591 /// compound literal like "(int){4}". This can be null if this is a
2592 /// synthesized compound expression.
2593 SourceLocation LParenLoc;
2594
2595 /// The type as written. This can be an incomplete array type, in
2596 /// which case the actual expression type will be different.
2597 /// The int part of the pair stores whether this expr is file scope.
2598 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
2599 Stmt *Init;
2600 public:
CompoundLiteralExpr(SourceLocation lparenloc,TypeSourceInfo * tinfo,QualType T,ExprValueKind VK,Expr * init,bool fileScope)2601 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
2602 QualType T, ExprValueKind VK, Expr *init, bool fileScope)
2603 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary,
2604 tinfo->getType()->isDependentType(),
2605 init->isValueDependent(),
2606 (init->isInstantiationDependent() ||
2607 tinfo->getType()->isInstantiationDependentType()),
2608 init->containsUnexpandedParameterPack()),
2609 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {}
2610
2611 /// \brief Construct an empty compound literal.
CompoundLiteralExpr(EmptyShell Empty)2612 explicit CompoundLiteralExpr(EmptyShell Empty)
2613 : Expr(CompoundLiteralExprClass, Empty) { }
2614
getInitializer()2615 const Expr *getInitializer() const { return cast<Expr>(Init); }
getInitializer()2616 Expr *getInitializer() { return cast<Expr>(Init); }
setInitializer(Expr * E)2617 void setInitializer(Expr *E) { Init = E; }
2618
isFileScope()2619 bool isFileScope() const { return TInfoAndScope.getInt(); }
setFileScope(bool FS)2620 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
2621
getLParenLoc()2622 SourceLocation getLParenLoc() const { return LParenLoc; }
setLParenLoc(SourceLocation L)2623 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2624
getTypeSourceInfo()2625 TypeSourceInfo *getTypeSourceInfo() const {
2626 return TInfoAndScope.getPointer();
2627 }
setTypeSourceInfo(TypeSourceInfo * tinfo)2628 void setTypeSourceInfo(TypeSourceInfo *tinfo) {
2629 TInfoAndScope.setPointer(tinfo);
2630 }
2631
getLocStart()2632 SourceLocation getLocStart() const LLVM_READONLY {
2633 // FIXME: Init should never be null.
2634 if (!Init)
2635 return SourceLocation();
2636 if (LParenLoc.isInvalid())
2637 return Init->getLocStart();
2638 return LParenLoc;
2639 }
getLocEnd()2640 SourceLocation getLocEnd() const LLVM_READONLY {
2641 // FIXME: Init should never be null.
2642 if (!Init)
2643 return SourceLocation();
2644 return Init->getLocEnd();
2645 }
2646
classof(const Stmt * T)2647 static bool classof(const Stmt *T) {
2648 return T->getStmtClass() == CompoundLiteralExprClass;
2649 }
2650
2651 // Iterators
children()2652 child_range children() { return child_range(&Init, &Init+1); }
2653 };
2654
2655 /// CastExpr - Base class for type casts, including both implicit
2656 /// casts (ImplicitCastExpr) and explicit casts that have some
2657 /// representation in the source code (ExplicitCastExpr's derived
2658 /// classes).
2659 class CastExpr : public Expr {
2660 private:
2661 Stmt *Op;
2662
2663 bool CastConsistency() const;
2664
path_buffer()2665 const CXXBaseSpecifier * const *path_buffer() const {
2666 return const_cast<CastExpr*>(this)->path_buffer();
2667 }
2668 CXXBaseSpecifier **path_buffer();
2669
setBasePathSize(unsigned basePathSize)2670 void setBasePathSize(unsigned basePathSize) {
2671 CastExprBits.BasePathSize = basePathSize;
2672 assert(CastExprBits.BasePathSize == basePathSize &&
2673 "basePathSize doesn't fit in bits of CastExprBits.BasePathSize!");
2674 }
2675
2676 protected:
CastExpr(StmtClass SC,QualType ty,ExprValueKind VK,const CastKind kind,Expr * op,unsigned BasePathSize)2677 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind,
2678 Expr *op, unsigned BasePathSize)
2679 : Expr(SC, ty, VK, OK_Ordinary,
2680 // Cast expressions are type-dependent if the type is
2681 // dependent (C++ [temp.dep.expr]p3).
2682 ty->isDependentType(),
2683 // Cast expressions are value-dependent if the type is
2684 // dependent or if the subexpression is value-dependent.
2685 ty->isDependentType() || (op && op->isValueDependent()),
2686 (ty->isInstantiationDependentType() ||
2687 (op && op->isInstantiationDependent())),
2688 // An implicit cast expression doesn't (lexically) contain an
2689 // unexpanded pack, even if its target type does.
2690 ((SC != ImplicitCastExprClass &&
2691 ty->containsUnexpandedParameterPack()) ||
2692 (op && op->containsUnexpandedParameterPack()))),
2693 Op(op) {
2694 assert(kind != CK_Invalid && "creating cast with invalid cast kind");
2695 CastExprBits.Kind = kind;
2696 setBasePathSize(BasePathSize);
2697 assert(CastConsistency());
2698 }
2699
2700 /// \brief Construct an empty cast.
CastExpr(StmtClass SC,EmptyShell Empty,unsigned BasePathSize)2701 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
2702 : Expr(SC, Empty) {
2703 setBasePathSize(BasePathSize);
2704 }
2705
2706 public:
getCastKind()2707 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
setCastKind(CastKind K)2708 void setCastKind(CastKind K) { CastExprBits.Kind = K; }
2709 const char *getCastKindName() const;
2710
getSubExpr()2711 Expr *getSubExpr() { return cast<Expr>(Op); }
getSubExpr()2712 const Expr *getSubExpr() const { return cast<Expr>(Op); }
setSubExpr(Expr * E)2713 void setSubExpr(Expr *E) { Op = E; }
2714
2715 /// \brief Retrieve the cast subexpression as it was written in the source
2716 /// code, looking through any implicit casts or other intermediate nodes
2717 /// introduced by semantic analysis.
2718 Expr *getSubExprAsWritten();
getSubExprAsWritten()2719 const Expr *getSubExprAsWritten() const {
2720 return const_cast<CastExpr *>(this)->getSubExprAsWritten();
2721 }
2722
2723 typedef CXXBaseSpecifier **path_iterator;
2724 typedef const CXXBaseSpecifier * const *path_const_iterator;
path_empty()2725 bool path_empty() const { return CastExprBits.BasePathSize == 0; }
path_size()2726 unsigned path_size() const { return CastExprBits.BasePathSize; }
path_begin()2727 path_iterator path_begin() { return path_buffer(); }
path_end()2728 path_iterator path_end() { return path_buffer() + path_size(); }
path_begin()2729 path_const_iterator path_begin() const { return path_buffer(); }
path_end()2730 path_const_iterator path_end() const { return path_buffer() + path_size(); }
2731
2732 void setCastPath(const CXXCastPath &Path);
2733
classof(const Stmt * T)2734 static bool classof(const Stmt *T) {
2735 return T->getStmtClass() >= firstCastExprConstant &&
2736 T->getStmtClass() <= lastCastExprConstant;
2737 }
2738
2739 // Iterators
children()2740 child_range children() { return child_range(&Op, &Op+1); }
2741 };
2742
2743 /// ImplicitCastExpr - Allows us to explicitly represent implicit type
2744 /// conversions, which have no direct representation in the original
2745 /// source code. For example: converting T[]->T*, void f()->void
2746 /// (*f)(), float->double, short->int, etc.
2747 ///
2748 /// In C, implicit casts always produce rvalues. However, in C++, an
2749 /// implicit cast whose result is being bound to a reference will be
2750 /// an lvalue or xvalue. For example:
2751 ///
2752 /// @code
2753 /// class Base { };
2754 /// class Derived : public Base { };
2755 /// Derived &&ref();
2756 /// void f(Derived d) {
2757 /// Base& b = d; // initializer is an ImplicitCastExpr
2758 /// // to an lvalue of type Base
2759 /// Base&& r = ref(); // initializer is an ImplicitCastExpr
2760 /// // to an xvalue of type Base
2761 /// }
2762 /// @endcode
2763 class ImplicitCastExpr : public CastExpr {
2764 private:
ImplicitCastExpr(QualType ty,CastKind kind,Expr * op,unsigned BasePathLength,ExprValueKind VK)2765 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
2766 unsigned BasePathLength, ExprValueKind VK)
2767 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) {
2768 }
2769
2770 /// \brief Construct an empty implicit cast.
ImplicitCastExpr(EmptyShell Shell,unsigned PathSize)2771 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize)
2772 : CastExpr(ImplicitCastExprClass, Shell, PathSize) { }
2773
2774 public:
2775 enum OnStack_t { OnStack };
ImplicitCastExpr(OnStack_t _,QualType ty,CastKind kind,Expr * op,ExprValueKind VK)2776 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
2777 ExprValueKind VK)
2778 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) {
2779 }
2780
2781 static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
2782 CastKind Kind, Expr *Operand,
2783 const CXXCastPath *BasePath,
2784 ExprValueKind Cat);
2785
2786 static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
2787 unsigned PathSize);
2788
getLocStart()2789 SourceLocation getLocStart() const LLVM_READONLY {
2790 return getSubExpr()->getLocStart();
2791 }
getLocEnd()2792 SourceLocation getLocEnd() const LLVM_READONLY {
2793 return getSubExpr()->getLocEnd();
2794 }
2795
classof(const Stmt * T)2796 static bool classof(const Stmt *T) {
2797 return T->getStmtClass() == ImplicitCastExprClass;
2798 }
2799 };
2800
IgnoreImpCasts()2801 inline Expr *Expr::IgnoreImpCasts() {
2802 Expr *e = this;
2803 while (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
2804 e = ice->getSubExpr();
2805 return e;
2806 }
2807
2808 /// ExplicitCastExpr - An explicit cast written in the source
2809 /// code.
2810 ///
2811 /// This class is effectively an abstract class, because it provides
2812 /// the basic representation of an explicitly-written cast without
2813 /// specifying which kind of cast (C cast, functional cast, static
2814 /// cast, etc.) was written; specific derived classes represent the
2815 /// particular style of cast and its location information.
2816 ///
2817 /// Unlike implicit casts, explicit cast nodes have two different
2818 /// types: the type that was written into the source code, and the
2819 /// actual type of the expression as determined by semantic
2820 /// analysis. These types may differ slightly. For example, in C++ one
2821 /// can cast to a reference type, which indicates that the resulting
2822 /// expression will be an lvalue or xvalue. The reference type, however,
2823 /// will not be used as the type of the expression.
2824 class ExplicitCastExpr : public CastExpr {
2825 /// TInfo - Source type info for the (written) type
2826 /// this expression is casting to.
2827 TypeSourceInfo *TInfo;
2828
2829 protected:
ExplicitCastExpr(StmtClass SC,QualType exprTy,ExprValueKind VK,CastKind kind,Expr * op,unsigned PathSize,TypeSourceInfo * writtenTy)2830 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
2831 CastKind kind, Expr *op, unsigned PathSize,
2832 TypeSourceInfo *writtenTy)
2833 : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {}
2834
2835 /// \brief Construct an empty explicit cast.
ExplicitCastExpr(StmtClass SC,EmptyShell Shell,unsigned PathSize)2836 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
2837 : CastExpr(SC, Shell, PathSize) { }
2838
2839 public:
2840 /// getTypeInfoAsWritten - Returns the type source info for the type
2841 /// that this expression is casting to.
getTypeInfoAsWritten()2842 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
setTypeInfoAsWritten(TypeSourceInfo * writtenTy)2843 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
2844
2845 /// getTypeAsWritten - Returns the type that this expression is
2846 /// casting to, as written in the source code.
getTypeAsWritten()2847 QualType getTypeAsWritten() const { return TInfo->getType(); }
2848
classof(const Stmt * T)2849 static bool classof(const Stmt *T) {
2850 return T->getStmtClass() >= firstExplicitCastExprConstant &&
2851 T->getStmtClass() <= lastExplicitCastExprConstant;
2852 }
2853 };
2854
2855 /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
2856 /// cast in C++ (C++ [expr.cast]), which uses the syntax
2857 /// (Type)expr. For example: @c (int)f.
2858 class CStyleCastExpr : public ExplicitCastExpr {
2859 SourceLocation LPLoc; // the location of the left paren
2860 SourceLocation RPLoc; // the location of the right paren
2861
CStyleCastExpr(QualType exprTy,ExprValueKind vk,CastKind kind,Expr * op,unsigned PathSize,TypeSourceInfo * writtenTy,SourceLocation l,SourceLocation r)2862 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
2863 unsigned PathSize, TypeSourceInfo *writtenTy,
2864 SourceLocation l, SourceLocation r)
2865 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
2866 writtenTy), LPLoc(l), RPLoc(r) {}
2867
2868 /// \brief Construct an empty C-style explicit cast.
CStyleCastExpr(EmptyShell Shell,unsigned PathSize)2869 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize)
2870 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { }
2871
2872 public:
2873 static CStyleCastExpr *Create(const ASTContext &Context, QualType T,
2874 ExprValueKind VK, CastKind K,
2875 Expr *Op, const CXXCastPath *BasePath,
2876 TypeSourceInfo *WrittenTy, SourceLocation L,
2877 SourceLocation R);
2878
2879 static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
2880 unsigned PathSize);
2881
getLParenLoc()2882 SourceLocation getLParenLoc() const { return LPLoc; }
setLParenLoc(SourceLocation L)2883 void setLParenLoc(SourceLocation L) { LPLoc = L; }
2884
getRParenLoc()2885 SourceLocation getRParenLoc() const { return RPLoc; }
setRParenLoc(SourceLocation L)2886 void setRParenLoc(SourceLocation L) { RPLoc = L; }
2887
getLocStart()2888 SourceLocation getLocStart() const LLVM_READONLY { return LPLoc; }
getLocEnd()2889 SourceLocation getLocEnd() const LLVM_READONLY {
2890 return getSubExpr()->getLocEnd();
2891 }
2892
classof(const Stmt * T)2893 static bool classof(const Stmt *T) {
2894 return T->getStmtClass() == CStyleCastExprClass;
2895 }
2896 };
2897
2898 /// \brief A builtin binary operation expression such as "x + y" or "x <= y".
2899 ///
2900 /// This expression node kind describes a builtin binary operation,
2901 /// such as "x + y" for integer values "x" and "y". The operands will
2902 /// already have been converted to appropriate types (e.g., by
2903 /// performing promotions or conversions).
2904 ///
2905 /// In C++, where operators may be overloaded, a different kind of
2906 /// expression node (CXXOperatorCallExpr) is used to express the
2907 /// invocation of an overloaded operator with operator syntax. Within
2908 /// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
2909 /// used to store an expression "x + y" depends on the subexpressions
2910 /// for x and y. If neither x or y is type-dependent, and the "+"
2911 /// operator resolves to a built-in operation, BinaryOperator will be
2912 /// used to express the computation (x and y may still be
2913 /// value-dependent). If either x or y is type-dependent, or if the
2914 /// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
2915 /// be used to express the computation.
2916 class BinaryOperator : public Expr {
2917 public:
2918 typedef BinaryOperatorKind Opcode;
2919
2920 private:
2921 unsigned Opc : 6;
2922
2923 // Records the FP_CONTRACT pragma status at the point that this binary
2924 // operator was parsed. This bit is only meaningful for operations on
2925 // floating point types. For all other types it should default to
2926 // false.
2927 unsigned FPContractable : 1;
2928 SourceLocation OpLoc;
2929
2930 enum { LHS, RHS, END_EXPR };
2931 Stmt* SubExprs[END_EXPR];
2932 public:
2933
BinaryOperator(Expr * lhs,Expr * rhs,Opcode opc,QualType ResTy,ExprValueKind VK,ExprObjectKind OK,SourceLocation opLoc,bool fpContractable)2934 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2935 ExprValueKind VK, ExprObjectKind OK,
2936 SourceLocation opLoc, bool fpContractable)
2937 : Expr(BinaryOperatorClass, ResTy, VK, OK,
2938 lhs->isTypeDependent() || rhs->isTypeDependent(),
2939 lhs->isValueDependent() || rhs->isValueDependent(),
2940 (lhs->isInstantiationDependent() ||
2941 rhs->isInstantiationDependent()),
2942 (lhs->containsUnexpandedParameterPack() ||
2943 rhs->containsUnexpandedParameterPack())),
2944 Opc(opc), FPContractable(fpContractable), OpLoc(opLoc) {
2945 SubExprs[LHS] = lhs;
2946 SubExprs[RHS] = rhs;
2947 assert(!isCompoundAssignmentOp() &&
2948 "Use CompoundAssignOperator for compound assignments");
2949 }
2950
2951 /// \brief Construct an empty binary operator.
BinaryOperator(EmptyShell Empty)2952 explicit BinaryOperator(EmptyShell Empty)
2953 : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { }
2954
getExprLoc()2955 SourceLocation getExprLoc() const LLVM_READONLY { return OpLoc; }
getOperatorLoc()2956 SourceLocation getOperatorLoc() const { return OpLoc; }
setOperatorLoc(SourceLocation L)2957 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2958
getOpcode()2959 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
setOpcode(Opcode O)2960 void setOpcode(Opcode O) { Opc = O; }
2961
getLHS()2962 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
setLHS(Expr * E)2963 void setLHS(Expr *E) { SubExprs[LHS] = E; }
getRHS()2964 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
setRHS(Expr * E)2965 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2966
getLocStart()2967 SourceLocation getLocStart() const LLVM_READONLY {
2968 return getLHS()->getLocStart();
2969 }
getLocEnd()2970 SourceLocation getLocEnd() const LLVM_READONLY {
2971 return getRHS()->getLocEnd();
2972 }
2973
2974 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2975 /// corresponds to, e.g. "<<=".
2976 static StringRef getOpcodeStr(Opcode Op);
2977
getOpcodeStr()2978 StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
2979
2980 /// \brief Retrieve the binary opcode that corresponds to the given
2981 /// overloaded operator.
2982 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
2983
2984 /// \brief Retrieve the overloaded operator kind that corresponds to
2985 /// the given binary opcode.
2986 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
2987
2988 /// predicates to categorize the respective opcodes.
isPtrMemOp()2989 bool isPtrMemOp() const { return Opc == BO_PtrMemD || Opc == BO_PtrMemI; }
isMultiplicativeOp()2990 bool isMultiplicativeOp() const { return Opc >= BO_Mul && Opc <= BO_Rem; }
isAdditiveOp(Opcode Opc)2991 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
isAdditiveOp()2992 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
isShiftOp(Opcode Opc)2993 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
isShiftOp()2994 bool isShiftOp() const { return isShiftOp(getOpcode()); }
2995
isBitwiseOp(Opcode Opc)2996 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
isBitwiseOp()2997 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
2998
isRelationalOp(Opcode Opc)2999 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
isRelationalOp()3000 bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
3001
isEqualityOp(Opcode Opc)3002 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
isEqualityOp()3003 bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
3004
isComparisonOp(Opcode Opc)3005 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_NE; }
isComparisonOp()3006 bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
3007
negateComparisonOp(Opcode Opc)3008 static Opcode negateComparisonOp(Opcode Opc) {
3009 switch (Opc) {
3010 default:
3011 llvm_unreachable("Not a comparsion operator.");
3012 case BO_LT: return BO_GE;
3013 case BO_GT: return BO_LE;
3014 case BO_LE: return BO_GT;
3015 case BO_GE: return BO_LT;
3016 case BO_EQ: return BO_NE;
3017 case BO_NE: return BO_EQ;
3018 }
3019 }
3020
reverseComparisonOp(Opcode Opc)3021 static Opcode reverseComparisonOp(Opcode Opc) {
3022 switch (Opc) {
3023 default:
3024 llvm_unreachable("Not a comparsion operator.");
3025 case BO_LT: return BO_GT;
3026 case BO_GT: return BO_LT;
3027 case BO_LE: return BO_GE;
3028 case BO_GE: return BO_LE;
3029 case BO_EQ:
3030 case BO_NE:
3031 return Opc;
3032 }
3033 }
3034
isLogicalOp(Opcode Opc)3035 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
isLogicalOp()3036 bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
3037
isAssignmentOp(Opcode Opc)3038 static bool isAssignmentOp(Opcode Opc) {
3039 return Opc >= BO_Assign && Opc <= BO_OrAssign;
3040 }
isAssignmentOp()3041 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
3042
isCompoundAssignmentOp(Opcode Opc)3043 static bool isCompoundAssignmentOp(Opcode Opc) {
3044 return Opc > BO_Assign && Opc <= BO_OrAssign;
3045 }
isCompoundAssignmentOp()3046 bool isCompoundAssignmentOp() const {
3047 return isCompoundAssignmentOp(getOpcode());
3048 }
getOpForCompoundAssignment(Opcode Opc)3049 static Opcode getOpForCompoundAssignment(Opcode Opc) {
3050 assert(isCompoundAssignmentOp(Opc));
3051 if (Opc >= BO_AndAssign)
3052 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
3053 else
3054 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
3055 }
3056
isShiftAssignOp(Opcode Opc)3057 static bool isShiftAssignOp(Opcode Opc) {
3058 return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
3059 }
isShiftAssignOp()3060 bool isShiftAssignOp() const {
3061 return isShiftAssignOp(getOpcode());
3062 }
3063
classof(const Stmt * S)3064 static bool classof(const Stmt *S) {
3065 return S->getStmtClass() >= firstBinaryOperatorConstant &&
3066 S->getStmtClass() <= lastBinaryOperatorConstant;
3067 }
3068
3069 // Iterators
children()3070 child_range children() {
3071 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3072 }
3073
3074 // Set the FP contractability status of this operator. Only meaningful for
3075 // operations on floating point types.
setFPContractable(bool FPC)3076 void setFPContractable(bool FPC) { FPContractable = FPC; }
3077
3078 // Get the FP contractability status of this operator. Only meaningful for
3079 // operations on floating point types.
isFPContractable()3080 bool isFPContractable() const { return FPContractable; }
3081
3082 protected:
BinaryOperator(Expr * lhs,Expr * rhs,Opcode opc,QualType ResTy,ExprValueKind VK,ExprObjectKind OK,SourceLocation opLoc,bool fpContractable,bool dead2)3083 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
3084 ExprValueKind VK, ExprObjectKind OK,
3085 SourceLocation opLoc, bool fpContractable, bool dead2)
3086 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK,
3087 lhs->isTypeDependent() || rhs->isTypeDependent(),
3088 lhs->isValueDependent() || rhs->isValueDependent(),
3089 (lhs->isInstantiationDependent() ||
3090 rhs->isInstantiationDependent()),
3091 (lhs->containsUnexpandedParameterPack() ||
3092 rhs->containsUnexpandedParameterPack())),
3093 Opc(opc), FPContractable(fpContractable), OpLoc(opLoc) {
3094 SubExprs[LHS] = lhs;
3095 SubExprs[RHS] = rhs;
3096 }
3097
BinaryOperator(StmtClass SC,EmptyShell Empty)3098 BinaryOperator(StmtClass SC, EmptyShell Empty)
3099 : Expr(SC, Empty), Opc(BO_MulAssign) { }
3100 };
3101
3102 /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
3103 /// track of the type the operation is performed in. Due to the semantics of
3104 /// these operators, the operands are promoted, the arithmetic performed, an
3105 /// implicit conversion back to the result type done, then the assignment takes
3106 /// place. This captures the intermediate type which the computation is done
3107 /// in.
3108 class CompoundAssignOperator : public BinaryOperator {
3109 QualType ComputationLHSType;
3110 QualType ComputationResultType;
3111 public:
CompoundAssignOperator(Expr * lhs,Expr * rhs,Opcode opc,QualType ResType,ExprValueKind VK,ExprObjectKind OK,QualType CompLHSType,QualType CompResultType,SourceLocation OpLoc,bool fpContractable)3112 CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType,
3113 ExprValueKind VK, ExprObjectKind OK,
3114 QualType CompLHSType, QualType CompResultType,
3115 SourceLocation OpLoc, bool fpContractable)
3116 : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, fpContractable,
3117 true),
3118 ComputationLHSType(CompLHSType),
3119 ComputationResultType(CompResultType) {
3120 assert(isCompoundAssignmentOp() &&
3121 "Only should be used for compound assignments");
3122 }
3123
3124 /// \brief Build an empty compound assignment operator expression.
CompoundAssignOperator(EmptyShell Empty)3125 explicit CompoundAssignOperator(EmptyShell Empty)
3126 : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
3127
3128 // The two computation types are the type the LHS is converted
3129 // to for the computation and the type of the result; the two are
3130 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
getComputationLHSType()3131 QualType getComputationLHSType() const { return ComputationLHSType; }
setComputationLHSType(QualType T)3132 void setComputationLHSType(QualType T) { ComputationLHSType = T; }
3133
getComputationResultType()3134 QualType getComputationResultType() const { return ComputationResultType; }
setComputationResultType(QualType T)3135 void setComputationResultType(QualType T) { ComputationResultType = T; }
3136
classof(const Stmt * S)3137 static bool classof(const Stmt *S) {
3138 return S->getStmtClass() == CompoundAssignOperatorClass;
3139 }
3140 };
3141
3142 /// AbstractConditionalOperator - An abstract base class for
3143 /// ConditionalOperator and BinaryConditionalOperator.
3144 class AbstractConditionalOperator : public Expr {
3145 SourceLocation QuestionLoc, ColonLoc;
3146 friend class ASTStmtReader;
3147
3148 protected:
AbstractConditionalOperator(StmtClass SC,QualType T,ExprValueKind VK,ExprObjectKind OK,bool TD,bool VD,bool ID,bool ContainsUnexpandedParameterPack,SourceLocation qloc,SourceLocation cloc)3149 AbstractConditionalOperator(StmtClass SC, QualType T,
3150 ExprValueKind VK, ExprObjectKind OK,
3151 bool TD, bool VD, bool ID,
3152 bool ContainsUnexpandedParameterPack,
3153 SourceLocation qloc,
3154 SourceLocation cloc)
3155 : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack),
3156 QuestionLoc(qloc), ColonLoc(cloc) {}
3157
AbstractConditionalOperator(StmtClass SC,EmptyShell Empty)3158 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
3159 : Expr(SC, Empty) { }
3160
3161 public:
3162 // getCond - Return the expression representing the condition for
3163 // the ?: operator.
3164 Expr *getCond() const;
3165
3166 // getTrueExpr - Return the subexpression representing the value of
3167 // the expression if the condition evaluates to true.
3168 Expr *getTrueExpr() const;
3169
3170 // getFalseExpr - Return the subexpression representing the value of
3171 // the expression if the condition evaluates to false. This is
3172 // the same as getRHS.
3173 Expr *getFalseExpr() const;
3174
getQuestionLoc()3175 SourceLocation getQuestionLoc() const { return QuestionLoc; }
getColonLoc()3176 SourceLocation getColonLoc() const { return ColonLoc; }
3177
classof(const Stmt * T)3178 static bool classof(const Stmt *T) {
3179 return T->getStmtClass() == ConditionalOperatorClass ||
3180 T->getStmtClass() == BinaryConditionalOperatorClass;
3181 }
3182 };
3183
3184 /// ConditionalOperator - The ?: ternary operator. The GNU "missing
3185 /// middle" extension is a BinaryConditionalOperator.
3186 class ConditionalOperator : public AbstractConditionalOperator {
3187 enum { COND, LHS, RHS, END_EXPR };
3188 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3189
3190 friend class ASTStmtReader;
3191 public:
ConditionalOperator(Expr * cond,SourceLocation QLoc,Expr * lhs,SourceLocation CLoc,Expr * rhs,QualType t,ExprValueKind VK,ExprObjectKind OK)3192 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
3193 SourceLocation CLoc, Expr *rhs,
3194 QualType t, ExprValueKind VK, ExprObjectKind OK)
3195 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK,
3196 // FIXME: the type of the conditional operator doesn't
3197 // depend on the type of the conditional, but the standard
3198 // seems to imply that it could. File a bug!
3199 (lhs->isTypeDependent() || rhs->isTypeDependent()),
3200 (cond->isValueDependent() || lhs->isValueDependent() ||
3201 rhs->isValueDependent()),
3202 (cond->isInstantiationDependent() ||
3203 lhs->isInstantiationDependent() ||
3204 rhs->isInstantiationDependent()),
3205 (cond->containsUnexpandedParameterPack() ||
3206 lhs->containsUnexpandedParameterPack() ||
3207 rhs->containsUnexpandedParameterPack()),
3208 QLoc, CLoc) {
3209 SubExprs[COND] = cond;
3210 SubExprs[LHS] = lhs;
3211 SubExprs[RHS] = rhs;
3212 }
3213
3214 /// \brief Build an empty conditional operator.
ConditionalOperator(EmptyShell Empty)3215 explicit ConditionalOperator(EmptyShell Empty)
3216 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
3217
3218 // getCond - Return the expression representing the condition for
3219 // the ?: operator.
getCond()3220 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3221
3222 // getTrueExpr - Return the subexpression representing the value of
3223 // the expression if the condition evaluates to true.
getTrueExpr()3224 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
3225
3226 // getFalseExpr - Return the subexpression representing the value of
3227 // the expression if the condition evaluates to false. This is
3228 // the same as getRHS.
getFalseExpr()3229 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
3230
getLHS()3231 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
getRHS()3232 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3233
getLocStart()3234 SourceLocation getLocStart() const LLVM_READONLY {
3235 return getCond()->getLocStart();
3236 }
getLocEnd()3237 SourceLocation getLocEnd() const LLVM_READONLY {
3238 return getRHS()->getLocEnd();
3239 }
3240
classof(const Stmt * T)3241 static bool classof(const Stmt *T) {
3242 return T->getStmtClass() == ConditionalOperatorClass;
3243 }
3244
3245 // Iterators
children()3246 child_range children() {
3247 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3248 }
3249 };
3250
3251 /// BinaryConditionalOperator - The GNU extension to the conditional
3252 /// operator which allows the middle operand to be omitted.
3253 ///
3254 /// This is a different expression kind on the assumption that almost
3255 /// every client ends up needing to know that these are different.
3256 class BinaryConditionalOperator : public AbstractConditionalOperator {
3257 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
3258
3259 /// - the common condition/left-hand-side expression, which will be
3260 /// evaluated as the opaque value
3261 /// - the condition, expressed in terms of the opaque value
3262 /// - the left-hand-side, expressed in terms of the opaque value
3263 /// - the right-hand-side
3264 Stmt *SubExprs[NUM_SUBEXPRS];
3265 OpaqueValueExpr *OpaqueValue;
3266
3267 friend class ASTStmtReader;
3268 public:
BinaryConditionalOperator(Expr * common,OpaqueValueExpr * opaqueValue,Expr * cond,Expr * lhs,Expr * rhs,SourceLocation qloc,SourceLocation cloc,QualType t,ExprValueKind VK,ExprObjectKind OK)3269 BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
3270 Expr *cond, Expr *lhs, Expr *rhs,
3271 SourceLocation qloc, SourceLocation cloc,
3272 QualType t, ExprValueKind VK, ExprObjectKind OK)
3273 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
3274 (common->isTypeDependent() || rhs->isTypeDependent()),
3275 (common->isValueDependent() || rhs->isValueDependent()),
3276 (common->isInstantiationDependent() ||
3277 rhs->isInstantiationDependent()),
3278 (common->containsUnexpandedParameterPack() ||
3279 rhs->containsUnexpandedParameterPack()),
3280 qloc, cloc),
3281 OpaqueValue(opaqueValue) {
3282 SubExprs[COMMON] = common;
3283 SubExprs[COND] = cond;
3284 SubExprs[LHS] = lhs;
3285 SubExprs[RHS] = rhs;
3286 assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value");
3287 }
3288
3289 /// \brief Build an empty conditional operator.
BinaryConditionalOperator(EmptyShell Empty)3290 explicit BinaryConditionalOperator(EmptyShell Empty)
3291 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
3292
3293 /// \brief getCommon - Return the common expression, written to the
3294 /// left of the condition. The opaque value will be bound to the
3295 /// result of this expression.
getCommon()3296 Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
3297
3298 /// \brief getOpaqueValue - Return the opaque value placeholder.
getOpaqueValue()3299 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
3300
3301 /// \brief getCond - Return the condition expression; this is defined
3302 /// in terms of the opaque value.
getCond()3303 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3304
3305 /// \brief getTrueExpr - Return the subexpression which will be
3306 /// evaluated if the condition evaluates to true; this is defined
3307 /// in terms of the opaque value.
getTrueExpr()3308 Expr *getTrueExpr() const {
3309 return cast<Expr>(SubExprs[LHS]);
3310 }
3311
3312 /// \brief getFalseExpr - Return the subexpression which will be
3313 /// evaluated if the condnition evaluates to false; this is
3314 /// defined in terms of the opaque value.
getFalseExpr()3315 Expr *getFalseExpr() const {
3316 return cast<Expr>(SubExprs[RHS]);
3317 }
3318
getLocStart()3319 SourceLocation getLocStart() const LLVM_READONLY {
3320 return getCommon()->getLocStart();
3321 }
getLocEnd()3322 SourceLocation getLocEnd() const LLVM_READONLY {
3323 return getFalseExpr()->getLocEnd();
3324 }
3325
classof(const Stmt * T)3326 static bool classof(const Stmt *T) {
3327 return T->getStmtClass() == BinaryConditionalOperatorClass;
3328 }
3329
3330 // Iterators
children()3331 child_range children() {
3332 return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
3333 }
3334 };
3335
getCond()3336 inline Expr *AbstractConditionalOperator::getCond() const {
3337 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3338 return co->getCond();
3339 return cast<BinaryConditionalOperator>(this)->getCond();
3340 }
3341
getTrueExpr()3342 inline Expr *AbstractConditionalOperator::getTrueExpr() const {
3343 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3344 return co->getTrueExpr();
3345 return cast<BinaryConditionalOperator>(this)->getTrueExpr();
3346 }
3347
getFalseExpr()3348 inline Expr *AbstractConditionalOperator::getFalseExpr() const {
3349 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3350 return co->getFalseExpr();
3351 return cast<BinaryConditionalOperator>(this)->getFalseExpr();
3352 }
3353
3354 /// AddrLabelExpr - The GNU address of label extension, representing &&label.
3355 class AddrLabelExpr : public Expr {
3356 SourceLocation AmpAmpLoc, LabelLoc;
3357 LabelDecl *Label;
3358 public:
AddrLabelExpr(SourceLocation AALoc,SourceLocation LLoc,LabelDecl * L,QualType t)3359 AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
3360 QualType t)
3361 : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false,
3362 false),
3363 AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
3364
3365 /// \brief Build an empty address of a label expression.
AddrLabelExpr(EmptyShell Empty)3366 explicit AddrLabelExpr(EmptyShell Empty)
3367 : Expr(AddrLabelExprClass, Empty) { }
3368
getAmpAmpLoc()3369 SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
setAmpAmpLoc(SourceLocation L)3370 void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
getLabelLoc()3371 SourceLocation getLabelLoc() const { return LabelLoc; }
setLabelLoc(SourceLocation L)3372 void setLabelLoc(SourceLocation L) { LabelLoc = L; }
3373
getLocStart()3374 SourceLocation getLocStart() const LLVM_READONLY { return AmpAmpLoc; }
getLocEnd()3375 SourceLocation getLocEnd() const LLVM_READONLY { return LabelLoc; }
3376
getLabel()3377 LabelDecl *getLabel() const { return Label; }
setLabel(LabelDecl * L)3378 void setLabel(LabelDecl *L) { Label = L; }
3379
classof(const Stmt * T)3380 static bool classof(const Stmt *T) {
3381 return T->getStmtClass() == AddrLabelExprClass;
3382 }
3383
3384 // Iterators
children()3385 child_range children() { return child_range(); }
3386 };
3387
3388 /// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
3389 /// The StmtExpr contains a single CompoundStmt node, which it evaluates and
3390 /// takes the value of the last subexpression.
3391 ///
3392 /// A StmtExpr is always an r-value; values "returned" out of a
3393 /// StmtExpr will be copied.
3394 class StmtExpr : public Expr {
3395 Stmt *SubStmt;
3396 SourceLocation LParenLoc, RParenLoc;
3397 public:
3398 // FIXME: Does type-dependence need to be computed differently?
3399 // FIXME: Do we need to compute instantiation instantiation-dependence for
3400 // statements? (ugh!)
StmtExpr(CompoundStmt * substmt,QualType T,SourceLocation lp,SourceLocation rp)3401 StmtExpr(CompoundStmt *substmt, QualType T,
3402 SourceLocation lp, SourceLocation rp) :
3403 Expr(StmtExprClass, T, VK_RValue, OK_Ordinary,
3404 T->isDependentType(), false, false, false),
3405 SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { }
3406
3407 /// \brief Build an empty statement expression.
StmtExpr(EmptyShell Empty)3408 explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
3409
getSubStmt()3410 CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
getSubStmt()3411 const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
setSubStmt(CompoundStmt * S)3412 void setSubStmt(CompoundStmt *S) { SubStmt = S; }
3413
getLocStart()3414 SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; }
getLocEnd()3415 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3416
getLParenLoc()3417 SourceLocation getLParenLoc() const { return LParenLoc; }
setLParenLoc(SourceLocation L)3418 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
getRParenLoc()3419 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)3420 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3421
classof(const Stmt * T)3422 static bool classof(const Stmt *T) {
3423 return T->getStmtClass() == StmtExprClass;
3424 }
3425
3426 // Iterators
children()3427 child_range children() { return child_range(&SubStmt, &SubStmt+1); }
3428 };
3429
3430
3431 /// ShuffleVectorExpr - clang-specific builtin-in function
3432 /// __builtin_shufflevector.
3433 /// This AST node represents a operator that does a constant
3434 /// shuffle, similar to LLVM's shufflevector instruction. It takes
3435 /// two vectors and a variable number of constant indices,
3436 /// and returns the appropriately shuffled vector.
3437 class ShuffleVectorExpr : public Expr {
3438 SourceLocation BuiltinLoc, RParenLoc;
3439
3440 // SubExprs - the list of values passed to the __builtin_shufflevector
3441 // function. The first two are vectors, and the rest are constant
3442 // indices. The number of values in this list is always
3443 // 2+the number of indices in the vector type.
3444 Stmt **SubExprs;
3445 unsigned NumExprs;
3446
3447 public:
3448 ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type,
3449 SourceLocation BLoc, SourceLocation RP);
3450
3451 /// \brief Build an empty vector-shuffle expression.
ShuffleVectorExpr(EmptyShell Empty)3452 explicit ShuffleVectorExpr(EmptyShell Empty)
3453 : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { }
3454
getBuiltinLoc()3455 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
setBuiltinLoc(SourceLocation L)3456 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3457
getRParenLoc()3458 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)3459 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3460
getLocStart()3461 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
getLocEnd()3462 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3463
classof(const Stmt * T)3464 static bool classof(const Stmt *T) {
3465 return T->getStmtClass() == ShuffleVectorExprClass;
3466 }
3467
3468 /// getNumSubExprs - Return the size of the SubExprs array. This includes the
3469 /// constant expression, the actual arguments passed in, and the function
3470 /// pointers.
getNumSubExprs()3471 unsigned getNumSubExprs() const { return NumExprs; }
3472
3473 /// \brief Retrieve the array of expressions.
getSubExprs()3474 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
3475
3476 /// getExpr - Return the Expr at the specified index.
getExpr(unsigned Index)3477 Expr *getExpr(unsigned Index) {
3478 assert((Index < NumExprs) && "Arg access out of range!");
3479 return cast<Expr>(SubExprs[Index]);
3480 }
getExpr(unsigned Index)3481 const Expr *getExpr(unsigned Index) const {
3482 assert((Index < NumExprs) && "Arg access out of range!");
3483 return cast<Expr>(SubExprs[Index]);
3484 }
3485
3486 void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs);
3487
getShuffleMaskIdx(const ASTContext & Ctx,unsigned N)3488 llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const {
3489 assert((N < NumExprs - 2) && "Shuffle idx out of range!");
3490 return getExpr(N+2)->EvaluateKnownConstInt(Ctx);
3491 }
3492
3493 // Iterators
children()3494 child_range children() {
3495 return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
3496 }
3497 };
3498
3499 /// ConvertVectorExpr - Clang builtin function __builtin_convertvector
3500 /// This AST node provides support for converting a vector type to another
3501 /// vector type of the same arity.
3502 class ConvertVectorExpr : public Expr {
3503 private:
3504 Stmt *SrcExpr;
3505 TypeSourceInfo *TInfo;
3506 SourceLocation BuiltinLoc, RParenLoc;
3507
3508 friend class ASTReader;
3509 friend class ASTStmtReader;
ConvertVectorExpr(EmptyShell Empty)3510 explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {}
3511
3512 public:
ConvertVectorExpr(Expr * SrcExpr,TypeSourceInfo * TI,QualType DstType,ExprValueKind VK,ExprObjectKind OK,SourceLocation BuiltinLoc,SourceLocation RParenLoc)3513 ConvertVectorExpr(Expr* SrcExpr, TypeSourceInfo *TI, QualType DstType,
3514 ExprValueKind VK, ExprObjectKind OK,
3515 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
3516 : Expr(ConvertVectorExprClass, DstType, VK, OK,
3517 DstType->isDependentType(),
3518 DstType->isDependentType() || SrcExpr->isValueDependent(),
3519 (DstType->isInstantiationDependentType() ||
3520 SrcExpr->isInstantiationDependent()),
3521 (DstType->containsUnexpandedParameterPack() ||
3522 SrcExpr->containsUnexpandedParameterPack())),
3523 SrcExpr(SrcExpr), TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
3524
3525 /// getSrcExpr - Return the Expr to be converted.
getSrcExpr()3526 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
3527
3528 /// getTypeSourceInfo - Return the destination type.
getTypeSourceInfo()3529 TypeSourceInfo *getTypeSourceInfo() const {
3530 return TInfo;
3531 }
setTypeSourceInfo(TypeSourceInfo * ti)3532 void setTypeSourceInfo(TypeSourceInfo *ti) {
3533 TInfo = ti;
3534 }
3535
3536 /// getBuiltinLoc - Return the location of the __builtin_convertvector token.
getBuiltinLoc()3537 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3538
3539 /// getRParenLoc - Return the location of final right parenthesis.
getRParenLoc()3540 SourceLocation getRParenLoc() const { return RParenLoc; }
3541
getLocStart()3542 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
getLocEnd()3543 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3544
classof(const Stmt * T)3545 static bool classof(const Stmt *T) {
3546 return T->getStmtClass() == ConvertVectorExprClass;
3547 }
3548
3549 // Iterators
children()3550 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
3551 };
3552
3553 /// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
3554 /// This AST node is similar to the conditional operator (?:) in C, with
3555 /// the following exceptions:
3556 /// - the test expression must be a integer constant expression.
3557 /// - the expression returned acts like the chosen subexpression in every
3558 /// visible way: the type is the same as that of the chosen subexpression,
3559 /// and all predicates (whether it's an l-value, whether it's an integer
3560 /// constant expression, etc.) return the same result as for the chosen
3561 /// sub-expression.
3562 class ChooseExpr : public Expr {
3563 enum { COND, LHS, RHS, END_EXPR };
3564 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3565 SourceLocation BuiltinLoc, RParenLoc;
3566 bool CondIsTrue;
3567 public:
ChooseExpr(SourceLocation BLoc,Expr * cond,Expr * lhs,Expr * rhs,QualType t,ExprValueKind VK,ExprObjectKind OK,SourceLocation RP,bool condIsTrue,bool TypeDependent,bool ValueDependent)3568 ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs,
3569 QualType t, ExprValueKind VK, ExprObjectKind OK,
3570 SourceLocation RP, bool condIsTrue,
3571 bool TypeDependent, bool ValueDependent)
3572 : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent,
3573 (cond->isInstantiationDependent() ||
3574 lhs->isInstantiationDependent() ||
3575 rhs->isInstantiationDependent()),
3576 (cond->containsUnexpandedParameterPack() ||
3577 lhs->containsUnexpandedParameterPack() ||
3578 rhs->containsUnexpandedParameterPack())),
3579 BuiltinLoc(BLoc), RParenLoc(RP), CondIsTrue(condIsTrue) {
3580 SubExprs[COND] = cond;
3581 SubExprs[LHS] = lhs;
3582 SubExprs[RHS] = rhs;
3583 }
3584
3585 /// \brief Build an empty __builtin_choose_expr.
ChooseExpr(EmptyShell Empty)3586 explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
3587
3588 /// isConditionTrue - Return whether the condition is true (i.e. not
3589 /// equal to zero).
isConditionTrue()3590 bool isConditionTrue() const {
3591 assert(!isConditionDependent() &&
3592 "Dependent condition isn't true or false");
3593 return CondIsTrue;
3594 }
setIsConditionTrue(bool isTrue)3595 void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; }
3596
isConditionDependent()3597 bool isConditionDependent() const {
3598 return getCond()->isTypeDependent() || getCond()->isValueDependent();
3599 }
3600
3601 /// getChosenSubExpr - Return the subexpression chosen according to the
3602 /// condition.
getChosenSubExpr()3603 Expr *getChosenSubExpr() const {
3604 return isConditionTrue() ? getLHS() : getRHS();
3605 }
3606
getCond()3607 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
setCond(Expr * E)3608 void setCond(Expr *E) { SubExprs[COND] = E; }
getLHS()3609 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
setLHS(Expr * E)3610 void setLHS(Expr *E) { SubExprs[LHS] = E; }
getRHS()3611 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
setRHS(Expr * E)3612 void setRHS(Expr *E) { SubExprs[RHS] = E; }
3613
getBuiltinLoc()3614 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
setBuiltinLoc(SourceLocation L)3615 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3616
getRParenLoc()3617 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)3618 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3619
getLocStart()3620 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
getLocEnd()3621 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3622
classof(const Stmt * T)3623 static bool classof(const Stmt *T) {
3624 return T->getStmtClass() == ChooseExprClass;
3625 }
3626
3627 // Iterators
children()3628 child_range children() {
3629 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3630 }
3631 };
3632
3633 /// GNUNullExpr - Implements the GNU __null extension, which is a name
3634 /// for a null pointer constant that has integral type (e.g., int or
3635 /// long) and is the same size and alignment as a pointer. The __null
3636 /// extension is typically only used by system headers, which define
3637 /// NULL as __null in C++ rather than using 0 (which is an integer
3638 /// that may not match the size of a pointer).
3639 class GNUNullExpr : public Expr {
3640 /// TokenLoc - The location of the __null keyword.
3641 SourceLocation TokenLoc;
3642
3643 public:
GNUNullExpr(QualType Ty,SourceLocation Loc)3644 GNUNullExpr(QualType Ty, SourceLocation Loc)
3645 : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false,
3646 false),
3647 TokenLoc(Loc) { }
3648
3649 /// \brief Build an empty GNU __null expression.
GNUNullExpr(EmptyShell Empty)3650 explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
3651
3652 /// getTokenLocation - The location of the __null token.
getTokenLocation()3653 SourceLocation getTokenLocation() const { return TokenLoc; }
setTokenLocation(SourceLocation L)3654 void setTokenLocation(SourceLocation L) { TokenLoc = L; }
3655
getLocStart()3656 SourceLocation getLocStart() const LLVM_READONLY { return TokenLoc; }
getLocEnd()3657 SourceLocation getLocEnd() const LLVM_READONLY { return TokenLoc; }
3658
classof(const Stmt * T)3659 static bool classof(const Stmt *T) {
3660 return T->getStmtClass() == GNUNullExprClass;
3661 }
3662
3663 // Iterators
children()3664 child_range children() { return child_range(); }
3665 };
3666
3667 /// VAArgExpr, used for the builtin function __builtin_va_arg.
3668 class VAArgExpr : public Expr {
3669 Stmt *Val;
3670 TypeSourceInfo *TInfo;
3671 SourceLocation BuiltinLoc, RParenLoc;
3672 public:
VAArgExpr(SourceLocation BLoc,Expr * e,TypeSourceInfo * TInfo,SourceLocation RPLoc,QualType t)3673 VAArgExpr(SourceLocation BLoc, Expr* e, TypeSourceInfo *TInfo,
3674 SourceLocation RPLoc, QualType t)
3675 : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary,
3676 t->isDependentType(), false,
3677 (TInfo->getType()->isInstantiationDependentType() ||
3678 e->isInstantiationDependent()),
3679 (TInfo->getType()->containsUnexpandedParameterPack() ||
3680 e->containsUnexpandedParameterPack())),
3681 Val(e), TInfo(TInfo),
3682 BuiltinLoc(BLoc),
3683 RParenLoc(RPLoc) { }
3684
3685 /// \brief Create an empty __builtin_va_arg expression.
VAArgExpr(EmptyShell Empty)3686 explicit VAArgExpr(EmptyShell Empty) : Expr(VAArgExprClass, Empty) { }
3687
getSubExpr()3688 const Expr *getSubExpr() const { return cast<Expr>(Val); }
getSubExpr()3689 Expr *getSubExpr() { return cast<Expr>(Val); }
setSubExpr(Expr * E)3690 void setSubExpr(Expr *E) { Val = E; }
3691
getWrittenTypeInfo()3692 TypeSourceInfo *getWrittenTypeInfo() const { return TInfo; }
setWrittenTypeInfo(TypeSourceInfo * TI)3693 void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo = TI; }
3694
getBuiltinLoc()3695 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
setBuiltinLoc(SourceLocation L)3696 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3697
getRParenLoc()3698 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)3699 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3700
getLocStart()3701 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
getLocEnd()3702 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3703
classof(const Stmt * T)3704 static bool classof(const Stmt *T) {
3705 return T->getStmtClass() == VAArgExprClass;
3706 }
3707
3708 // Iterators
children()3709 child_range children() { return child_range(&Val, &Val+1); }
3710 };
3711
3712 /// @brief Describes an C or C++ initializer list.
3713 ///
3714 /// InitListExpr describes an initializer list, which can be used to
3715 /// initialize objects of different types, including
3716 /// struct/class/union types, arrays, and vectors. For example:
3717 ///
3718 /// @code
3719 /// struct foo x = { 1, { 2, 3 } };
3720 /// @endcode
3721 ///
3722 /// Prior to semantic analysis, an initializer list will represent the
3723 /// initializer list as written by the user, but will have the
3724 /// placeholder type "void". This initializer list is called the
3725 /// syntactic form of the initializer, and may contain C99 designated
3726 /// initializers (represented as DesignatedInitExprs), initializations
3727 /// of subobject members without explicit braces, and so on. Clients
3728 /// interested in the original syntax of the initializer list should
3729 /// use the syntactic form of the initializer list.
3730 ///
3731 /// After semantic analysis, the initializer list will represent the
3732 /// semantic form of the initializer, where the initializations of all
3733 /// subobjects are made explicit with nested InitListExpr nodes and
3734 /// C99 designators have been eliminated by placing the designated
3735 /// initializations into the subobject they initialize. Additionally,
3736 /// any "holes" in the initialization, where no initializer has been
3737 /// specified for a particular subobject, will be replaced with
3738 /// implicitly-generated ImplicitValueInitExpr expressions that
3739 /// value-initialize the subobjects. Note, however, that the
3740 /// initializer lists may still have fewer initializers than there are
3741 /// elements to initialize within the object.
3742 ///
3743 /// After semantic analysis has completed, given an initializer list,
3744 /// method isSemanticForm() returns true if and only if this is the
3745 /// semantic form of the initializer list (note: the same AST node
3746 /// may at the same time be the syntactic form).
3747 /// Given the semantic form of the initializer list, one can retrieve
3748 /// the syntactic form of that initializer list (when different)
3749 /// using method getSyntacticForm(); the method returns null if applied
3750 /// to a initializer list which is already in syntactic form.
3751 /// Similarly, given the syntactic form (i.e., an initializer list such
3752 /// that isSemanticForm() returns false), one can retrieve the semantic
3753 /// form using method getSemanticForm().
3754 /// Since many initializer lists have the same syntactic and semantic forms,
3755 /// getSyntacticForm() may return NULL, indicating that the current
3756 /// semantic initializer list also serves as its syntactic form.
3757 class InitListExpr : public Expr {
3758 // FIXME: Eliminate this vector in favor of ASTContext allocation
3759 typedef ASTVector<Stmt *> InitExprsTy;
3760 InitExprsTy InitExprs;
3761 SourceLocation LBraceLoc, RBraceLoc;
3762
3763 /// The alternative form of the initializer list (if it exists).
3764 /// The int part of the pair stores whether this initializer list is
3765 /// in semantic form. If not null, the pointer points to:
3766 /// - the syntactic form, if this is in semantic form;
3767 /// - the semantic form, if this is in syntactic form.
3768 llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm;
3769
3770 /// \brief Either:
3771 /// If this initializer list initializes an array with more elements than
3772 /// there are initializers in the list, specifies an expression to be used
3773 /// for value initialization of the rest of the elements.
3774 /// Or
3775 /// If this initializer list initializes a union, specifies which
3776 /// field within the union will be initialized.
3777 llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
3778
3779 public:
3780 InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
3781 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc);
3782
3783 /// \brief Build an empty initializer list.
InitListExpr(EmptyShell Empty)3784 explicit InitListExpr(EmptyShell Empty)
3785 : Expr(InitListExprClass, Empty) { }
3786
getNumInits()3787 unsigned getNumInits() const { return InitExprs.size(); }
3788
3789 /// \brief Retrieve the set of initializers.
getInits()3790 Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
3791
getInit(unsigned Init)3792 const Expr *getInit(unsigned Init) const {
3793 assert(Init < getNumInits() && "Initializer access out of range!");
3794 return cast_or_null<Expr>(InitExprs[Init]);
3795 }
3796
getInit(unsigned Init)3797 Expr *getInit(unsigned Init) {
3798 assert(Init < getNumInits() && "Initializer access out of range!");
3799 return cast_or_null<Expr>(InitExprs[Init]);
3800 }
3801
setInit(unsigned Init,Expr * expr)3802 void setInit(unsigned Init, Expr *expr) {
3803 assert(Init < getNumInits() && "Initializer access out of range!");
3804 InitExprs[Init] = expr;
3805
3806 if (expr) {
3807 ExprBits.TypeDependent |= expr->isTypeDependent();
3808 ExprBits.ValueDependent |= expr->isValueDependent();
3809 ExprBits.InstantiationDependent |= expr->isInstantiationDependent();
3810 ExprBits.ContainsUnexpandedParameterPack |=
3811 expr->containsUnexpandedParameterPack();
3812 }
3813 }
3814
3815 /// \brief Reserve space for some number of initializers.
3816 void reserveInits(const ASTContext &C, unsigned NumInits);
3817
3818 /// @brief Specify the number of initializers
3819 ///
3820 /// If there are more than @p NumInits initializers, the remaining
3821 /// initializers will be destroyed. If there are fewer than @p
3822 /// NumInits initializers, NULL expressions will be added for the
3823 /// unknown initializers.
3824 void resizeInits(const ASTContext &Context, unsigned NumInits);
3825
3826 /// @brief Updates the initializer at index @p Init with the new
3827 /// expression @p expr, and returns the old expression at that
3828 /// location.
3829 ///
3830 /// When @p Init is out of range for this initializer list, the
3831 /// initializer list will be extended with NULL expressions to
3832 /// accommodate the new entry.
3833 Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr);
3834
3835 /// \brief If this initializer list initializes an array with more elements
3836 /// than there are initializers in the list, specifies an expression to be
3837 /// used for value initialization of the rest of the elements.
getArrayFiller()3838 Expr *getArrayFiller() {
3839 return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>();
3840 }
getArrayFiller()3841 const Expr *getArrayFiller() const {
3842 return const_cast<InitListExpr *>(this)->getArrayFiller();
3843 }
3844 void setArrayFiller(Expr *filler);
3845
3846 /// \brief Return true if this is an array initializer and its array "filler"
3847 /// has been set.
hasArrayFiller()3848 bool hasArrayFiller() const { return getArrayFiller(); }
3849
3850 /// \brief If this initializes a union, specifies which field in the
3851 /// union to initialize.
3852 ///
3853 /// Typically, this field is the first named field within the
3854 /// union. However, a designated initializer can specify the
3855 /// initialization of a different field within the union.
getInitializedFieldInUnion()3856 FieldDecl *getInitializedFieldInUnion() {
3857 return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>();
3858 }
getInitializedFieldInUnion()3859 const FieldDecl *getInitializedFieldInUnion() const {
3860 return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
3861 }
setInitializedFieldInUnion(FieldDecl * FD)3862 void setInitializedFieldInUnion(FieldDecl *FD) {
3863 assert((FD == nullptr
3864 || getInitializedFieldInUnion() == nullptr
3865 || getInitializedFieldInUnion() == FD)
3866 && "Only one field of a union may be initialized at a time!");
3867 ArrayFillerOrUnionFieldInit = FD;
3868 }
3869
3870 // Explicit InitListExpr's originate from source code (and have valid source
3871 // locations). Implicit InitListExpr's are created by the semantic analyzer.
isExplicit()3872 bool isExplicit() {
3873 return LBraceLoc.isValid() && RBraceLoc.isValid();
3874 }
3875
3876 // Is this an initializer for an array of characters, initialized by a string
3877 // literal or an @encode?
3878 bool isStringLiteralInit() const;
3879
getLBraceLoc()3880 SourceLocation getLBraceLoc() const { return LBraceLoc; }
setLBraceLoc(SourceLocation Loc)3881 void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
getRBraceLoc()3882 SourceLocation getRBraceLoc() const { return RBraceLoc; }
setRBraceLoc(SourceLocation Loc)3883 void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
3884
isSemanticForm()3885 bool isSemanticForm() const { return AltForm.getInt(); }
getSemanticForm()3886 InitListExpr *getSemanticForm() const {
3887 return isSemanticForm() ? nullptr : AltForm.getPointer();
3888 }
getSyntacticForm()3889 InitListExpr *getSyntacticForm() const {
3890 return isSemanticForm() ? AltForm.getPointer() : nullptr;
3891 }
3892
setSyntacticForm(InitListExpr * Init)3893 void setSyntacticForm(InitListExpr *Init) {
3894 AltForm.setPointer(Init);
3895 AltForm.setInt(true);
3896 Init->AltForm.setPointer(this);
3897 Init->AltForm.setInt(false);
3898 }
3899
hadArrayRangeDesignator()3900 bool hadArrayRangeDesignator() const {
3901 return InitListExprBits.HadArrayRangeDesignator != 0;
3902 }
3903 void sawArrayRangeDesignator(bool ARD = true) {
3904 InitListExprBits.HadArrayRangeDesignator = ARD;
3905 }
3906
3907 SourceLocation getLocStart() const LLVM_READONLY;
3908 SourceLocation getLocEnd() const LLVM_READONLY;
3909
classof(const Stmt * T)3910 static bool classof(const Stmt *T) {
3911 return T->getStmtClass() == InitListExprClass;
3912 }
3913
3914 // Iterators
children()3915 child_range children() {
3916 // FIXME: This does not include the array filler expression.
3917 if (InitExprs.empty()) return child_range();
3918 return child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
3919 }
3920
3921 typedef InitExprsTy::iterator iterator;
3922 typedef InitExprsTy::const_iterator const_iterator;
3923 typedef InitExprsTy::reverse_iterator reverse_iterator;
3924 typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
3925
begin()3926 iterator begin() { return InitExprs.begin(); }
begin()3927 const_iterator begin() const { return InitExprs.begin(); }
end()3928 iterator end() { return InitExprs.end(); }
end()3929 const_iterator end() const { return InitExprs.end(); }
rbegin()3930 reverse_iterator rbegin() { return InitExprs.rbegin(); }
rbegin()3931 const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
rend()3932 reverse_iterator rend() { return InitExprs.rend(); }
rend()3933 const_reverse_iterator rend() const { return InitExprs.rend(); }
3934
3935 friend class ASTStmtReader;
3936 friend class ASTStmtWriter;
3937 };
3938
3939 /// @brief Represents a C99 designated initializer expression.
3940 ///
3941 /// A designated initializer expression (C99 6.7.8) contains one or
3942 /// more designators (which can be field designators, array
3943 /// designators, or GNU array-range designators) followed by an
3944 /// expression that initializes the field or element(s) that the
3945 /// designators refer to. For example, given:
3946 ///
3947 /// @code
3948 /// struct point {
3949 /// double x;
3950 /// double y;
3951 /// };
3952 /// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
3953 /// @endcode
3954 ///
3955 /// The InitListExpr contains three DesignatedInitExprs, the first of
3956 /// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
3957 /// designators, one array designator for @c [2] followed by one field
3958 /// designator for @c .y. The initialization expression will be 1.0.
3959 class DesignatedInitExpr : public Expr {
3960 public:
3961 /// \brief Forward declaration of the Designator class.
3962 class Designator;
3963
3964 private:
3965 /// The location of the '=' or ':' prior to the actual initializer
3966 /// expression.
3967 SourceLocation EqualOrColonLoc;
3968
3969 /// Whether this designated initializer used the GNU deprecated
3970 /// syntax rather than the C99 '=' syntax.
3971 bool GNUSyntax : 1;
3972
3973 /// The number of designators in this initializer expression.
3974 unsigned NumDesignators : 15;
3975
3976 /// The number of subexpressions of this initializer expression,
3977 /// which contains both the initializer and any additional
3978 /// expressions used by array and array-range designators.
3979 unsigned NumSubExprs : 16;
3980
3981 /// \brief The designators in this designated initialization
3982 /// expression.
3983 Designator *Designators;
3984
3985
3986 DesignatedInitExpr(const ASTContext &C, QualType Ty, unsigned NumDesignators,
3987 const Designator *Designators,
3988 SourceLocation EqualOrColonLoc, bool GNUSyntax,
3989 ArrayRef<Expr*> IndexExprs, Expr *Init);
3990
DesignatedInitExpr(unsigned NumSubExprs)3991 explicit DesignatedInitExpr(unsigned NumSubExprs)
3992 : Expr(DesignatedInitExprClass, EmptyShell()),
3993 NumDesignators(0), NumSubExprs(NumSubExprs), Designators(nullptr) { }
3994
3995 public:
3996 /// A field designator, e.g., ".x".
3997 struct FieldDesignator {
3998 /// Refers to the field that is being initialized. The low bit
3999 /// of this field determines whether this is actually a pointer
4000 /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
4001 /// initially constructed, a field designator will store an
4002 /// IdentifierInfo*. After semantic analysis has resolved that
4003 /// name, the field designator will instead store a FieldDecl*.
4004 uintptr_t NameOrField;
4005
4006 /// The location of the '.' in the designated initializer.
4007 unsigned DotLoc;
4008
4009 /// The location of the field name in the designated initializer.
4010 unsigned FieldLoc;
4011 };
4012
4013 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
4014 struct ArrayOrRangeDesignator {
4015 /// Location of the first index expression within the designated
4016 /// initializer expression's list of subexpressions.
4017 unsigned Index;
4018 /// The location of the '[' starting the array range designator.
4019 unsigned LBracketLoc;
4020 /// The location of the ellipsis separating the start and end
4021 /// indices. Only valid for GNU array-range designators.
4022 unsigned EllipsisLoc;
4023 /// The location of the ']' terminating the array range designator.
4024 unsigned RBracketLoc;
4025 };
4026
4027 /// @brief Represents a single C99 designator.
4028 ///
4029 /// @todo This class is infuriatingly similar to clang::Designator,
4030 /// but minor differences (storing indices vs. storing pointers)
4031 /// keep us from reusing it. Try harder, later, to rectify these
4032 /// differences.
4033 class Designator {
4034 /// @brief The kind of designator this describes.
4035 enum {
4036 FieldDesignator,
4037 ArrayDesignator,
4038 ArrayRangeDesignator
4039 } Kind;
4040
4041 union {
4042 /// A field designator, e.g., ".x".
4043 struct FieldDesignator Field;
4044 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
4045 struct ArrayOrRangeDesignator ArrayOrRange;
4046 };
4047 friend class DesignatedInitExpr;
4048
4049 public:
Designator()4050 Designator() {}
4051
4052 /// @brief Initializes a field designator.
Designator(const IdentifierInfo * FieldName,SourceLocation DotLoc,SourceLocation FieldLoc)4053 Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
4054 SourceLocation FieldLoc)
4055 : Kind(FieldDesignator) {
4056 Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
4057 Field.DotLoc = DotLoc.getRawEncoding();
4058 Field.FieldLoc = FieldLoc.getRawEncoding();
4059 }
4060
4061 /// @brief Initializes an array designator.
Designator(unsigned Index,SourceLocation LBracketLoc,SourceLocation RBracketLoc)4062 Designator(unsigned Index, SourceLocation LBracketLoc,
4063 SourceLocation RBracketLoc)
4064 : Kind(ArrayDesignator) {
4065 ArrayOrRange.Index = Index;
4066 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4067 ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
4068 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4069 }
4070
4071 /// @brief Initializes a GNU array-range designator.
Designator(unsigned Index,SourceLocation LBracketLoc,SourceLocation EllipsisLoc,SourceLocation RBracketLoc)4072 Designator(unsigned Index, SourceLocation LBracketLoc,
4073 SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
4074 : Kind(ArrayRangeDesignator) {
4075 ArrayOrRange.Index = Index;
4076 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4077 ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
4078 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4079 }
4080
isFieldDesignator()4081 bool isFieldDesignator() const { return Kind == FieldDesignator; }
isArrayDesignator()4082 bool isArrayDesignator() const { return Kind == ArrayDesignator; }
isArrayRangeDesignator()4083 bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
4084
4085 IdentifierInfo *getFieldName() const;
4086
getField()4087 FieldDecl *getField() const {
4088 assert(Kind == FieldDesignator && "Only valid on a field designator");
4089 if (Field.NameOrField & 0x01)
4090 return nullptr;
4091 else
4092 return reinterpret_cast<FieldDecl *>(Field.NameOrField);
4093 }
4094
setField(FieldDecl * FD)4095 void setField(FieldDecl *FD) {
4096 assert(Kind == FieldDesignator && "Only valid on a field designator");
4097 Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
4098 }
4099
getDotLoc()4100 SourceLocation getDotLoc() const {
4101 assert(Kind == FieldDesignator && "Only valid on a field designator");
4102 return SourceLocation::getFromRawEncoding(Field.DotLoc);
4103 }
4104
getFieldLoc()4105 SourceLocation getFieldLoc() const {
4106 assert(Kind == FieldDesignator && "Only valid on a field designator");
4107 return SourceLocation::getFromRawEncoding(Field.FieldLoc);
4108 }
4109
getLBracketLoc()4110 SourceLocation getLBracketLoc() const {
4111 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4112 "Only valid on an array or array-range designator");
4113 return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
4114 }
4115
getRBracketLoc()4116 SourceLocation getRBracketLoc() const {
4117 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4118 "Only valid on an array or array-range designator");
4119 return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
4120 }
4121
getEllipsisLoc()4122 SourceLocation getEllipsisLoc() const {
4123 assert(Kind == ArrayRangeDesignator &&
4124 "Only valid on an array-range designator");
4125 return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
4126 }
4127
getFirstExprIndex()4128 unsigned getFirstExprIndex() const {
4129 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4130 "Only valid on an array or array-range designator");
4131 return ArrayOrRange.Index;
4132 }
4133
getLocStart()4134 SourceLocation getLocStart() const LLVM_READONLY {
4135 if (Kind == FieldDesignator)
4136 return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
4137 else
4138 return getLBracketLoc();
4139 }
getLocEnd()4140 SourceLocation getLocEnd() const LLVM_READONLY {
4141 return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc();
4142 }
getSourceRange()4143 SourceRange getSourceRange() const LLVM_READONLY {
4144 return SourceRange(getLocStart(), getLocEnd());
4145 }
4146 };
4147
4148 static DesignatedInitExpr *Create(const ASTContext &C,
4149 Designator *Designators,
4150 unsigned NumDesignators,
4151 ArrayRef<Expr*> IndexExprs,
4152 SourceLocation EqualOrColonLoc,
4153 bool GNUSyntax, Expr *Init);
4154
4155 static DesignatedInitExpr *CreateEmpty(const ASTContext &C,
4156 unsigned NumIndexExprs);
4157
4158 /// @brief Returns the number of designators in this initializer.
size()4159 unsigned size() const { return NumDesignators; }
4160
4161 // Iterator access to the designators.
4162 typedef Designator *designators_iterator;
designators_begin()4163 designators_iterator designators_begin() { return Designators; }
designators_end()4164 designators_iterator designators_end() {
4165 return Designators + NumDesignators;
4166 }
4167
4168 typedef const Designator *const_designators_iterator;
designators_begin()4169 const_designators_iterator designators_begin() const { return Designators; }
designators_end()4170 const_designators_iterator designators_end() const {
4171 return Designators + NumDesignators;
4172 }
4173
4174 typedef llvm::iterator_range<designators_iterator> designators_range;
designators()4175 designators_range designators() {
4176 return designators_range(designators_begin(), designators_end());
4177 }
4178
4179 typedef llvm::iterator_range<const_designators_iterator>
4180 designators_const_range;
designators()4181 designators_const_range designators() const {
4182 return designators_const_range(designators_begin(), designators_end());
4183 }
4184
4185 typedef std::reverse_iterator<designators_iterator>
4186 reverse_designators_iterator;
designators_rbegin()4187 reverse_designators_iterator designators_rbegin() {
4188 return reverse_designators_iterator(designators_end());
4189 }
designators_rend()4190 reverse_designators_iterator designators_rend() {
4191 return reverse_designators_iterator(designators_begin());
4192 }
4193
4194 typedef std::reverse_iterator<const_designators_iterator>
4195 const_reverse_designators_iterator;
designators_rbegin()4196 const_reverse_designators_iterator designators_rbegin() const {
4197 return const_reverse_designators_iterator(designators_end());
4198 }
designators_rend()4199 const_reverse_designators_iterator designators_rend() const {
4200 return const_reverse_designators_iterator(designators_begin());
4201 }
4202
getDesignator(unsigned Idx)4203 Designator *getDesignator(unsigned Idx) { return &designators_begin()[Idx]; }
4204
4205 void setDesignators(const ASTContext &C, const Designator *Desigs,
4206 unsigned NumDesigs);
4207
4208 Expr *getArrayIndex(const Designator &D) const;
4209 Expr *getArrayRangeStart(const Designator &D) const;
4210 Expr *getArrayRangeEnd(const Designator &D) const;
4211
4212 /// @brief Retrieve the location of the '=' that precedes the
4213 /// initializer value itself, if present.
getEqualOrColonLoc()4214 SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
setEqualOrColonLoc(SourceLocation L)4215 void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
4216
4217 /// @brief Determines whether this designated initializer used the
4218 /// deprecated GNU syntax for designated initializers.
usesGNUSyntax()4219 bool usesGNUSyntax() const { return GNUSyntax; }
setGNUSyntax(bool GNU)4220 void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
4221
4222 /// @brief Retrieve the initializer value.
getInit()4223 Expr *getInit() const {
4224 return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
4225 }
4226
setInit(Expr * init)4227 void setInit(Expr *init) {
4228 *child_begin() = init;
4229 }
4230
4231 /// \brief Retrieve the total number of subexpressions in this
4232 /// designated initializer expression, including the actual
4233 /// initialized value and any expressions that occur within array
4234 /// and array-range designators.
getNumSubExprs()4235 unsigned getNumSubExprs() const { return NumSubExprs; }
4236
getSubExpr(unsigned Idx)4237 Expr *getSubExpr(unsigned Idx) const {
4238 assert(Idx < NumSubExprs && "Subscript out of range");
4239 return cast<Expr>(reinterpret_cast<Stmt *const *>(this + 1)[Idx]);
4240 }
4241
setSubExpr(unsigned Idx,Expr * E)4242 void setSubExpr(unsigned Idx, Expr *E) {
4243 assert(Idx < NumSubExprs && "Subscript out of range");
4244 reinterpret_cast<Stmt **>(this + 1)[Idx] = E;
4245 }
4246
4247 /// \brief Replaces the designator at index @p Idx with the series
4248 /// of designators in [First, Last).
4249 void ExpandDesignator(const ASTContext &C, unsigned Idx,
4250 const Designator *First, const Designator *Last);
4251
4252 SourceRange getDesignatorsSourceRange() const;
4253
4254 SourceLocation getLocStart() const LLVM_READONLY;
4255 SourceLocation getLocEnd() const LLVM_READONLY;
4256
classof(const Stmt * T)4257 static bool classof(const Stmt *T) {
4258 return T->getStmtClass() == DesignatedInitExprClass;
4259 }
4260
4261 // Iterators
children()4262 child_range children() {
4263 Stmt **begin = reinterpret_cast<Stmt**>(this + 1);
4264 return child_range(begin, begin + NumSubExprs);
4265 }
4266 };
4267
4268 /// \brief Represents an implicitly-generated value initialization of
4269 /// an object of a given type.
4270 ///
4271 /// Implicit value initializations occur within semantic initializer
4272 /// list expressions (InitListExpr) as placeholders for subobject
4273 /// initializations not explicitly specified by the user.
4274 ///
4275 /// \see InitListExpr
4276 class ImplicitValueInitExpr : public Expr {
4277 public:
ImplicitValueInitExpr(QualType ty)4278 explicit ImplicitValueInitExpr(QualType ty)
4279 : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary,
4280 false, false, ty->isInstantiationDependentType(), false) { }
4281
4282 /// \brief Construct an empty implicit value initialization.
ImplicitValueInitExpr(EmptyShell Empty)4283 explicit ImplicitValueInitExpr(EmptyShell Empty)
4284 : Expr(ImplicitValueInitExprClass, Empty) { }
4285
classof(const Stmt * T)4286 static bool classof(const Stmt *T) {
4287 return T->getStmtClass() == ImplicitValueInitExprClass;
4288 }
4289
getLocStart()4290 SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
getLocEnd()4291 SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4292
4293 // Iterators
children()4294 child_range children() { return child_range(); }
4295 };
4296
4297
4298 class ParenListExpr : public Expr {
4299 Stmt **Exprs;
4300 unsigned NumExprs;
4301 SourceLocation LParenLoc, RParenLoc;
4302
4303 public:
4304 ParenListExpr(const ASTContext& C, SourceLocation lparenloc,
4305 ArrayRef<Expr*> exprs, SourceLocation rparenloc);
4306
4307 /// \brief Build an empty paren list.
ParenListExpr(EmptyShell Empty)4308 explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { }
4309
getNumExprs()4310 unsigned getNumExprs() const { return NumExprs; }
4311
getExpr(unsigned Init)4312 const Expr* getExpr(unsigned Init) const {
4313 assert(Init < getNumExprs() && "Initializer access out of range!");
4314 return cast_or_null<Expr>(Exprs[Init]);
4315 }
4316
getExpr(unsigned Init)4317 Expr* getExpr(unsigned Init) {
4318 assert(Init < getNumExprs() && "Initializer access out of range!");
4319 return cast_or_null<Expr>(Exprs[Init]);
4320 }
4321
getExprs()4322 Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); }
4323
getLParenLoc()4324 SourceLocation getLParenLoc() const { return LParenLoc; }
getRParenLoc()4325 SourceLocation getRParenLoc() const { return RParenLoc; }
4326
getLocStart()4327 SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; }
getLocEnd()4328 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4329
classof(const Stmt * T)4330 static bool classof(const Stmt *T) {
4331 return T->getStmtClass() == ParenListExprClass;
4332 }
4333
4334 // Iterators
children()4335 child_range children() {
4336 return child_range(&Exprs[0], &Exprs[0]+NumExprs);
4337 }
4338
4339 friend class ASTStmtReader;
4340 friend class ASTStmtWriter;
4341 };
4342
4343
4344 /// \brief Represents a C11 generic selection.
4345 ///
4346 /// A generic selection (C11 6.5.1.1) contains an unevaluated controlling
4347 /// expression, followed by one or more generic associations. Each generic
4348 /// association specifies a type name and an expression, or "default" and an
4349 /// expression (in which case it is known as a default generic association).
4350 /// The type and value of the generic selection are identical to those of its
4351 /// result expression, which is defined as the expression in the generic
4352 /// association with a type name that is compatible with the type of the
4353 /// controlling expression, or the expression in the default generic association
4354 /// if no types are compatible. For example:
4355 ///
4356 /// @code
4357 /// _Generic(X, double: 1, float: 2, default: 3)
4358 /// @endcode
4359 ///
4360 /// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f
4361 /// or 3 if "hello".
4362 ///
4363 /// As an extension, generic selections are allowed in C++, where the following
4364 /// additional semantics apply:
4365 ///
4366 /// Any generic selection whose controlling expression is type-dependent or
4367 /// which names a dependent type in its association list is result-dependent,
4368 /// which means that the choice of result expression is dependent.
4369 /// Result-dependent generic associations are both type- and value-dependent.
4370 class GenericSelectionExpr : public Expr {
4371 enum { CONTROLLING, END_EXPR };
4372 TypeSourceInfo **AssocTypes;
4373 Stmt **SubExprs;
4374 unsigned NumAssocs, ResultIndex;
4375 SourceLocation GenericLoc, DefaultLoc, RParenLoc;
4376
4377 public:
4378 GenericSelectionExpr(const ASTContext &Context,
4379 SourceLocation GenericLoc, Expr *ControllingExpr,
4380 ArrayRef<TypeSourceInfo*> AssocTypes,
4381 ArrayRef<Expr*> AssocExprs,
4382 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4383 bool ContainsUnexpandedParameterPack,
4384 unsigned ResultIndex);
4385
4386 /// This constructor is used in the result-dependent case.
4387 GenericSelectionExpr(const ASTContext &Context,
4388 SourceLocation GenericLoc, Expr *ControllingExpr,
4389 ArrayRef<TypeSourceInfo*> AssocTypes,
4390 ArrayRef<Expr*> AssocExprs,
4391 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4392 bool ContainsUnexpandedParameterPack);
4393
GenericSelectionExpr(EmptyShell Empty)4394 explicit GenericSelectionExpr(EmptyShell Empty)
4395 : Expr(GenericSelectionExprClass, Empty) { }
4396
getNumAssocs()4397 unsigned getNumAssocs() const { return NumAssocs; }
4398
getGenericLoc()4399 SourceLocation getGenericLoc() const { return GenericLoc; }
getDefaultLoc()4400 SourceLocation getDefaultLoc() const { return DefaultLoc; }
getRParenLoc()4401 SourceLocation getRParenLoc() const { return RParenLoc; }
4402
getAssocExpr(unsigned i)4403 const Expr *getAssocExpr(unsigned i) const {
4404 return cast<Expr>(SubExprs[END_EXPR+i]);
4405 }
getAssocExpr(unsigned i)4406 Expr *getAssocExpr(unsigned i) { return cast<Expr>(SubExprs[END_EXPR+i]); }
4407
getAssocTypeSourceInfo(unsigned i)4408 const TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) const {
4409 return AssocTypes[i];
4410 }
getAssocTypeSourceInfo(unsigned i)4411 TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) { return AssocTypes[i]; }
4412
getAssocType(unsigned i)4413 QualType getAssocType(unsigned i) const {
4414 if (const TypeSourceInfo *TS = getAssocTypeSourceInfo(i))
4415 return TS->getType();
4416 else
4417 return QualType();
4418 }
4419
getControllingExpr()4420 const Expr *getControllingExpr() const {
4421 return cast<Expr>(SubExprs[CONTROLLING]);
4422 }
getControllingExpr()4423 Expr *getControllingExpr() { return cast<Expr>(SubExprs[CONTROLLING]); }
4424
4425 /// Whether this generic selection is result-dependent.
isResultDependent()4426 bool isResultDependent() const { return ResultIndex == -1U; }
4427
4428 /// The zero-based index of the result expression's generic association in
4429 /// the generic selection's association list. Defined only if the
4430 /// generic selection is not result-dependent.
getResultIndex()4431 unsigned getResultIndex() const {
4432 assert(!isResultDependent() && "Generic selection is result-dependent");
4433 return ResultIndex;
4434 }
4435
4436 /// The generic selection's result expression. Defined only if the
4437 /// generic selection is not result-dependent.
getResultExpr()4438 const Expr *getResultExpr() const { return getAssocExpr(getResultIndex()); }
getResultExpr()4439 Expr *getResultExpr() { return getAssocExpr(getResultIndex()); }
4440
getLocStart()4441 SourceLocation getLocStart() const LLVM_READONLY { return GenericLoc; }
getLocEnd()4442 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4443
classof(const Stmt * T)4444 static bool classof(const Stmt *T) {
4445 return T->getStmtClass() == GenericSelectionExprClass;
4446 }
4447
children()4448 child_range children() {
4449 return child_range(SubExprs, SubExprs+END_EXPR+NumAssocs);
4450 }
4451
4452 friend class ASTStmtReader;
4453 };
4454
4455 //===----------------------------------------------------------------------===//
4456 // Clang Extensions
4457 //===----------------------------------------------------------------------===//
4458
4459
4460 /// ExtVectorElementExpr - This represents access to specific elements of a
4461 /// vector, and may occur on the left hand side or right hand side. For example
4462 /// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector.
4463 ///
4464 /// Note that the base may have either vector or pointer to vector type, just
4465 /// like a struct field reference.
4466 ///
4467 class ExtVectorElementExpr : public Expr {
4468 Stmt *Base;
4469 IdentifierInfo *Accessor;
4470 SourceLocation AccessorLoc;
4471 public:
ExtVectorElementExpr(QualType ty,ExprValueKind VK,Expr * base,IdentifierInfo & accessor,SourceLocation loc)4472 ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base,
4473 IdentifierInfo &accessor, SourceLocation loc)
4474 : Expr(ExtVectorElementExprClass, ty, VK,
4475 (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent),
4476 base->isTypeDependent(), base->isValueDependent(),
4477 base->isInstantiationDependent(),
4478 base->containsUnexpandedParameterPack()),
4479 Base(base), Accessor(&accessor), AccessorLoc(loc) {}
4480
4481 /// \brief Build an empty vector element expression.
ExtVectorElementExpr(EmptyShell Empty)4482 explicit ExtVectorElementExpr(EmptyShell Empty)
4483 : Expr(ExtVectorElementExprClass, Empty) { }
4484
getBase()4485 const Expr *getBase() const { return cast<Expr>(Base); }
getBase()4486 Expr *getBase() { return cast<Expr>(Base); }
setBase(Expr * E)4487 void setBase(Expr *E) { Base = E; }
4488
getAccessor()4489 IdentifierInfo &getAccessor() const { return *Accessor; }
setAccessor(IdentifierInfo * II)4490 void setAccessor(IdentifierInfo *II) { Accessor = II; }
4491
getAccessorLoc()4492 SourceLocation getAccessorLoc() const { return AccessorLoc; }
setAccessorLoc(SourceLocation L)4493 void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
4494
4495 /// getNumElements - Get the number of components being selected.
4496 unsigned getNumElements() const;
4497
4498 /// containsDuplicateElements - Return true if any element access is
4499 /// repeated.
4500 bool containsDuplicateElements() const;
4501
4502 /// getEncodedElementAccess - Encode the elements accessed into an llvm
4503 /// aggregate Constant of ConstantInt(s).
4504 void getEncodedElementAccess(SmallVectorImpl<unsigned> &Elts) const;
4505
getLocStart()4506 SourceLocation getLocStart() const LLVM_READONLY {
4507 return getBase()->getLocStart();
4508 }
getLocEnd()4509 SourceLocation getLocEnd() const LLVM_READONLY { return AccessorLoc; }
4510
4511 /// isArrow - Return true if the base expression is a pointer to vector,
4512 /// return false if the base expression is a vector.
4513 bool isArrow() const;
4514
classof(const Stmt * T)4515 static bool classof(const Stmt *T) {
4516 return T->getStmtClass() == ExtVectorElementExprClass;
4517 }
4518
4519 // Iterators
children()4520 child_range children() { return child_range(&Base, &Base+1); }
4521 };
4522
4523
4524 /// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
4525 /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
4526 class BlockExpr : public Expr {
4527 protected:
4528 BlockDecl *TheBlock;
4529 public:
BlockExpr(BlockDecl * BD,QualType ty)4530 BlockExpr(BlockDecl *BD, QualType ty)
4531 : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary,
4532 ty->isDependentType(), ty->isDependentType(),
4533 ty->isInstantiationDependentType() || BD->isDependentContext(),
4534 false),
4535 TheBlock(BD) {}
4536
4537 /// \brief Build an empty block expression.
BlockExpr(EmptyShell Empty)4538 explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
4539
getBlockDecl()4540 const BlockDecl *getBlockDecl() const { return TheBlock; }
getBlockDecl()4541 BlockDecl *getBlockDecl() { return TheBlock; }
setBlockDecl(BlockDecl * BD)4542 void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
4543
4544 // Convenience functions for probing the underlying BlockDecl.
4545 SourceLocation getCaretLocation() const;
4546 const Stmt *getBody() const;
4547 Stmt *getBody();
4548
getLocStart()4549 SourceLocation getLocStart() const LLVM_READONLY { return getCaretLocation(); }
getLocEnd()4550 SourceLocation getLocEnd() const LLVM_READONLY { return getBody()->getLocEnd(); }
4551
4552 /// getFunctionType - Return the underlying function type for this block.
4553 const FunctionProtoType *getFunctionType() const;
4554
classof(const Stmt * T)4555 static bool classof(const Stmt *T) {
4556 return T->getStmtClass() == BlockExprClass;
4557 }
4558
4559 // Iterators
children()4560 child_range children() { return child_range(); }
4561 };
4562
4563 /// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2]
4564 /// This AST node provides support for reinterpreting a type to another
4565 /// type of the same size.
4566 class AsTypeExpr : public Expr {
4567 private:
4568 Stmt *SrcExpr;
4569 SourceLocation BuiltinLoc, RParenLoc;
4570
4571 friend class ASTReader;
4572 friend class ASTStmtReader;
AsTypeExpr(EmptyShell Empty)4573 explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {}
4574
4575 public:
AsTypeExpr(Expr * SrcExpr,QualType DstType,ExprValueKind VK,ExprObjectKind OK,SourceLocation BuiltinLoc,SourceLocation RParenLoc)4576 AsTypeExpr(Expr* SrcExpr, QualType DstType,
4577 ExprValueKind VK, ExprObjectKind OK,
4578 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
4579 : Expr(AsTypeExprClass, DstType, VK, OK,
4580 DstType->isDependentType(),
4581 DstType->isDependentType() || SrcExpr->isValueDependent(),
4582 (DstType->isInstantiationDependentType() ||
4583 SrcExpr->isInstantiationDependent()),
4584 (DstType->containsUnexpandedParameterPack() ||
4585 SrcExpr->containsUnexpandedParameterPack())),
4586 SrcExpr(SrcExpr), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
4587
4588 /// getSrcExpr - Return the Expr to be converted.
getSrcExpr()4589 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
4590
4591 /// getBuiltinLoc - Return the location of the __builtin_astype token.
getBuiltinLoc()4592 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4593
4594 /// getRParenLoc - Return the location of final right parenthesis.
getRParenLoc()4595 SourceLocation getRParenLoc() const { return RParenLoc; }
4596
getLocStart()4597 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
getLocEnd()4598 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4599
classof(const Stmt * T)4600 static bool classof(const Stmt *T) {
4601 return T->getStmtClass() == AsTypeExprClass;
4602 }
4603
4604 // Iterators
children()4605 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
4606 };
4607
4608 /// PseudoObjectExpr - An expression which accesses a pseudo-object
4609 /// l-value. A pseudo-object is an abstract object, accesses to which
4610 /// are translated to calls. The pseudo-object expression has a
4611 /// syntactic form, which shows how the expression was actually
4612 /// written in the source code, and a semantic form, which is a series
4613 /// of expressions to be executed in order which detail how the
4614 /// operation is actually evaluated. Optionally, one of the semantic
4615 /// forms may also provide a result value for the expression.
4616 ///
4617 /// If any of the semantic-form expressions is an OpaqueValueExpr,
4618 /// that OVE is required to have a source expression, and it is bound
4619 /// to the result of that source expression. Such OVEs may appear
4620 /// only in subsequent semantic-form expressions and as
4621 /// sub-expressions of the syntactic form.
4622 ///
4623 /// PseudoObjectExpr should be used only when an operation can be
4624 /// usefully described in terms of fairly simple rewrite rules on
4625 /// objects and functions that are meant to be used by end-developers.
4626 /// For example, under the Itanium ABI, dynamic casts are implemented
4627 /// as a call to a runtime function called __dynamic_cast; using this
4628 /// class to describe that would be inappropriate because that call is
4629 /// not really part of the user-visible semantics, and instead the
4630 /// cast is properly reflected in the AST and IR-generation has been
4631 /// taught to generate the call as necessary. In contrast, an
4632 /// Objective-C property access is semantically defined to be
4633 /// equivalent to a particular message send, and this is very much
4634 /// part of the user model. The name of this class encourages this
4635 /// modelling design.
4636 class PseudoObjectExpr : public Expr {
4637 // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions.
4638 // Always at least two, because the first sub-expression is the
4639 // syntactic form.
4640
4641 // PseudoObjectExprBits.ResultIndex - The index of the
4642 // sub-expression holding the result. 0 means the result is void,
4643 // which is unambiguous because it's the index of the syntactic
4644 // form. Note that this is therefore 1 higher than the value passed
4645 // in to Create, which is an index within the semantic forms.
4646 // Note also that ASTStmtWriter assumes this encoding.
4647
getSubExprsBuffer()4648 Expr **getSubExprsBuffer() { return reinterpret_cast<Expr**>(this + 1); }
getSubExprsBuffer()4649 const Expr * const *getSubExprsBuffer() const {
4650 return reinterpret_cast<const Expr * const *>(this + 1);
4651 }
4652
4653 friend class ASTStmtReader;
4654
4655 PseudoObjectExpr(QualType type, ExprValueKind VK,
4656 Expr *syntactic, ArrayRef<Expr*> semantic,
4657 unsigned resultIndex);
4658
4659 PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs);
4660
getNumSubExprs()4661 unsigned getNumSubExprs() const {
4662 return PseudoObjectExprBits.NumSubExprs;
4663 }
4664
4665 public:
4666 /// NoResult - A value for the result index indicating that there is
4667 /// no semantic result.
4668 enum : unsigned { NoResult = ~0U };
4669
4670 static PseudoObjectExpr *Create(const ASTContext &Context, Expr *syntactic,
4671 ArrayRef<Expr*> semantic,
4672 unsigned resultIndex);
4673
4674 static PseudoObjectExpr *Create(const ASTContext &Context, EmptyShell shell,
4675 unsigned numSemanticExprs);
4676
4677 /// Return the syntactic form of this expression, i.e. the
4678 /// expression it actually looks like. Likely to be expressed in
4679 /// terms of OpaqueValueExprs bound in the semantic form.
getSyntacticForm()4680 Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; }
getSyntacticForm()4681 const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; }
4682
4683 /// Return the index of the result-bearing expression into the semantics
4684 /// expressions, or PseudoObjectExpr::NoResult if there is none.
getResultExprIndex()4685 unsigned getResultExprIndex() const {
4686 if (PseudoObjectExprBits.ResultIndex == 0) return NoResult;
4687 return PseudoObjectExprBits.ResultIndex - 1;
4688 }
4689
4690 /// Return the result-bearing expression, or null if there is none.
getResultExpr()4691 Expr *getResultExpr() {
4692 if (PseudoObjectExprBits.ResultIndex == 0)
4693 return nullptr;
4694 return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex];
4695 }
getResultExpr()4696 const Expr *getResultExpr() const {
4697 return const_cast<PseudoObjectExpr*>(this)->getResultExpr();
4698 }
4699
getNumSemanticExprs()4700 unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; }
4701
4702 typedef Expr * const *semantics_iterator;
4703 typedef const Expr * const *const_semantics_iterator;
semantics_begin()4704 semantics_iterator semantics_begin() {
4705 return getSubExprsBuffer() + 1;
4706 }
semantics_begin()4707 const_semantics_iterator semantics_begin() const {
4708 return getSubExprsBuffer() + 1;
4709 }
semantics_end()4710 semantics_iterator semantics_end() {
4711 return getSubExprsBuffer() + getNumSubExprs();
4712 }
semantics_end()4713 const_semantics_iterator semantics_end() const {
4714 return getSubExprsBuffer() + getNumSubExprs();
4715 }
getSemanticExpr(unsigned index)4716 Expr *getSemanticExpr(unsigned index) {
4717 assert(index + 1 < getNumSubExprs());
4718 return getSubExprsBuffer()[index + 1];
4719 }
getSemanticExpr(unsigned index)4720 const Expr *getSemanticExpr(unsigned index) const {
4721 return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index);
4722 }
4723
getExprLoc()4724 SourceLocation getExprLoc() const LLVM_READONLY {
4725 return getSyntacticForm()->getExprLoc();
4726 }
4727
getLocStart()4728 SourceLocation getLocStart() const LLVM_READONLY {
4729 return getSyntacticForm()->getLocStart();
4730 }
getLocEnd()4731 SourceLocation getLocEnd() const LLVM_READONLY {
4732 return getSyntacticForm()->getLocEnd();
4733 }
4734
children()4735 child_range children() {
4736 Stmt **cs = reinterpret_cast<Stmt**>(getSubExprsBuffer());
4737 return child_range(cs, cs + getNumSubExprs());
4738 }
4739
classof(const Stmt * T)4740 static bool classof(const Stmt *T) {
4741 return T->getStmtClass() == PseudoObjectExprClass;
4742 }
4743 };
4744
4745 /// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*,
4746 /// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the
4747 /// similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>.
4748 /// All of these instructions take one primary pointer and at least one memory
4749 /// order.
4750 class AtomicExpr : public Expr {
4751 public:
4752 enum AtomicOp {
4753 #define BUILTIN(ID, TYPE, ATTRS)
4754 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID,
4755 #include "clang/Basic/Builtins.def"
4756 // Avoid trailing comma
4757 BI_First = 0
4758 };
4759
4760 // The ABI values for various atomic memory orderings.
4761 enum AtomicOrderingKind {
4762 AO_ABI_memory_order_relaxed = 0,
4763 AO_ABI_memory_order_consume = 1,
4764 AO_ABI_memory_order_acquire = 2,
4765 AO_ABI_memory_order_release = 3,
4766 AO_ABI_memory_order_acq_rel = 4,
4767 AO_ABI_memory_order_seq_cst = 5
4768 };
4769
4770 private:
4771 enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR };
4772 Stmt* SubExprs[END_EXPR];
4773 unsigned NumSubExprs;
4774 SourceLocation BuiltinLoc, RParenLoc;
4775 AtomicOp Op;
4776
4777 friend class ASTStmtReader;
4778
4779 public:
4780 AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, QualType t,
4781 AtomicOp op, SourceLocation RP);
4782
4783 /// \brief Determine the number of arguments the specified atomic builtin
4784 /// should have.
4785 static unsigned getNumSubExprs(AtomicOp Op);
4786
4787 /// \brief Build an empty AtomicExpr.
AtomicExpr(EmptyShell Empty)4788 explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { }
4789
getPtr()4790 Expr *getPtr() const {
4791 return cast<Expr>(SubExprs[PTR]);
4792 }
getOrder()4793 Expr *getOrder() const {
4794 return cast<Expr>(SubExprs[ORDER]);
4795 }
getVal1()4796 Expr *getVal1() const {
4797 if (Op == AO__c11_atomic_init)
4798 return cast<Expr>(SubExprs[ORDER]);
4799 assert(NumSubExprs > VAL1);
4800 return cast<Expr>(SubExprs[VAL1]);
4801 }
getOrderFail()4802 Expr *getOrderFail() const {
4803 assert(NumSubExprs > ORDER_FAIL);
4804 return cast<Expr>(SubExprs[ORDER_FAIL]);
4805 }
getVal2()4806 Expr *getVal2() const {
4807 if (Op == AO__atomic_exchange)
4808 return cast<Expr>(SubExprs[ORDER_FAIL]);
4809 assert(NumSubExprs > VAL2);
4810 return cast<Expr>(SubExprs[VAL2]);
4811 }
getWeak()4812 Expr *getWeak() const {
4813 assert(NumSubExprs > WEAK);
4814 return cast<Expr>(SubExprs[WEAK]);
4815 }
4816
getOp()4817 AtomicOp getOp() const { return Op; }
getNumSubExprs()4818 unsigned getNumSubExprs() { return NumSubExprs; }
4819
getSubExprs()4820 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
4821
isVolatile()4822 bool isVolatile() const {
4823 return getPtr()->getType()->getPointeeType().isVolatileQualified();
4824 }
4825
isCmpXChg()4826 bool isCmpXChg() const {
4827 return getOp() == AO__c11_atomic_compare_exchange_strong ||
4828 getOp() == AO__c11_atomic_compare_exchange_weak ||
4829 getOp() == AO__atomic_compare_exchange ||
4830 getOp() == AO__atomic_compare_exchange_n;
4831 }
4832
getBuiltinLoc()4833 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
getRParenLoc()4834 SourceLocation getRParenLoc() const { return RParenLoc; }
4835
getLocStart()4836 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
getLocEnd()4837 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4838
classof(const Stmt * T)4839 static bool classof(const Stmt *T) {
4840 return T->getStmtClass() == AtomicExprClass;
4841 }
4842
4843 // Iterators
children()4844 child_range children() {
4845 return child_range(SubExprs, SubExprs+NumSubExprs);
4846 }
4847 };
4848
4849 /// TypoExpr - Internal placeholder for expressions where typo correction
4850 /// still needs to be performed and/or an error diagnostic emitted.
4851 class TypoExpr : public Expr {
4852 public:
TypoExpr(QualType T)4853 TypoExpr(QualType T)
4854 : Expr(TypoExprClass, T, VK_LValue, OK_Ordinary,
4855 /*isTypeDependent*/ true,
4856 /*isValueDependent*/ true,
4857 /*isInstantiationDependent*/ true,
4858 /*containsUnexpandedParameterPack*/ false) {
4859 assert(T->isDependentType() && "TypoExpr given a non-dependent type");
4860 }
4861
children()4862 child_range children() { return child_range(); }
getLocStart()4863 SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
getLocEnd()4864 SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4865 };
4866 } // end namespace clang
4867
4868 #endif
4869