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