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