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