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