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