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