1 //===- Stmt.h - Classes for representing statements -------------*- 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 Stmt interface and subclasses.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_CLANG_AST_STMT_H
14 #define LLVM_CLANG_AST_STMT_H
15 
16 #include "clang/AST/DeclGroup.h"
17 #include "clang/AST/DependenceFlags.h"
18 #include "clang/AST/StmtIterator.h"
19 #include "clang/Basic/CapturedStmt.h"
20 #include "clang/Basic/IdentifierTable.h"
21 #include "clang/Basic/LLVM.h"
22 #include "clang/Basic/SourceLocation.h"
23 #include "llvm/ADT/ArrayRef.h"
24 #include "llvm/ADT/BitmaskEnum.h"
25 #include "llvm/ADT/PointerIntPair.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/iterator.h"
28 #include "llvm/ADT/iterator_range.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/Compiler.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include <algorithm>
33 #include <cassert>
34 #include <cstddef>
35 #include <iterator>
36 #include <string>
37 
38 namespace llvm {
39 
40 class FoldingSetNodeID;
41 
42 } // namespace llvm
43 
44 namespace clang {
45 
46 class ASTContext;
47 class Attr;
48 class CapturedDecl;
49 class Decl;
50 class Expr;
51 class AddrLabelExpr;
52 class LabelDecl;
53 class ODRHash;
54 class PrinterHelper;
55 struct PrintingPolicy;
56 class RecordDecl;
57 class SourceManager;
58 class StringLiteral;
59 class Token;
60 class VarDecl;
61 
62 //===----------------------------------------------------------------------===//
63 // AST classes for statements.
64 //===----------------------------------------------------------------------===//
65 
66 /// Stmt - This represents one statement.
67 ///
alignas(void *)68 class alignas(void *) Stmt {
69 public:
70   enum StmtClass {
71     NoStmtClass = 0,
72 #define STMT(CLASS, PARENT) CLASS##Class,
73 #define STMT_RANGE(BASE, FIRST, LAST) \
74         first##BASE##Constant=FIRST##Class, last##BASE##Constant=LAST##Class,
75 #define LAST_STMT_RANGE(BASE, FIRST, LAST) \
76         first##BASE##Constant=FIRST##Class, last##BASE##Constant=LAST##Class
77 #define ABSTRACT_STMT(STMT)
78 #include "clang/AST/StmtNodes.inc"
79   };
80 
81   // Make vanilla 'new' and 'delete' illegal for Stmts.
82 protected:
83   friend class ASTStmtReader;
84   friend class ASTStmtWriter;
85 
86   void *operator new(size_t bytes) noexcept {
87     llvm_unreachable("Stmts cannot be allocated with regular 'new'.");
88   }
89 
90   void operator delete(void *data) noexcept {
91     llvm_unreachable("Stmts cannot be released with regular 'delete'.");
92   }
93 
94   //===--- Statement bitfields classes ---===//
95 
96   class StmtBitfields {
97     friend class ASTStmtReader;
98     friend class ASTStmtWriter;
99     friend class Stmt;
100 
101     /// The statement class.
102     unsigned sClass : 8;
103   };
104   enum { NumStmtBits = 8 };
105 
106   class NullStmtBitfields {
107     friend class ASTStmtReader;
108     friend class ASTStmtWriter;
109     friend class NullStmt;
110 
111     unsigned : NumStmtBits;
112 
113     /// True if the null statement was preceded by an empty macro, e.g:
114     /// @code
115     ///   #define CALL(x)
116     ///   CALL(0);
117     /// @endcode
118     unsigned HasLeadingEmptyMacro : 1;
119 
120     /// The location of the semi-colon.
121     SourceLocation SemiLoc;
122   };
123 
124   class CompoundStmtBitfields {
125     friend class ASTStmtReader;
126     friend class CompoundStmt;
127 
128     unsigned : NumStmtBits;
129 
130     unsigned NumStmts : 32 - NumStmtBits;
131 
132     /// The location of the opening "{".
133     SourceLocation LBraceLoc;
134   };
135 
136   class LabelStmtBitfields {
137     friend class LabelStmt;
138 
139     unsigned : NumStmtBits;
140 
141     SourceLocation IdentLoc;
142   };
143 
144   class AttributedStmtBitfields {
145     friend class ASTStmtReader;
146     friend class AttributedStmt;
147 
148     unsigned : NumStmtBits;
149 
150     /// Number of attributes.
151     unsigned NumAttrs : 32 - NumStmtBits;
152 
153     /// The location of the attribute.
154     SourceLocation AttrLoc;
155   };
156 
157   class IfStmtBitfields {
158     friend class ASTStmtReader;
159     friend class IfStmt;
160 
161     unsigned : NumStmtBits;
162 
163     /// True if this if statement is a constexpr if.
164     unsigned IsConstexpr : 1;
165 
166     /// True if this if statement has storage for an else statement.
167     unsigned HasElse : 1;
168 
169     /// True if this if statement has storage for a variable declaration.
170     unsigned HasVar : 1;
171 
172     /// True if this if statement has storage for an init statement.
173     unsigned HasInit : 1;
174 
175     /// The location of the "if".
176     SourceLocation IfLoc;
177   };
178 
179   class SwitchStmtBitfields {
180     friend class SwitchStmt;
181 
182     unsigned : NumStmtBits;
183 
184     /// True if the SwitchStmt has storage for an init statement.
185     unsigned HasInit : 1;
186 
187     /// True if the SwitchStmt has storage for a condition variable.
188     unsigned HasVar : 1;
189 
190     /// If the SwitchStmt is a switch on an enum value, records whether all
191     /// the enum values were covered by CaseStmts.  The coverage information
192     /// value is meant to be a hint for possible clients.
193     unsigned AllEnumCasesCovered : 1;
194 
195     /// The location of the "switch".
196     SourceLocation SwitchLoc;
197   };
198 
199   class WhileStmtBitfields {
200     friend class ASTStmtReader;
201     friend class WhileStmt;
202 
203     unsigned : NumStmtBits;
204 
205     /// True if the WhileStmt has storage for a condition variable.
206     unsigned HasVar : 1;
207 
208     /// The location of the "while".
209     SourceLocation WhileLoc;
210   };
211 
212   class DoStmtBitfields {
213     friend class DoStmt;
214 
215     unsigned : NumStmtBits;
216 
217     /// The location of the "do".
218     SourceLocation DoLoc;
219   };
220 
221   class ForStmtBitfields {
222     friend class ForStmt;
223 
224     unsigned : NumStmtBits;
225 
226     /// The location of the "for".
227     SourceLocation ForLoc;
228   };
229 
230   class GotoStmtBitfields {
231     friend class GotoStmt;
232     friend class IndirectGotoStmt;
233 
234     unsigned : NumStmtBits;
235 
236     /// The location of the "goto".
237     SourceLocation GotoLoc;
238   };
239 
240   class ContinueStmtBitfields {
241     friend class ContinueStmt;
242 
243     unsigned : NumStmtBits;
244 
245     /// The location of the "continue".
246     SourceLocation ContinueLoc;
247   };
248 
249   class BreakStmtBitfields {
250     friend class BreakStmt;
251 
252     unsigned : NumStmtBits;
253 
254     /// The location of the "break".
255     SourceLocation BreakLoc;
256   };
257 
258   class ReturnStmtBitfields {
259     friend class ReturnStmt;
260 
261     unsigned : NumStmtBits;
262 
263     /// True if this ReturnStmt has storage for an NRVO candidate.
264     unsigned HasNRVOCandidate : 1;
265 
266     /// The location of the "return".
267     SourceLocation RetLoc;
268   };
269 
270   class SwitchCaseBitfields {
271     friend class SwitchCase;
272     friend class CaseStmt;
273 
274     unsigned : NumStmtBits;
275 
276     /// Used by CaseStmt to store whether it is a case statement
277     /// of the form case LHS ... RHS (a GNU extension).
278     unsigned CaseStmtIsGNURange : 1;
279 
280     /// The location of the "case" or "default" keyword.
281     SourceLocation KeywordLoc;
282   };
283 
284   //===--- Expression bitfields classes ---===//
285 
286   class ExprBitfields {
287     friend class ASTStmtReader; // deserialization
288     friend class AtomicExpr; // ctor
289     friend class BlockDeclRefExpr; // ctor
290     friend class CallExpr; // ctor
291     friend class CXXConstructExpr; // ctor
292     friend class CXXDependentScopeMemberExpr; // ctor
293     friend class CXXNewExpr; // ctor
294     friend class CXXUnresolvedConstructExpr; // ctor
295     friend class DeclRefExpr; // computeDependence
296     friend class DependentScopeDeclRefExpr; // ctor
297     friend class DesignatedInitExpr; // ctor
298     friend class Expr;
299     friend class InitListExpr; // ctor
300     friend class ObjCArrayLiteral; // ctor
301     friend class ObjCDictionaryLiteral; // ctor
302     friend class ObjCMessageExpr; // ctor
303     friend class OffsetOfExpr; // ctor
304     friend class OpaqueValueExpr; // ctor
305     friend class OverloadExpr; // ctor
306     friend class ParenListExpr; // ctor
307     friend class PseudoObjectExpr; // ctor
308     friend class ShuffleVectorExpr; // ctor
309 
310     unsigned : NumStmtBits;
311 
312     unsigned ValueKind : 2;
313     unsigned ObjectKind : 3;
314     unsigned /*ExprDependence*/ Dependent : llvm::BitWidth<ExprDependence>;
315   };
316   enum { NumExprBits = NumStmtBits + 5 + llvm::BitWidth<ExprDependence> };
317 
318   class ConstantExprBitfields {
319     friend class ASTStmtReader;
320     friend class ASTStmtWriter;
321     friend class ConstantExpr;
322 
323     unsigned : NumExprBits;
324 
325     /// The kind of result that is tail-allocated.
326     unsigned ResultKind : 2;
327 
328     /// The kind of Result as defined by APValue::Kind.
329     unsigned APValueKind : 4;
330 
331     /// When ResultKind == RSK_Int64, true if the tail-allocated integer is
332     /// unsigned.
333     unsigned IsUnsigned : 1;
334 
335     /// When ResultKind == RSK_Int64. the BitWidth of the tail-allocated
336     /// integer. 7 bits because it is the minimal number of bits to represent a
337     /// value from 0 to 64 (the size of the tail-allocated integer).
338     unsigned BitWidth : 7;
339 
340     /// When ResultKind == RSK_APValue, true if the ASTContext will cleanup the
341     /// tail-allocated APValue.
342     unsigned HasCleanup : 1;
343 
344     /// True if this ConstantExpr was created for immediate invocation.
345     unsigned IsImmediateInvocation : 1;
346   };
347 
348   class PredefinedExprBitfields {
349     friend class ASTStmtReader;
350     friend class PredefinedExpr;
351 
352     unsigned : NumExprBits;
353 
354     /// The kind of this PredefinedExpr. One of the enumeration values
355     /// in PredefinedExpr::IdentKind.
356     unsigned Kind : 4;
357 
358     /// True if this PredefinedExpr has a trailing "StringLiteral *"
359     /// for the predefined identifier.
360     unsigned HasFunctionName : 1;
361 
362     /// The location of this PredefinedExpr.
363     SourceLocation Loc;
364   };
365 
366   class DeclRefExprBitfields {
367     friend class ASTStmtReader; // deserialization
368     friend class DeclRefExpr;
369 
370     unsigned : NumExprBits;
371 
372     unsigned HasQualifier : 1;
373     unsigned HasTemplateKWAndArgsInfo : 1;
374     unsigned HasFoundDecl : 1;
375     unsigned HadMultipleCandidates : 1;
376     unsigned RefersToEnclosingVariableOrCapture : 1;
377     unsigned NonOdrUseReason : 2;
378 
379     /// The location of the declaration name itself.
380     SourceLocation Loc;
381   };
382 
383 
384   class FloatingLiteralBitfields {
385     friend class FloatingLiteral;
386 
387     unsigned : NumExprBits;
388 
389     unsigned Semantics : 3; // Provides semantics for APFloat construction
390     unsigned IsExact : 1;
391   };
392 
393   class StringLiteralBitfields {
394     friend class ASTStmtReader;
395     friend class StringLiteral;
396 
397     unsigned : NumExprBits;
398 
399     /// The kind of this string literal.
400     /// One of the enumeration values of StringLiteral::StringKind.
401     unsigned Kind : 3;
402 
403     /// The width of a single character in bytes. Only values of 1, 2,
404     /// and 4 bytes are supported. StringLiteral::mapCharByteWidth maps
405     /// the target + string kind to the appropriate CharByteWidth.
406     unsigned CharByteWidth : 3;
407 
408     unsigned IsPascal : 1;
409 
410     /// The number of concatenated token this string is made of.
411     /// This is the number of trailing SourceLocation.
412     unsigned NumConcatenated;
413   };
414 
415   class CharacterLiteralBitfields {
416     friend class CharacterLiteral;
417 
418     unsigned : NumExprBits;
419 
420     unsigned Kind : 3;
421   };
422 
423   class UnaryOperatorBitfields {
424     friend class UnaryOperator;
425 
426     unsigned : NumExprBits;
427 
428     unsigned Opc : 5;
429     unsigned CanOverflow : 1;
430     //
431     /// This is only meaningful for operations on floating point
432     /// types when additional values need to be in trailing storage.
433     /// It is 0 otherwise.
434     unsigned HasFPFeatures : 1;
435 
436     SourceLocation Loc;
437   };
438 
439   class UnaryExprOrTypeTraitExprBitfields {
440     friend class UnaryExprOrTypeTraitExpr;
441 
442     unsigned : NumExprBits;
443 
444     unsigned Kind : 3;
445     unsigned IsType : 1; // true if operand is a type, false if an expression.
446   };
447 
448   class ArrayOrMatrixSubscriptExprBitfields {
449     friend class ArraySubscriptExpr;
450     friend class MatrixSubscriptExpr;
451 
452     unsigned : NumExprBits;
453 
454     SourceLocation RBracketLoc;
455   };
456 
457   class CallExprBitfields {
458     friend class CallExpr;
459 
460     unsigned : NumExprBits;
461 
462     unsigned NumPreArgs : 1;
463 
464     /// True if the callee of the call expression was found using ADL.
465     unsigned UsesADL : 1;
466 
467     /// True if the call expression has some floating-point features.
468     unsigned HasFPFeatures : 1;
469 
470     /// Padding used to align OffsetToTrailingObjects to a byte multiple.
471     unsigned : 24 - 3 - NumExprBits;
472 
473     /// The offset in bytes from the this pointer to the start of the
474     /// trailing objects belonging to CallExpr. Intentionally byte sized
475     /// for faster access.
476     unsigned OffsetToTrailingObjects : 8;
477   };
478   enum { NumCallExprBits = 32 };
479 
480   class MemberExprBitfields {
481     friend class ASTStmtReader;
482     friend class MemberExpr;
483 
484     unsigned : NumExprBits;
485 
486     /// IsArrow - True if this is "X->F", false if this is "X.F".
487     unsigned IsArrow : 1;
488 
489     /// True if this member expression used a nested-name-specifier to
490     /// refer to the member, e.g., "x->Base::f", or found its member via
491     /// a using declaration.  When true, a MemberExprNameQualifier
492     /// structure is allocated immediately after the MemberExpr.
493     unsigned HasQualifierOrFoundDecl : 1;
494 
495     /// True if this member expression specified a template keyword
496     /// and/or a template argument list explicitly, e.g., x->f<int>,
497     /// x->template f, x->template f<int>.
498     /// When true, an ASTTemplateKWAndArgsInfo structure and its
499     /// TemplateArguments (if any) are present.
500     unsigned HasTemplateKWAndArgsInfo : 1;
501 
502     /// True if this member expression refers to a method that
503     /// was resolved from an overloaded set having size greater than 1.
504     unsigned HadMultipleCandidates : 1;
505 
506     /// Value of type NonOdrUseReason indicating why this MemberExpr does
507     /// not constitute an odr-use of the named declaration. Meaningful only
508     /// when naming a static member.
509     unsigned NonOdrUseReason : 2;
510 
511     /// This is the location of the -> or . in the expression.
512     SourceLocation OperatorLoc;
513   };
514 
515   class CastExprBitfields {
516     friend class CastExpr;
517     friend class ImplicitCastExpr;
518 
519     unsigned : NumExprBits;
520 
521     unsigned Kind : 6;
522     unsigned PartOfExplicitCast : 1; // Only set for ImplicitCastExpr.
523 
524     /// True if the call expression has some floating-point features.
525     unsigned HasFPFeatures : 1;
526 
527     /// The number of CXXBaseSpecifiers in the cast. 14 bits would be enough
528     /// here. ([implimits] Direct and indirect base classes [16384]).
529     unsigned BasePathSize;
530   };
531 
532   class BinaryOperatorBitfields {
533     friend class BinaryOperator;
534 
535     unsigned : NumExprBits;
536 
537     unsigned Opc : 6;
538 
539     /// This is only meaningful for operations on floating point
540     /// types when additional values need to be in trailing storage.
541     /// It is 0 otherwise.
542     unsigned HasFPFeatures : 1;
543 
544     SourceLocation OpLoc;
545   };
546 
547   class InitListExprBitfields {
548     friend class InitListExpr;
549 
550     unsigned : NumExprBits;
551 
552     /// Whether this initializer list originally had a GNU array-range
553     /// designator in it. This is a temporary marker used by CodeGen.
554     unsigned HadArrayRangeDesignator : 1;
555   };
556 
557   class ParenListExprBitfields {
558     friend class ASTStmtReader;
559     friend class ParenListExpr;
560 
561     unsigned : NumExprBits;
562 
563     /// The number of expressions in the paren list.
564     unsigned NumExprs;
565   };
566 
567   class GenericSelectionExprBitfields {
568     friend class ASTStmtReader;
569     friend class GenericSelectionExpr;
570 
571     unsigned : NumExprBits;
572 
573     /// The location of the "_Generic".
574     SourceLocation GenericLoc;
575   };
576 
577   class PseudoObjectExprBitfields {
578     friend class ASTStmtReader; // deserialization
579     friend class PseudoObjectExpr;
580 
581     unsigned : NumExprBits;
582 
583     // These don't need to be particularly wide, because they're
584     // strictly limited by the forms of expressions we permit.
585     unsigned NumSubExprs : 8;
586     unsigned ResultIndex : 32 - 8 - NumExprBits;
587   };
588 
589   class SourceLocExprBitfields {
590     friend class ASTStmtReader;
591     friend class SourceLocExpr;
592 
593     unsigned : NumExprBits;
594 
595     /// The kind of source location builtin represented by the SourceLocExpr.
596     /// Ex. __builtin_LINE, __builtin_FUNCTION, ect.
597     unsigned Kind : 2;
598   };
599 
600   class StmtExprBitfields {
601     friend class ASTStmtReader;
602     friend class StmtExpr;
603 
604     unsigned : NumExprBits;
605 
606     /// The number of levels of template parameters enclosing this statement
607     /// expression. Used to determine if a statement expression remains
608     /// dependent after instantiation.
609     unsigned TemplateDepth;
610   };
611 
612   //===--- C++ Expression bitfields classes ---===//
613 
614   class CXXOperatorCallExprBitfields {
615     friend class ASTStmtReader;
616     friend class CXXOperatorCallExpr;
617 
618     unsigned : NumCallExprBits;
619 
620     /// The kind of this overloaded operator. One of the enumerator
621     /// value of OverloadedOperatorKind.
622     unsigned OperatorKind : 6;
623   };
624 
625   class CXXRewrittenBinaryOperatorBitfields {
626     friend class ASTStmtReader;
627     friend class CXXRewrittenBinaryOperator;
628 
629     unsigned : NumCallExprBits;
630 
631     unsigned IsReversed : 1;
632   };
633 
634   class CXXBoolLiteralExprBitfields {
635     friend class CXXBoolLiteralExpr;
636 
637     unsigned : NumExprBits;
638 
639     /// The value of the boolean literal.
640     unsigned Value : 1;
641 
642     /// The location of the boolean literal.
643     SourceLocation Loc;
644   };
645 
646   class CXXNullPtrLiteralExprBitfields {
647     friend class CXXNullPtrLiteralExpr;
648 
649     unsigned : NumExprBits;
650 
651     /// The location of the null pointer literal.
652     SourceLocation Loc;
653   };
654 
655   class CXXThisExprBitfields {
656     friend class CXXThisExpr;
657 
658     unsigned : NumExprBits;
659 
660     /// Whether this is an implicit "this".
661     unsigned IsImplicit : 1;
662 
663     /// The location of the "this".
664     SourceLocation Loc;
665   };
666 
667   class CXXThrowExprBitfields {
668     friend class ASTStmtReader;
669     friend class CXXThrowExpr;
670 
671     unsigned : NumExprBits;
672 
673     /// Whether the thrown variable (if any) is in scope.
674     unsigned IsThrownVariableInScope : 1;
675 
676     /// The location of the "throw".
677     SourceLocation ThrowLoc;
678   };
679 
680   class CXXDefaultArgExprBitfields {
681     friend class ASTStmtReader;
682     friend class CXXDefaultArgExpr;
683 
684     unsigned : NumExprBits;
685 
686     /// The location where the default argument expression was used.
687     SourceLocation Loc;
688   };
689 
690   class CXXDefaultInitExprBitfields {
691     friend class ASTStmtReader;
692     friend class CXXDefaultInitExpr;
693 
694     unsigned : NumExprBits;
695 
696     /// The location where the default initializer expression was used.
697     SourceLocation Loc;
698   };
699 
700   class CXXScalarValueInitExprBitfields {
701     friend class ASTStmtReader;
702     friend class CXXScalarValueInitExpr;
703 
704     unsigned : NumExprBits;
705 
706     SourceLocation RParenLoc;
707   };
708 
709   class CXXNewExprBitfields {
710     friend class ASTStmtReader;
711     friend class ASTStmtWriter;
712     friend class CXXNewExpr;
713 
714     unsigned : NumExprBits;
715 
716     /// Was the usage ::new, i.e. is the global new to be used?
717     unsigned IsGlobalNew : 1;
718 
719     /// Do we allocate an array? If so, the first trailing "Stmt *" is the
720     /// size expression.
721     unsigned IsArray : 1;
722 
723     /// Should the alignment be passed to the allocation function?
724     unsigned ShouldPassAlignment : 1;
725 
726     /// If this is an array allocation, does the usual deallocation
727     /// function for the allocated type want to know the allocated size?
728     unsigned UsualArrayDeleteWantsSize : 1;
729 
730     /// What kind of initializer do we have? Could be none, parens, or braces.
731     /// In storage, we distinguish between "none, and no initializer expr", and
732     /// "none, but an implicit initializer expr".
733     unsigned StoredInitializationStyle : 2;
734 
735     /// True if the allocated type was expressed as a parenthesized type-id.
736     unsigned IsParenTypeId : 1;
737 
738     /// The number of placement new arguments.
739     unsigned NumPlacementArgs;
740   };
741 
742   class CXXDeleteExprBitfields {
743     friend class ASTStmtReader;
744     friend class CXXDeleteExpr;
745 
746     unsigned : NumExprBits;
747 
748     /// Is this a forced global delete, i.e. "::delete"?
749     unsigned GlobalDelete : 1;
750 
751     /// Is this the array form of delete, i.e. "delete[]"?
752     unsigned ArrayForm : 1;
753 
754     /// ArrayFormAsWritten can be different from ArrayForm if 'delete' is
755     /// applied to pointer-to-array type (ArrayFormAsWritten will be false
756     /// while ArrayForm will be true).
757     unsigned ArrayFormAsWritten : 1;
758 
759     /// Does the usual deallocation function for the element type require
760     /// a size_t argument?
761     unsigned UsualArrayDeleteWantsSize : 1;
762 
763     /// Location of the expression.
764     SourceLocation Loc;
765   };
766 
767   class TypeTraitExprBitfields {
768     friend class ASTStmtReader;
769     friend class ASTStmtWriter;
770     friend class TypeTraitExpr;
771 
772     unsigned : NumExprBits;
773 
774     /// The kind of type trait, which is a value of a TypeTrait enumerator.
775     unsigned Kind : 8;
776 
777     /// If this expression is not value-dependent, this indicates whether
778     /// the trait evaluated true or false.
779     unsigned Value : 1;
780 
781     /// The number of arguments to this type trait. According to [implimits]
782     /// 8 bits would be enough, but we require (and test for) at least 16 bits
783     /// to mirror FunctionType.
784     unsigned NumArgs;
785   };
786 
787   class DependentScopeDeclRefExprBitfields {
788     friend class ASTStmtReader;
789     friend class ASTStmtWriter;
790     friend class DependentScopeDeclRefExpr;
791 
792     unsigned : NumExprBits;
793 
794     /// Whether the name includes info for explicit template
795     /// keyword and arguments.
796     unsigned HasTemplateKWAndArgsInfo : 1;
797   };
798 
799   class CXXConstructExprBitfields {
800     friend class ASTStmtReader;
801     friend class CXXConstructExpr;
802 
803     unsigned : NumExprBits;
804 
805     unsigned Elidable : 1;
806     unsigned HadMultipleCandidates : 1;
807     unsigned ListInitialization : 1;
808     unsigned StdInitListInitialization : 1;
809     unsigned ZeroInitialization : 1;
810     unsigned ConstructionKind : 3;
811 
812     SourceLocation Loc;
813   };
814 
815   class ExprWithCleanupsBitfields {
816     friend class ASTStmtReader; // deserialization
817     friend class ExprWithCleanups;
818 
819     unsigned : NumExprBits;
820 
821     // When false, it must not have side effects.
822     unsigned CleanupsHaveSideEffects : 1;
823 
824     unsigned NumObjects : 32 - 1 - NumExprBits;
825   };
826 
827   class CXXUnresolvedConstructExprBitfields {
828     friend class ASTStmtReader;
829     friend class CXXUnresolvedConstructExpr;
830 
831     unsigned : NumExprBits;
832 
833     /// The number of arguments used to construct the type.
834     unsigned NumArgs;
835   };
836 
837   class CXXDependentScopeMemberExprBitfields {
838     friend class ASTStmtReader;
839     friend class CXXDependentScopeMemberExpr;
840 
841     unsigned : NumExprBits;
842 
843     /// Whether this member expression used the '->' operator or
844     /// the '.' operator.
845     unsigned IsArrow : 1;
846 
847     /// Whether this member expression has info for explicit template
848     /// keyword and arguments.
849     unsigned HasTemplateKWAndArgsInfo : 1;
850 
851     /// See getFirstQualifierFoundInScope() and the comment listing
852     /// the trailing objects.
853     unsigned HasFirstQualifierFoundInScope : 1;
854 
855     /// The location of the '->' or '.' operator.
856     SourceLocation OperatorLoc;
857   };
858 
859   class OverloadExprBitfields {
860     friend class ASTStmtReader;
861     friend class OverloadExpr;
862 
863     unsigned : NumExprBits;
864 
865     /// Whether the name includes info for explicit template
866     /// keyword and arguments.
867     unsigned HasTemplateKWAndArgsInfo : 1;
868 
869     /// Padding used by the derived classes to store various bits. If you
870     /// need to add some data here, shrink this padding and add your data
871     /// above. NumOverloadExprBits also needs to be updated.
872     unsigned : 32 - NumExprBits - 1;
873 
874     /// The number of results.
875     unsigned NumResults;
876   };
877   enum { NumOverloadExprBits = NumExprBits + 1 };
878 
879   class UnresolvedLookupExprBitfields {
880     friend class ASTStmtReader;
881     friend class UnresolvedLookupExpr;
882 
883     unsigned : NumOverloadExprBits;
884 
885     /// True if these lookup results should be extended by
886     /// argument-dependent lookup if this is the operand of a function call.
887     unsigned RequiresADL : 1;
888 
889     /// True if these lookup results are overloaded.  This is pretty trivially
890     /// rederivable if we urgently need to kill this field.
891     unsigned Overloaded : 1;
892   };
893   static_assert(sizeof(UnresolvedLookupExprBitfields) <= 4,
894                 "UnresolvedLookupExprBitfields must be <= than 4 bytes to"
895                 "avoid trashing OverloadExprBitfields::NumResults!");
896 
897   class UnresolvedMemberExprBitfields {
898     friend class ASTStmtReader;
899     friend class UnresolvedMemberExpr;
900 
901     unsigned : NumOverloadExprBits;
902 
903     /// Whether this member expression used the '->' operator or
904     /// the '.' operator.
905     unsigned IsArrow : 1;
906 
907     /// Whether the lookup results contain an unresolved using declaration.
908     unsigned HasUnresolvedUsing : 1;
909   };
910   static_assert(sizeof(UnresolvedMemberExprBitfields) <= 4,
911                 "UnresolvedMemberExprBitfields must be <= than 4 bytes to"
912                 "avoid trashing OverloadExprBitfields::NumResults!");
913 
914   class CXXNoexceptExprBitfields {
915     friend class ASTStmtReader;
916     friend class CXXNoexceptExpr;
917 
918     unsigned : NumExprBits;
919 
920     unsigned Value : 1;
921   };
922 
923   class SubstNonTypeTemplateParmExprBitfields {
924     friend class ASTStmtReader;
925     friend class SubstNonTypeTemplateParmExpr;
926 
927     unsigned : NumExprBits;
928 
929     /// The location of the non-type template parameter reference.
930     SourceLocation NameLoc;
931   };
932 
933   class LambdaExprBitfields {
934     friend class ASTStmtReader;
935     friend class ASTStmtWriter;
936     friend class LambdaExpr;
937 
938     unsigned : NumExprBits;
939 
940     /// The default capture kind, which is a value of type
941     /// LambdaCaptureDefault.
942     unsigned CaptureDefault : 2;
943 
944     /// Whether this lambda had an explicit parameter list vs. an
945     /// implicit (and empty) parameter list.
946     unsigned ExplicitParams : 1;
947 
948     /// Whether this lambda had the result type explicitly specified.
949     unsigned ExplicitResultType : 1;
950 
951     /// The number of captures.
952     unsigned NumCaptures : 16;
953   };
954 
955   class RequiresExprBitfields {
956     friend class ASTStmtReader;
957     friend class ASTStmtWriter;
958     friend class RequiresExpr;
959 
960     unsigned : NumExprBits;
961 
962     unsigned IsSatisfied : 1;
963     SourceLocation RequiresKWLoc;
964   };
965 
966   //===--- C++ Coroutines TS bitfields classes ---===//
967 
968   class CoawaitExprBitfields {
969     friend class CoawaitExpr;
970 
971     unsigned : NumExprBits;
972 
973     unsigned IsImplicit : 1;
974   };
975 
976   //===--- Obj-C Expression bitfields classes ---===//
977 
978   class ObjCIndirectCopyRestoreExprBitfields {
979     friend class ObjCIndirectCopyRestoreExpr;
980 
981     unsigned : NumExprBits;
982 
983     unsigned ShouldCopy : 1;
984   };
985 
986   //===--- Clang Extensions bitfields classes ---===//
987 
988   class OpaqueValueExprBitfields {
989     friend class ASTStmtReader;
990     friend class OpaqueValueExpr;
991 
992     unsigned : NumExprBits;
993 
994     /// The OVE is a unique semantic reference to its source expression if this
995     /// bit is set to true.
996     unsigned IsUnique : 1;
997 
998     SourceLocation Loc;
999   };
1000 
1001   union {
1002     // Same order as in StmtNodes.td.
1003     // Statements
1004     StmtBitfields StmtBits;
1005     NullStmtBitfields NullStmtBits;
1006     CompoundStmtBitfields CompoundStmtBits;
1007     LabelStmtBitfields LabelStmtBits;
1008     AttributedStmtBitfields AttributedStmtBits;
1009     IfStmtBitfields IfStmtBits;
1010     SwitchStmtBitfields SwitchStmtBits;
1011     WhileStmtBitfields WhileStmtBits;
1012     DoStmtBitfields DoStmtBits;
1013     ForStmtBitfields ForStmtBits;
1014     GotoStmtBitfields GotoStmtBits;
1015     ContinueStmtBitfields ContinueStmtBits;
1016     BreakStmtBitfields BreakStmtBits;
1017     ReturnStmtBitfields ReturnStmtBits;
1018     SwitchCaseBitfields SwitchCaseBits;
1019 
1020     // Expressions
1021     ExprBitfields ExprBits;
1022     ConstantExprBitfields ConstantExprBits;
1023     PredefinedExprBitfields PredefinedExprBits;
1024     DeclRefExprBitfields DeclRefExprBits;
1025     FloatingLiteralBitfields FloatingLiteralBits;
1026     StringLiteralBitfields StringLiteralBits;
1027     CharacterLiteralBitfields CharacterLiteralBits;
1028     UnaryOperatorBitfields UnaryOperatorBits;
1029     UnaryExprOrTypeTraitExprBitfields UnaryExprOrTypeTraitExprBits;
1030     ArrayOrMatrixSubscriptExprBitfields ArrayOrMatrixSubscriptExprBits;
1031     CallExprBitfields CallExprBits;
1032     MemberExprBitfields MemberExprBits;
1033     CastExprBitfields CastExprBits;
1034     BinaryOperatorBitfields BinaryOperatorBits;
1035     InitListExprBitfields InitListExprBits;
1036     ParenListExprBitfields ParenListExprBits;
1037     GenericSelectionExprBitfields GenericSelectionExprBits;
1038     PseudoObjectExprBitfields PseudoObjectExprBits;
1039     SourceLocExprBitfields SourceLocExprBits;
1040 
1041     // GNU Extensions.
1042     StmtExprBitfields StmtExprBits;
1043 
1044     // C++ Expressions
1045     CXXOperatorCallExprBitfields CXXOperatorCallExprBits;
1046     CXXRewrittenBinaryOperatorBitfields CXXRewrittenBinaryOperatorBits;
1047     CXXBoolLiteralExprBitfields CXXBoolLiteralExprBits;
1048     CXXNullPtrLiteralExprBitfields CXXNullPtrLiteralExprBits;
1049     CXXThisExprBitfields CXXThisExprBits;
1050     CXXThrowExprBitfields CXXThrowExprBits;
1051     CXXDefaultArgExprBitfields CXXDefaultArgExprBits;
1052     CXXDefaultInitExprBitfields CXXDefaultInitExprBits;
1053     CXXScalarValueInitExprBitfields CXXScalarValueInitExprBits;
1054     CXXNewExprBitfields CXXNewExprBits;
1055     CXXDeleteExprBitfields CXXDeleteExprBits;
1056     TypeTraitExprBitfields TypeTraitExprBits;
1057     DependentScopeDeclRefExprBitfields DependentScopeDeclRefExprBits;
1058     CXXConstructExprBitfields CXXConstructExprBits;
1059     ExprWithCleanupsBitfields ExprWithCleanupsBits;
1060     CXXUnresolvedConstructExprBitfields CXXUnresolvedConstructExprBits;
1061     CXXDependentScopeMemberExprBitfields CXXDependentScopeMemberExprBits;
1062     OverloadExprBitfields OverloadExprBits;
1063     UnresolvedLookupExprBitfields UnresolvedLookupExprBits;
1064     UnresolvedMemberExprBitfields UnresolvedMemberExprBits;
1065     CXXNoexceptExprBitfields CXXNoexceptExprBits;
1066     SubstNonTypeTemplateParmExprBitfields SubstNonTypeTemplateParmExprBits;
1067     LambdaExprBitfields LambdaExprBits;
1068     RequiresExprBitfields RequiresExprBits;
1069 
1070     // C++ Coroutines TS expressions
1071     CoawaitExprBitfields CoawaitBits;
1072 
1073     // Obj-C Expressions
1074     ObjCIndirectCopyRestoreExprBitfields ObjCIndirectCopyRestoreExprBits;
1075 
1076     // Clang Extensions
1077     OpaqueValueExprBitfields OpaqueValueExprBits;
1078   };
1079 
1080 public:
1081   // Only allow allocation of Stmts using the allocator in ASTContext
1082   // or by doing a placement new.
1083   void* operator new(size_t bytes, const ASTContext& C,
1084                      unsigned alignment = 8);
1085 
1086   void* operator new(size_t bytes, const ASTContext* C,
1087                      unsigned alignment = 8) {
1088     return operator new(bytes, *C, alignment);
1089   }
1090 
1091   void *operator new(size_t bytes, void *mem) noexcept { return mem; }
1092 
1093   void operator delete(void *, const ASTContext &, unsigned) noexcept {}
1094   void operator delete(void *, const ASTContext *, unsigned) noexcept {}
1095   void operator delete(void *, size_t) noexcept {}
1096   void operator delete(void *, void *) noexcept {}
1097 
1098 public:
1099   /// A placeholder type used to construct an empty shell of a
1100   /// type, that will be filled in later (e.g., by some
1101   /// de-serialization).
1102   struct EmptyShell {};
1103 
1104   /// The likelihood of a branch being taken.
1105   enum Likelihood {
1106     LH_Unlikely = -1, ///< Branch has the [[unlikely]] attribute.
1107     LH_None,          ///< No attribute set or branches of the IfStmt have
1108                       ///< the same attribute.
1109     LH_Likely         ///< Branch has the [[likely]] attribute.
1110   };
1111 
1112 protected:
1113   /// Iterator for iterating over Stmt * arrays that contain only T *.
1114   ///
1115   /// This is needed because AST nodes use Stmt* arrays to store
1116   /// references to children (to be compatible with StmtIterator).
1117   template<typename T, typename TPtr = T *, typename StmtPtr = Stmt *>
1118   struct CastIterator
1119       : llvm::iterator_adaptor_base<CastIterator<T, TPtr, StmtPtr>, StmtPtr *,
1120                                     std::random_access_iterator_tag, TPtr> {
1121     using Base = typename CastIterator::iterator_adaptor_base;
1122 
1123     CastIterator() : Base(nullptr) {}
1124     CastIterator(StmtPtr *I) : Base(I) {}
1125 
1126     typename Base::value_type operator*() const {
1127       return cast_or_null<T>(*this->I);
1128     }
1129   };
1130 
1131   /// Const iterator for iterating over Stmt * arrays that contain only T *.
1132   template <typename T>
1133   using ConstCastIterator = CastIterator<T, const T *const, const Stmt *const>;
1134 
1135   using ExprIterator = CastIterator<Expr>;
1136   using ConstExprIterator = ConstCastIterator<Expr>;
1137 
1138 private:
1139   /// Whether statistic collection is enabled.
1140   static bool StatisticsEnabled;
1141 
1142 protected:
1143   /// Construct an empty statement.
1144   explicit Stmt(StmtClass SC, EmptyShell) : Stmt(SC) {}
1145 
1146 public:
1147   Stmt() = delete;
1148   Stmt(const Stmt &) = delete;
1149   Stmt(Stmt &&) = delete;
1150   Stmt &operator=(const Stmt &) = delete;
1151   Stmt &operator=(Stmt &&) = delete;
1152 
1153   Stmt(StmtClass SC) {
1154     static_assert(sizeof(*this) <= 8,
1155                   "changing bitfields changed sizeof(Stmt)");
1156     static_assert(sizeof(*this) % alignof(void *) == 0,
1157                   "Insufficient alignment!");
1158     StmtBits.sClass = SC;
1159     if (StatisticsEnabled) Stmt::addStmtClass(SC);
1160   }
1161 
1162   StmtClass getStmtClass() const {
1163     return static_cast<StmtClass>(StmtBits.sClass);
1164   }
1165 
1166   const char *getStmtClassName() const;
1167 
1168   /// SourceLocation tokens are not useful in isolation - they are low level
1169   /// value objects created/interpreted by SourceManager. We assume AST
1170   /// clients will have a pointer to the respective SourceManager.
1171   SourceRange getSourceRange() const LLVM_READONLY;
1172   SourceLocation getBeginLoc() const LLVM_READONLY;
1173   SourceLocation getEndLoc() const LLVM_READONLY;
1174 
1175   // global temp stats (until we have a per-module visitor)
1176   static void addStmtClass(const StmtClass s);
1177   static void EnableStatistics();
1178   static void PrintStats();
1179 
1180   /// \returns the likelihood of a set of attributes.
1181   static Likelihood getLikelihood(ArrayRef<const Attr *> Attrs);
1182 
1183   /// \returns the likelihood of a statement.
1184   static Likelihood getLikelihood(const Stmt *S);
1185 
1186   /// \returns the likelihood attribute of a statement.
1187   static const Attr *getLikelihoodAttr(const Stmt *S);
1188 
1189   /// \returns the likelihood of the 'then' branch of an 'if' statement. The
1190   /// 'else' branch is required to determine whether both branches specify the
1191   /// same likelihood, which affects the result.
1192   static Likelihood getLikelihood(const Stmt *Then, const Stmt *Else);
1193 
1194   /// \returns whether the likelihood of the branches of an if statement are
1195   /// conflicting. When the first element is \c true there's a conflict and
1196   /// the Attr's are the conflicting attributes of the Then and Else Stmt.
1197   static std::tuple<bool, const Attr *, const Attr *>
1198   determineLikelihoodConflict(const Stmt *Then, const Stmt *Else);
1199 
1200   /// Dumps the specified AST fragment and all subtrees to
1201   /// \c llvm::errs().
1202   void dump() const;
1203   void dump(raw_ostream &OS, const ASTContext &Context) const;
1204 
1205   /// \return Unique reproducible object identifier
1206   int64_t getID(const ASTContext &Context) const;
1207 
1208   /// dumpColor - same as dump(), but forces color highlighting.
1209   void dumpColor() const;
1210 
1211   /// dumpPretty/printPretty - These two methods do a "pretty print" of the AST
1212   /// back to its original source language syntax.
1213   void dumpPretty(const ASTContext &Context) const;
1214   void printPretty(raw_ostream &OS, PrinterHelper *Helper,
1215                    const PrintingPolicy &Policy, unsigned Indentation = 0,
1216                    StringRef NewlineSymbol = "\n",
1217                    const ASTContext *Context = nullptr) const;
1218 
1219   /// Pretty-prints in JSON format.
1220   void printJson(raw_ostream &Out, PrinterHelper *Helper,
1221                  const PrintingPolicy &Policy, bool AddQuotes) const;
1222 
1223   /// viewAST - Visualize an AST rooted at this Stmt* using GraphViz.  Only
1224   ///   works on systems with GraphViz (Mac OS X) or dot+gv installed.
1225   void viewAST() const;
1226 
1227   /// Skip no-op (attributed, compound) container stmts and skip captured
1228   /// stmt at the top, if \a IgnoreCaptured is true.
1229   Stmt *IgnoreContainers(bool IgnoreCaptured = false);
1230   const Stmt *IgnoreContainers(bool IgnoreCaptured = false) const {
1231     return const_cast<Stmt *>(this)->IgnoreContainers(IgnoreCaptured);
1232   }
1233 
1234   const Stmt *stripLabelLikeStatements() const;
1235   Stmt *stripLabelLikeStatements() {
1236     return const_cast<Stmt*>(
1237       const_cast<const Stmt*>(this)->stripLabelLikeStatements());
1238   }
1239 
1240   /// Child Iterators: All subclasses must implement 'children'
1241   /// to permit easy iteration over the substatements/subexpessions of an
1242   /// AST node.  This permits easy iteration over all nodes in the AST.
1243   using child_iterator = StmtIterator;
1244   using const_child_iterator = ConstStmtIterator;
1245 
1246   using child_range = llvm::iterator_range<child_iterator>;
1247   using const_child_range = llvm::iterator_range<const_child_iterator>;
1248 
1249   child_range children();
1250 
1251   const_child_range children() const {
1252     auto Children = const_cast<Stmt *>(this)->children();
1253     return const_child_range(Children.begin(), Children.end());
1254   }
1255 
1256   child_iterator child_begin() { return children().begin(); }
1257   child_iterator child_end() { return children().end(); }
1258 
1259   const_child_iterator child_begin() const { return children().begin(); }
1260   const_child_iterator child_end() const { return children().end(); }
1261 
1262   /// Produce a unique representation of the given statement.
1263   ///
1264   /// \param ID once the profiling operation is complete, will contain
1265   /// the unique representation of the given statement.
1266   ///
1267   /// \param Context the AST context in which the statement resides
1268   ///
1269   /// \param Canonical whether the profile should be based on the canonical
1270   /// representation of this statement (e.g., where non-type template
1271   /// parameters are identified by index/level rather than their
1272   /// declaration pointers) or the exact representation of the statement as
1273   /// written in the source.
1274   void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
1275                bool Canonical) const;
1276 
1277   /// Calculate a unique representation for a statement that is
1278   /// stable across compiler invocations.
1279   ///
1280   /// \param ID profile information will be stored in ID.
1281   ///
1282   /// \param Hash an ODRHash object which will be called where pointers would
1283   /// have been used in the Profile function.
1284   void ProcessODRHash(llvm::FoldingSetNodeID &ID, ODRHash& Hash) const;
1285 };
1286 
1287 /// DeclStmt - Adaptor class for mixing declarations with statements and
1288 /// expressions. For example, CompoundStmt mixes statements, expressions
1289 /// and declarations (variables, types). Another example is ForStmt, where
1290 /// the first statement can be an expression or a declaration.
1291 class DeclStmt : public Stmt {
1292   DeclGroupRef DG;
1293   SourceLocation StartLoc, EndLoc;
1294 
1295 public:
DeclStmt(DeclGroupRef dg,SourceLocation startLoc,SourceLocation endLoc)1296   DeclStmt(DeclGroupRef dg, SourceLocation startLoc, SourceLocation endLoc)
1297       : Stmt(DeclStmtClass), DG(dg), StartLoc(startLoc), EndLoc(endLoc) {}
1298 
1299   /// Build an empty declaration statement.
DeclStmt(EmptyShell Empty)1300   explicit DeclStmt(EmptyShell Empty) : Stmt(DeclStmtClass, Empty) {}
1301 
1302   /// isSingleDecl - This method returns true if this DeclStmt refers
1303   /// to a single Decl.
isSingleDecl()1304   bool isSingleDecl() const { return DG.isSingleDecl(); }
1305 
getSingleDecl()1306   const Decl *getSingleDecl() const { return DG.getSingleDecl(); }
getSingleDecl()1307   Decl *getSingleDecl() { return DG.getSingleDecl(); }
1308 
getDeclGroup()1309   const DeclGroupRef getDeclGroup() const { return DG; }
getDeclGroup()1310   DeclGroupRef getDeclGroup() { return DG; }
setDeclGroup(DeclGroupRef DGR)1311   void setDeclGroup(DeclGroupRef DGR) { DG = DGR; }
1312 
setStartLoc(SourceLocation L)1313   void setStartLoc(SourceLocation L) { StartLoc = L; }
getEndLoc()1314   SourceLocation getEndLoc() const { return EndLoc; }
setEndLoc(SourceLocation L)1315   void setEndLoc(SourceLocation L) { EndLoc = L; }
1316 
getBeginLoc()1317   SourceLocation getBeginLoc() const LLVM_READONLY { return StartLoc; }
1318 
classof(const Stmt * T)1319   static bool classof(const Stmt *T) {
1320     return T->getStmtClass() == DeclStmtClass;
1321   }
1322 
1323   // Iterators over subexpressions.
children()1324   child_range children() {
1325     return child_range(child_iterator(DG.begin(), DG.end()),
1326                        child_iterator(DG.end(), DG.end()));
1327   }
1328 
children()1329   const_child_range children() const {
1330     auto Children = const_cast<DeclStmt *>(this)->children();
1331     return const_child_range(Children);
1332   }
1333 
1334   using decl_iterator = DeclGroupRef::iterator;
1335   using const_decl_iterator = DeclGroupRef::const_iterator;
1336   using decl_range = llvm::iterator_range<decl_iterator>;
1337   using decl_const_range = llvm::iterator_range<const_decl_iterator>;
1338 
decls()1339   decl_range decls() { return decl_range(decl_begin(), decl_end()); }
1340 
decls()1341   decl_const_range decls() const {
1342     return decl_const_range(decl_begin(), decl_end());
1343   }
1344 
decl_begin()1345   decl_iterator decl_begin() { return DG.begin(); }
decl_end()1346   decl_iterator decl_end() { return DG.end(); }
decl_begin()1347   const_decl_iterator decl_begin() const { return DG.begin(); }
decl_end()1348   const_decl_iterator decl_end() const { return DG.end(); }
1349 
1350   using reverse_decl_iterator = std::reverse_iterator<decl_iterator>;
1351 
decl_rbegin()1352   reverse_decl_iterator decl_rbegin() {
1353     return reverse_decl_iterator(decl_end());
1354   }
1355 
decl_rend()1356   reverse_decl_iterator decl_rend() {
1357     return reverse_decl_iterator(decl_begin());
1358   }
1359 };
1360 
1361 /// NullStmt - This is the null statement ";": C99 6.8.3p3.
1362 ///
1363 class NullStmt : public Stmt {
1364 public:
1365   NullStmt(SourceLocation L, bool hasLeadingEmptyMacro = false)
Stmt(NullStmtClass)1366       : Stmt(NullStmtClass) {
1367     NullStmtBits.HasLeadingEmptyMacro = hasLeadingEmptyMacro;
1368     setSemiLoc(L);
1369   }
1370 
1371   /// Build an empty null statement.
NullStmt(EmptyShell Empty)1372   explicit NullStmt(EmptyShell Empty) : Stmt(NullStmtClass, Empty) {}
1373 
getSemiLoc()1374   SourceLocation getSemiLoc() const { return NullStmtBits.SemiLoc; }
setSemiLoc(SourceLocation L)1375   void setSemiLoc(SourceLocation L) { NullStmtBits.SemiLoc = L; }
1376 
hasLeadingEmptyMacro()1377   bool hasLeadingEmptyMacro() const {
1378     return NullStmtBits.HasLeadingEmptyMacro;
1379   }
1380 
getBeginLoc()1381   SourceLocation getBeginLoc() const { return getSemiLoc(); }
getEndLoc()1382   SourceLocation getEndLoc() const { return getSemiLoc(); }
1383 
classof(const Stmt * T)1384   static bool classof(const Stmt *T) {
1385     return T->getStmtClass() == NullStmtClass;
1386   }
1387 
children()1388   child_range children() {
1389     return child_range(child_iterator(), child_iterator());
1390   }
1391 
children()1392   const_child_range children() const {
1393     return const_child_range(const_child_iterator(), const_child_iterator());
1394   }
1395 };
1396 
1397 /// CompoundStmt - This represents a group of statements like { stmt stmt }.
1398 class CompoundStmt final : public Stmt,
1399                            private llvm::TrailingObjects<CompoundStmt, Stmt *> {
1400   friend class ASTStmtReader;
1401   friend TrailingObjects;
1402 
1403   /// The location of the closing "}". LBraceLoc is stored in CompoundStmtBits.
1404   SourceLocation RBraceLoc;
1405 
1406   CompoundStmt(ArrayRef<Stmt *> Stmts, SourceLocation LB, SourceLocation RB);
CompoundStmt(EmptyShell Empty)1407   explicit CompoundStmt(EmptyShell Empty) : Stmt(CompoundStmtClass, Empty) {}
1408 
1409   void setStmts(ArrayRef<Stmt *> Stmts);
1410 
1411 public:
1412   static CompoundStmt *Create(const ASTContext &C, ArrayRef<Stmt *> Stmts,
1413                               SourceLocation LB, SourceLocation RB);
1414 
1415   // Build an empty compound statement with a location.
CompoundStmt(SourceLocation Loc)1416   explicit CompoundStmt(SourceLocation Loc)
1417       : Stmt(CompoundStmtClass), RBraceLoc(Loc) {
1418     CompoundStmtBits.NumStmts = 0;
1419     CompoundStmtBits.LBraceLoc = Loc;
1420   }
1421 
1422   // Build an empty compound statement.
1423   static CompoundStmt *CreateEmpty(const ASTContext &C, unsigned NumStmts);
1424 
body_empty()1425   bool body_empty() const { return CompoundStmtBits.NumStmts == 0; }
size()1426   unsigned size() const { return CompoundStmtBits.NumStmts; }
1427 
1428   using body_iterator = Stmt **;
1429   using body_range = llvm::iterator_range<body_iterator>;
1430 
body()1431   body_range body() { return body_range(body_begin(), body_end()); }
body_begin()1432   body_iterator body_begin() { return getTrailingObjects<Stmt *>(); }
body_end()1433   body_iterator body_end() { return body_begin() + size(); }
body_front()1434   Stmt *body_front() { return !body_empty() ? body_begin()[0] : nullptr; }
1435 
body_back()1436   Stmt *body_back() {
1437     return !body_empty() ? body_begin()[size() - 1] : nullptr;
1438   }
1439 
1440   using const_body_iterator = Stmt *const *;
1441   using body_const_range = llvm::iterator_range<const_body_iterator>;
1442 
body()1443   body_const_range body() const {
1444     return body_const_range(body_begin(), body_end());
1445   }
1446 
body_begin()1447   const_body_iterator body_begin() const {
1448     return getTrailingObjects<Stmt *>();
1449   }
1450 
body_end()1451   const_body_iterator body_end() const { return body_begin() + size(); }
1452 
body_front()1453   const Stmt *body_front() const {
1454     return !body_empty() ? body_begin()[0] : nullptr;
1455   }
1456 
body_back()1457   const Stmt *body_back() const {
1458     return !body_empty() ? body_begin()[size() - 1] : nullptr;
1459   }
1460 
1461   using reverse_body_iterator = std::reverse_iterator<body_iterator>;
1462 
body_rbegin()1463   reverse_body_iterator body_rbegin() {
1464     return reverse_body_iterator(body_end());
1465   }
1466 
body_rend()1467   reverse_body_iterator body_rend() {
1468     return reverse_body_iterator(body_begin());
1469   }
1470 
1471   using const_reverse_body_iterator =
1472       std::reverse_iterator<const_body_iterator>;
1473 
body_rbegin()1474   const_reverse_body_iterator body_rbegin() const {
1475     return const_reverse_body_iterator(body_end());
1476   }
1477 
body_rend()1478   const_reverse_body_iterator body_rend() const {
1479     return const_reverse_body_iterator(body_begin());
1480   }
1481 
1482   // Get the Stmt that StmtExpr would consider to be the result of this
1483   // compound statement. This is used by StmtExpr to properly emulate the GCC
1484   // compound expression extension, which ignores trailing NullStmts when
1485   // getting the result of the expression.
1486   // i.e. ({ 5;;; })
1487   //           ^^ ignored
1488   // If we don't find something that isn't a NullStmt, just return the last
1489   // Stmt.
getStmtExprResult()1490   Stmt *getStmtExprResult() {
1491     for (auto *B : llvm::reverse(body())) {
1492       if (!isa<NullStmt>(B))
1493         return B;
1494     }
1495     return body_back();
1496   }
1497 
getStmtExprResult()1498   const Stmt *getStmtExprResult() const {
1499     return const_cast<CompoundStmt *>(this)->getStmtExprResult();
1500   }
1501 
getBeginLoc()1502   SourceLocation getBeginLoc() const { return CompoundStmtBits.LBraceLoc; }
getEndLoc()1503   SourceLocation getEndLoc() const { return RBraceLoc; }
1504 
getLBracLoc()1505   SourceLocation getLBracLoc() const { return CompoundStmtBits.LBraceLoc; }
getRBracLoc()1506   SourceLocation getRBracLoc() const { return RBraceLoc; }
1507 
classof(const Stmt * T)1508   static bool classof(const Stmt *T) {
1509     return T->getStmtClass() == CompoundStmtClass;
1510   }
1511 
1512   // Iterators
children()1513   child_range children() { return child_range(body_begin(), body_end()); }
1514 
children()1515   const_child_range children() const {
1516     return const_child_range(body_begin(), body_end());
1517   }
1518 };
1519 
1520 // SwitchCase is the base class for CaseStmt and DefaultStmt,
1521 class SwitchCase : public Stmt {
1522 protected:
1523   /// The location of the ":".
1524   SourceLocation ColonLoc;
1525 
1526   // The location of the "case" or "default" keyword. Stored in SwitchCaseBits.
1527   // SourceLocation KeywordLoc;
1528 
1529   /// A pointer to the following CaseStmt or DefaultStmt class,
1530   /// used by SwitchStmt.
1531   SwitchCase *NextSwitchCase = nullptr;
1532 
SwitchCase(StmtClass SC,SourceLocation KWLoc,SourceLocation ColonLoc)1533   SwitchCase(StmtClass SC, SourceLocation KWLoc, SourceLocation ColonLoc)
1534       : Stmt(SC), ColonLoc(ColonLoc) {
1535     setKeywordLoc(KWLoc);
1536   }
1537 
SwitchCase(StmtClass SC,EmptyShell)1538   SwitchCase(StmtClass SC, EmptyShell) : Stmt(SC) {}
1539 
1540 public:
getNextSwitchCase()1541   const SwitchCase *getNextSwitchCase() const { return NextSwitchCase; }
getNextSwitchCase()1542   SwitchCase *getNextSwitchCase() { return NextSwitchCase; }
setNextSwitchCase(SwitchCase * SC)1543   void setNextSwitchCase(SwitchCase *SC) { NextSwitchCase = SC; }
1544 
getKeywordLoc()1545   SourceLocation getKeywordLoc() const { return SwitchCaseBits.KeywordLoc; }
setKeywordLoc(SourceLocation L)1546   void setKeywordLoc(SourceLocation L) { SwitchCaseBits.KeywordLoc = L; }
getColonLoc()1547   SourceLocation getColonLoc() const { return ColonLoc; }
setColonLoc(SourceLocation L)1548   void setColonLoc(SourceLocation L) { ColonLoc = L; }
1549 
1550   inline Stmt *getSubStmt();
getSubStmt()1551   const Stmt *getSubStmt() const {
1552     return const_cast<SwitchCase *>(this)->getSubStmt();
1553   }
1554 
getBeginLoc()1555   SourceLocation getBeginLoc() const { return getKeywordLoc(); }
1556   inline SourceLocation getEndLoc() const LLVM_READONLY;
1557 
classof(const Stmt * T)1558   static bool classof(const Stmt *T) {
1559     return T->getStmtClass() == CaseStmtClass ||
1560            T->getStmtClass() == DefaultStmtClass;
1561   }
1562 };
1563 
1564 /// CaseStmt - Represent a case statement. It can optionally be a GNU case
1565 /// statement of the form LHS ... RHS representing a range of cases.
1566 class CaseStmt final
1567     : public SwitchCase,
1568       private llvm::TrailingObjects<CaseStmt, Stmt *, SourceLocation> {
1569   friend TrailingObjects;
1570 
1571   // CaseStmt is followed by several trailing objects, some of which optional.
1572   // Note that it would be more convenient to put the optional trailing objects
1573   // at the end but this would impact children().
1574   // The trailing objects are in order:
1575   //
1576   // * A "Stmt *" for the LHS of the case statement. Always present.
1577   //
1578   // * A "Stmt *" for the RHS of the case statement. This is a GNU extension
1579   //   which allow ranges in cases statement of the form LHS ... RHS.
1580   //   Present if and only if caseStmtIsGNURange() is true.
1581   //
1582   // * A "Stmt *" for the substatement of the case statement. Always present.
1583   //
1584   // * A SourceLocation for the location of the ... if this is a case statement
1585   //   with a range. Present if and only if caseStmtIsGNURange() is true.
1586   enum { LhsOffset = 0, SubStmtOffsetFromRhs = 1 };
1587   enum { NumMandatoryStmtPtr = 2 };
1588 
numTrailingObjects(OverloadToken<Stmt * >)1589   unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
1590     return NumMandatoryStmtPtr + caseStmtIsGNURange();
1591   }
1592 
numTrailingObjects(OverloadToken<SourceLocation>)1593   unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
1594     return caseStmtIsGNURange();
1595   }
1596 
lhsOffset()1597   unsigned lhsOffset() const { return LhsOffset; }
rhsOffset()1598   unsigned rhsOffset() const { return LhsOffset + caseStmtIsGNURange(); }
subStmtOffset()1599   unsigned subStmtOffset() const { return rhsOffset() + SubStmtOffsetFromRhs; }
1600 
1601   /// Build a case statement assuming that the storage for the
1602   /// trailing objects has been properly allocated.
CaseStmt(Expr * lhs,Expr * rhs,SourceLocation caseLoc,SourceLocation ellipsisLoc,SourceLocation colonLoc)1603   CaseStmt(Expr *lhs, Expr *rhs, SourceLocation caseLoc,
1604            SourceLocation ellipsisLoc, SourceLocation colonLoc)
1605       : SwitchCase(CaseStmtClass, caseLoc, colonLoc) {
1606     // Handle GNU case statements of the form LHS ... RHS.
1607     bool IsGNURange = rhs != nullptr;
1608     SwitchCaseBits.CaseStmtIsGNURange = IsGNURange;
1609     setLHS(lhs);
1610     setSubStmt(nullptr);
1611     if (IsGNURange) {
1612       setRHS(rhs);
1613       setEllipsisLoc(ellipsisLoc);
1614     }
1615   }
1616 
1617   /// Build an empty switch case statement.
CaseStmt(EmptyShell Empty,bool CaseStmtIsGNURange)1618   explicit CaseStmt(EmptyShell Empty, bool CaseStmtIsGNURange)
1619       : SwitchCase(CaseStmtClass, Empty) {
1620     SwitchCaseBits.CaseStmtIsGNURange = CaseStmtIsGNURange;
1621   }
1622 
1623 public:
1624   /// Build a case statement.
1625   static CaseStmt *Create(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
1626                           SourceLocation caseLoc, SourceLocation ellipsisLoc,
1627                           SourceLocation colonLoc);
1628 
1629   /// Build an empty case statement.
1630   static CaseStmt *CreateEmpty(const ASTContext &Ctx, bool CaseStmtIsGNURange);
1631 
1632   /// True if this case statement is of the form case LHS ... RHS, which
1633   /// is a GNU extension. In this case the RHS can be obtained with getRHS()
1634   /// and the location of the ellipsis can be obtained with getEllipsisLoc().
caseStmtIsGNURange()1635   bool caseStmtIsGNURange() const { return SwitchCaseBits.CaseStmtIsGNURange; }
1636 
getCaseLoc()1637   SourceLocation getCaseLoc() const { return getKeywordLoc(); }
setCaseLoc(SourceLocation L)1638   void setCaseLoc(SourceLocation L) { setKeywordLoc(L); }
1639 
1640   /// Get the location of the ... in a case statement of the form LHS ... RHS.
getEllipsisLoc()1641   SourceLocation getEllipsisLoc() const {
1642     return caseStmtIsGNURange() ? *getTrailingObjects<SourceLocation>()
1643                                 : SourceLocation();
1644   }
1645 
1646   /// Set the location of the ... in a case statement of the form LHS ... RHS.
1647   /// Assert that this case statement is of this form.
setEllipsisLoc(SourceLocation L)1648   void setEllipsisLoc(SourceLocation L) {
1649     assert(
1650         caseStmtIsGNURange() &&
1651         "setEllipsisLoc but this is not a case stmt of the form LHS ... RHS!");
1652     *getTrailingObjects<SourceLocation>() = L;
1653   }
1654 
getLHS()1655   Expr *getLHS() {
1656     return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[lhsOffset()]);
1657   }
1658 
getLHS()1659   const Expr *getLHS() const {
1660     return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[lhsOffset()]);
1661   }
1662 
setLHS(Expr * Val)1663   void setLHS(Expr *Val) {
1664     getTrailingObjects<Stmt *>()[lhsOffset()] = reinterpret_cast<Stmt *>(Val);
1665   }
1666 
getRHS()1667   Expr *getRHS() {
1668     return caseStmtIsGNURange() ? reinterpret_cast<Expr *>(
1669                                       getTrailingObjects<Stmt *>()[rhsOffset()])
1670                                 : nullptr;
1671   }
1672 
getRHS()1673   const Expr *getRHS() const {
1674     return caseStmtIsGNURange() ? reinterpret_cast<Expr *>(
1675                                       getTrailingObjects<Stmt *>()[rhsOffset()])
1676                                 : nullptr;
1677   }
1678 
setRHS(Expr * Val)1679   void setRHS(Expr *Val) {
1680     assert(caseStmtIsGNURange() &&
1681            "setRHS but this is not a case stmt of the form LHS ... RHS!");
1682     getTrailingObjects<Stmt *>()[rhsOffset()] = reinterpret_cast<Stmt *>(Val);
1683   }
1684 
getSubStmt()1685   Stmt *getSubStmt() { return getTrailingObjects<Stmt *>()[subStmtOffset()]; }
getSubStmt()1686   const Stmt *getSubStmt() const {
1687     return getTrailingObjects<Stmt *>()[subStmtOffset()];
1688   }
1689 
setSubStmt(Stmt * S)1690   void setSubStmt(Stmt *S) {
1691     getTrailingObjects<Stmt *>()[subStmtOffset()] = S;
1692   }
1693 
getBeginLoc()1694   SourceLocation getBeginLoc() const { return getKeywordLoc(); }
getEndLoc()1695   SourceLocation getEndLoc() const LLVM_READONLY {
1696     // Handle deeply nested case statements with iteration instead of recursion.
1697     const CaseStmt *CS = this;
1698     while (const auto *CS2 = dyn_cast<CaseStmt>(CS->getSubStmt()))
1699       CS = CS2;
1700 
1701     return CS->getSubStmt()->getEndLoc();
1702   }
1703 
classof(const Stmt * T)1704   static bool classof(const Stmt *T) {
1705     return T->getStmtClass() == CaseStmtClass;
1706   }
1707 
1708   // Iterators
children()1709   child_range children() {
1710     return child_range(getTrailingObjects<Stmt *>(),
1711                        getTrailingObjects<Stmt *>() +
1712                            numTrailingObjects(OverloadToken<Stmt *>()));
1713   }
1714 
children()1715   const_child_range children() const {
1716     return const_child_range(getTrailingObjects<Stmt *>(),
1717                              getTrailingObjects<Stmt *>() +
1718                                  numTrailingObjects(OverloadToken<Stmt *>()));
1719   }
1720 };
1721 
1722 class DefaultStmt : public SwitchCase {
1723   Stmt *SubStmt;
1724 
1725 public:
DefaultStmt(SourceLocation DL,SourceLocation CL,Stmt * substmt)1726   DefaultStmt(SourceLocation DL, SourceLocation CL, Stmt *substmt)
1727       : SwitchCase(DefaultStmtClass, DL, CL), SubStmt(substmt) {}
1728 
1729   /// Build an empty default statement.
DefaultStmt(EmptyShell Empty)1730   explicit DefaultStmt(EmptyShell Empty)
1731       : SwitchCase(DefaultStmtClass, Empty) {}
1732 
getSubStmt()1733   Stmt *getSubStmt() { return SubStmt; }
getSubStmt()1734   const Stmt *getSubStmt() const { return SubStmt; }
setSubStmt(Stmt * S)1735   void setSubStmt(Stmt *S) { SubStmt = S; }
1736 
getDefaultLoc()1737   SourceLocation getDefaultLoc() const { return getKeywordLoc(); }
setDefaultLoc(SourceLocation L)1738   void setDefaultLoc(SourceLocation L) { setKeywordLoc(L); }
1739 
getBeginLoc()1740   SourceLocation getBeginLoc() const { return getKeywordLoc(); }
getEndLoc()1741   SourceLocation getEndLoc() const LLVM_READONLY {
1742     return SubStmt->getEndLoc();
1743   }
1744 
classof(const Stmt * T)1745   static bool classof(const Stmt *T) {
1746     return T->getStmtClass() == DefaultStmtClass;
1747   }
1748 
1749   // Iterators
children()1750   child_range children() { return child_range(&SubStmt, &SubStmt + 1); }
1751 
children()1752   const_child_range children() const {
1753     return const_child_range(&SubStmt, &SubStmt + 1);
1754   }
1755 };
1756 
getEndLoc()1757 SourceLocation SwitchCase::getEndLoc() const {
1758   if (const auto *CS = dyn_cast<CaseStmt>(this))
1759     return CS->getEndLoc();
1760   else if (const auto *DS = dyn_cast<DefaultStmt>(this))
1761     return DS->getEndLoc();
1762   llvm_unreachable("SwitchCase is neither a CaseStmt nor a DefaultStmt!");
1763 }
1764 
getSubStmt()1765 Stmt *SwitchCase::getSubStmt() {
1766   if (auto *CS = dyn_cast<CaseStmt>(this))
1767     return CS->getSubStmt();
1768   else if (auto *DS = dyn_cast<DefaultStmt>(this))
1769     return DS->getSubStmt();
1770   llvm_unreachable("SwitchCase is neither a CaseStmt nor a DefaultStmt!");
1771 }
1772 
1773 /// Represents a statement that could possibly have a value and type. This
1774 /// covers expression-statements, as well as labels and attributed statements.
1775 ///
1776 /// Value statements have a special meaning when they are the last non-null
1777 /// statement in a GNU statement expression, where they determine the value
1778 /// of the statement expression.
1779 class ValueStmt : public Stmt {
1780 protected:
1781   using Stmt::Stmt;
1782 
1783 public:
1784   const Expr *getExprStmt() const;
getExprStmt()1785   Expr *getExprStmt() {
1786     const ValueStmt *ConstThis = this;
1787     return const_cast<Expr*>(ConstThis->getExprStmt());
1788   }
1789 
classof(const Stmt * T)1790   static bool classof(const Stmt *T) {
1791     return T->getStmtClass() >= firstValueStmtConstant &&
1792            T->getStmtClass() <= lastValueStmtConstant;
1793   }
1794 };
1795 
1796 /// LabelStmt - Represents a label, which has a substatement.  For example:
1797 ///    foo: return;
1798 class LabelStmt : public ValueStmt {
1799   LabelDecl *TheDecl;
1800   Stmt *SubStmt;
1801 
1802 public:
1803   /// Build a label statement.
LabelStmt(SourceLocation IL,LabelDecl * D,Stmt * substmt)1804   LabelStmt(SourceLocation IL, LabelDecl *D, Stmt *substmt)
1805       : ValueStmt(LabelStmtClass), TheDecl(D), SubStmt(substmt) {
1806     setIdentLoc(IL);
1807   }
1808 
1809   /// Build an empty label statement.
LabelStmt(EmptyShell Empty)1810   explicit LabelStmt(EmptyShell Empty) : ValueStmt(LabelStmtClass, Empty) {}
1811 
getIdentLoc()1812   SourceLocation getIdentLoc() const { return LabelStmtBits.IdentLoc; }
setIdentLoc(SourceLocation L)1813   void setIdentLoc(SourceLocation L) { LabelStmtBits.IdentLoc = L; }
1814 
getDecl()1815   LabelDecl *getDecl() const { return TheDecl; }
setDecl(LabelDecl * D)1816   void setDecl(LabelDecl *D) { TheDecl = D; }
1817 
1818   const char *getName() const;
getSubStmt()1819   Stmt *getSubStmt() { return SubStmt; }
1820 
getSubStmt()1821   const Stmt *getSubStmt() const { return SubStmt; }
setSubStmt(Stmt * SS)1822   void setSubStmt(Stmt *SS) { SubStmt = SS; }
1823 
getBeginLoc()1824   SourceLocation getBeginLoc() const { return getIdentLoc(); }
getEndLoc()1825   SourceLocation getEndLoc() const LLVM_READONLY { return SubStmt->getEndLoc();}
1826 
children()1827   child_range children() { return child_range(&SubStmt, &SubStmt + 1); }
1828 
children()1829   const_child_range children() const {
1830     return const_child_range(&SubStmt, &SubStmt + 1);
1831   }
1832 
classof(const Stmt * T)1833   static bool classof(const Stmt *T) {
1834     return T->getStmtClass() == LabelStmtClass;
1835   }
1836 };
1837 
1838 /// Represents an attribute applied to a statement.
1839 ///
1840 /// Represents an attribute applied to a statement. For example:
1841 ///   [[omp::for(...)]] for (...) { ... }
1842 class AttributedStmt final
1843     : public ValueStmt,
1844       private llvm::TrailingObjects<AttributedStmt, const Attr *> {
1845   friend class ASTStmtReader;
1846   friend TrailingObjects;
1847 
1848   Stmt *SubStmt;
1849 
AttributedStmt(SourceLocation Loc,ArrayRef<const Attr * > Attrs,Stmt * SubStmt)1850   AttributedStmt(SourceLocation Loc, ArrayRef<const Attr *> Attrs,
1851                  Stmt *SubStmt)
1852       : ValueStmt(AttributedStmtClass), SubStmt(SubStmt) {
1853     AttributedStmtBits.NumAttrs = Attrs.size();
1854     AttributedStmtBits.AttrLoc = Loc;
1855     std::copy(Attrs.begin(), Attrs.end(), getAttrArrayPtr());
1856   }
1857 
AttributedStmt(EmptyShell Empty,unsigned NumAttrs)1858   explicit AttributedStmt(EmptyShell Empty, unsigned NumAttrs)
1859       : ValueStmt(AttributedStmtClass, Empty) {
1860     AttributedStmtBits.NumAttrs = NumAttrs;
1861     AttributedStmtBits.AttrLoc = SourceLocation{};
1862     std::fill_n(getAttrArrayPtr(), NumAttrs, nullptr);
1863   }
1864 
getAttrArrayPtr()1865   const Attr *const *getAttrArrayPtr() const {
1866     return getTrailingObjects<const Attr *>();
1867   }
getAttrArrayPtr()1868   const Attr **getAttrArrayPtr() { return getTrailingObjects<const Attr *>(); }
1869 
1870 public:
1871   static AttributedStmt *Create(const ASTContext &C, SourceLocation Loc,
1872                                 ArrayRef<const Attr *> Attrs, Stmt *SubStmt);
1873 
1874   // Build an empty attributed statement.
1875   static AttributedStmt *CreateEmpty(const ASTContext &C, unsigned NumAttrs);
1876 
getAttrLoc()1877   SourceLocation getAttrLoc() const { return AttributedStmtBits.AttrLoc; }
getAttrs()1878   ArrayRef<const Attr *> getAttrs() const {
1879     return llvm::makeArrayRef(getAttrArrayPtr(), AttributedStmtBits.NumAttrs);
1880   }
1881 
getSubStmt()1882   Stmt *getSubStmt() { return SubStmt; }
getSubStmt()1883   const Stmt *getSubStmt() const { return SubStmt; }
1884 
getBeginLoc()1885   SourceLocation getBeginLoc() const { return getAttrLoc(); }
getEndLoc()1886   SourceLocation getEndLoc() const LLVM_READONLY { return SubStmt->getEndLoc();}
1887 
children()1888   child_range children() { return child_range(&SubStmt, &SubStmt + 1); }
1889 
children()1890   const_child_range children() const {
1891     return const_child_range(&SubStmt, &SubStmt + 1);
1892   }
1893 
classof(const Stmt * T)1894   static bool classof(const Stmt *T) {
1895     return T->getStmtClass() == AttributedStmtClass;
1896   }
1897 };
1898 
1899 /// IfStmt - This represents an if/then/else.
1900 class IfStmt final
1901     : public Stmt,
1902       private llvm::TrailingObjects<IfStmt, Stmt *, SourceLocation> {
1903   friend TrailingObjects;
1904 
1905   // IfStmt is followed by several trailing objects, some of which optional.
1906   // Note that it would be more convenient to put the optional trailing
1907   // objects at then end but this would change the order of the children.
1908   // The trailing objects are in order:
1909   //
1910   // * A "Stmt *" for the init statement.
1911   //    Present if and only if hasInitStorage().
1912   //
1913   // * A "Stmt *" for the condition variable.
1914   //    Present if and only if hasVarStorage(). This is in fact a "DeclStmt *".
1915   //
1916   // * A "Stmt *" for the condition.
1917   //    Always present. This is in fact a "Expr *".
1918   //
1919   // * A "Stmt *" for the then statement.
1920   //    Always present.
1921   //
1922   // * A "Stmt *" for the else statement.
1923   //    Present if and only if hasElseStorage().
1924   //
1925   // * A "SourceLocation" for the location of the "else".
1926   //    Present if and only if hasElseStorage().
1927   enum { InitOffset = 0, ThenOffsetFromCond = 1, ElseOffsetFromCond = 2 };
1928   enum { NumMandatoryStmtPtr = 2 };
1929   SourceLocation LParenLoc;
1930   SourceLocation RParenLoc;
1931 
numTrailingObjects(OverloadToken<Stmt * >)1932   unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
1933     return NumMandatoryStmtPtr + hasElseStorage() + hasVarStorage() +
1934            hasInitStorage();
1935   }
1936 
numTrailingObjects(OverloadToken<SourceLocation>)1937   unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
1938     return hasElseStorage();
1939   }
1940 
initOffset()1941   unsigned initOffset() const { return InitOffset; }
varOffset()1942   unsigned varOffset() const { return InitOffset + hasInitStorage(); }
condOffset()1943   unsigned condOffset() const {
1944     return InitOffset + hasInitStorage() + hasVarStorage();
1945   }
thenOffset()1946   unsigned thenOffset() const { return condOffset() + ThenOffsetFromCond; }
elseOffset()1947   unsigned elseOffset() const { return condOffset() + ElseOffsetFromCond; }
1948 
1949   /// Build an if/then/else statement.
1950   IfStmt(const ASTContext &Ctx, SourceLocation IL, bool IsConstexpr, Stmt *Init,
1951          VarDecl *Var, Expr *Cond, SourceLocation LParenLoc,
1952          SourceLocation RParenLoc, Stmt *Then, SourceLocation EL, Stmt *Else);
1953 
1954   /// Build an empty if/then/else statement.
1955   explicit IfStmt(EmptyShell Empty, bool HasElse, bool HasVar, bool HasInit);
1956 
1957 public:
1958   /// Create an IfStmt.
1959   static IfStmt *Create(const ASTContext &Ctx, SourceLocation IL,
1960                         bool IsConstexpr, Stmt *Init, VarDecl *Var, Expr *Cond,
1961                         SourceLocation LPL, SourceLocation RPL, Stmt *Then,
1962                         SourceLocation EL = SourceLocation(),
1963                         Stmt *Else = nullptr);
1964 
1965   /// Create an empty IfStmt optionally with storage for an else statement,
1966   /// condition variable and init expression.
1967   static IfStmt *CreateEmpty(const ASTContext &Ctx, bool HasElse, bool HasVar,
1968                              bool HasInit);
1969 
1970   /// True if this IfStmt has the storage for an init statement.
hasInitStorage()1971   bool hasInitStorage() const { return IfStmtBits.HasInit; }
1972 
1973   /// True if this IfStmt has storage for a variable declaration.
hasVarStorage()1974   bool hasVarStorage() const { return IfStmtBits.HasVar; }
1975 
1976   /// True if this IfStmt has storage for an else statement.
hasElseStorage()1977   bool hasElseStorage() const { return IfStmtBits.HasElse; }
1978 
getCond()1979   Expr *getCond() {
1980     return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[condOffset()]);
1981   }
1982 
getCond()1983   const Expr *getCond() const {
1984     return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[condOffset()]);
1985   }
1986 
setCond(Expr * Cond)1987   void setCond(Expr *Cond) {
1988     getTrailingObjects<Stmt *>()[condOffset()] = reinterpret_cast<Stmt *>(Cond);
1989   }
1990 
getThen()1991   Stmt *getThen() { return getTrailingObjects<Stmt *>()[thenOffset()]; }
getThen()1992   const Stmt *getThen() const {
1993     return getTrailingObjects<Stmt *>()[thenOffset()];
1994   }
1995 
setThen(Stmt * Then)1996   void setThen(Stmt *Then) {
1997     getTrailingObjects<Stmt *>()[thenOffset()] = Then;
1998   }
1999 
getElse()2000   Stmt *getElse() {
2001     return hasElseStorage() ? getTrailingObjects<Stmt *>()[elseOffset()]
2002                             : nullptr;
2003   }
2004 
getElse()2005   const Stmt *getElse() const {
2006     return hasElseStorage() ? getTrailingObjects<Stmt *>()[elseOffset()]
2007                             : nullptr;
2008   }
2009 
setElse(Stmt * Else)2010   void setElse(Stmt *Else) {
2011     assert(hasElseStorage() &&
2012            "This if statement has no storage for an else statement!");
2013     getTrailingObjects<Stmt *>()[elseOffset()] = Else;
2014   }
2015 
2016   /// Retrieve the variable declared in this "if" statement, if any.
2017   ///
2018   /// In the following example, "x" is the condition variable.
2019   /// \code
2020   /// if (int x = foo()) {
2021   ///   printf("x is %d", x);
2022   /// }
2023   /// \endcode
2024   VarDecl *getConditionVariable();
getConditionVariable()2025   const VarDecl *getConditionVariable() const {
2026     return const_cast<IfStmt *>(this)->getConditionVariable();
2027   }
2028 
2029   /// Set the condition variable for this if statement.
2030   /// The if statement must have storage for the condition variable.
2031   void setConditionVariable(const ASTContext &Ctx, VarDecl *V);
2032 
2033   /// If this IfStmt has a condition variable, return the faux DeclStmt
2034   /// associated with the creation of that condition variable.
getConditionVariableDeclStmt()2035   DeclStmt *getConditionVariableDeclStmt() {
2036     return hasVarStorage() ? static_cast<DeclStmt *>(
2037                                  getTrailingObjects<Stmt *>()[varOffset()])
2038                            : nullptr;
2039   }
2040 
getConditionVariableDeclStmt()2041   const DeclStmt *getConditionVariableDeclStmt() const {
2042     return hasVarStorage() ? static_cast<DeclStmt *>(
2043                                  getTrailingObjects<Stmt *>()[varOffset()])
2044                            : nullptr;
2045   }
2046 
getInit()2047   Stmt *getInit() {
2048     return hasInitStorage() ? getTrailingObjects<Stmt *>()[initOffset()]
2049                             : nullptr;
2050   }
2051 
getInit()2052   const Stmt *getInit() const {
2053     return hasInitStorage() ? getTrailingObjects<Stmt *>()[initOffset()]
2054                             : nullptr;
2055   }
2056 
setInit(Stmt * Init)2057   void setInit(Stmt *Init) {
2058     assert(hasInitStorage() &&
2059            "This if statement has no storage for an init statement!");
2060     getTrailingObjects<Stmt *>()[initOffset()] = Init;
2061   }
2062 
getIfLoc()2063   SourceLocation getIfLoc() const { return IfStmtBits.IfLoc; }
setIfLoc(SourceLocation IfLoc)2064   void setIfLoc(SourceLocation IfLoc) { IfStmtBits.IfLoc = IfLoc; }
2065 
getElseLoc()2066   SourceLocation getElseLoc() const {
2067     return hasElseStorage() ? *getTrailingObjects<SourceLocation>()
2068                             : SourceLocation();
2069   }
2070 
setElseLoc(SourceLocation ElseLoc)2071   void setElseLoc(SourceLocation ElseLoc) {
2072     assert(hasElseStorage() &&
2073            "This if statement has no storage for an else statement!");
2074     *getTrailingObjects<SourceLocation>() = ElseLoc;
2075   }
2076 
isConstexpr()2077   bool isConstexpr() const { return IfStmtBits.IsConstexpr; }
setConstexpr(bool C)2078   void setConstexpr(bool C) { IfStmtBits.IsConstexpr = C; }
2079 
2080   /// If this is an 'if constexpr', determine which substatement will be taken.
2081   /// Otherwise, or if the condition is value-dependent, returns None.
2082   Optional<const Stmt*> getNondiscardedCase(const ASTContext &Ctx) const;
2083 
2084   bool isObjCAvailabilityCheck() const;
2085 
getBeginLoc()2086   SourceLocation getBeginLoc() const { return getIfLoc(); }
getEndLoc()2087   SourceLocation getEndLoc() const LLVM_READONLY {
2088     if (getElse())
2089       return getElse()->getEndLoc();
2090     return getThen()->getEndLoc();
2091   }
getLParenLoc()2092   SourceLocation getLParenLoc() const { return LParenLoc; }
setLParenLoc(SourceLocation Loc)2093   void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
getRParenLoc()2094   SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation Loc)2095   void setRParenLoc(SourceLocation Loc) { RParenLoc = Loc; }
2096 
2097   // Iterators over subexpressions.  The iterators will include iterating
2098   // over the initialization expression referenced by the condition variable.
children()2099   child_range children() {
2100     return child_range(getTrailingObjects<Stmt *>(),
2101                        getTrailingObjects<Stmt *>() +
2102                            numTrailingObjects(OverloadToken<Stmt *>()));
2103   }
2104 
children()2105   const_child_range children() const {
2106     return const_child_range(getTrailingObjects<Stmt *>(),
2107                              getTrailingObjects<Stmt *>() +
2108                                  numTrailingObjects(OverloadToken<Stmt *>()));
2109   }
2110 
classof(const Stmt * T)2111   static bool classof(const Stmt *T) {
2112     return T->getStmtClass() == IfStmtClass;
2113   }
2114 };
2115 
2116 /// SwitchStmt - This represents a 'switch' stmt.
2117 class SwitchStmt final : public Stmt,
2118                          private llvm::TrailingObjects<SwitchStmt, Stmt *> {
2119   friend TrailingObjects;
2120 
2121   /// Points to a linked list of case and default statements.
2122   SwitchCase *FirstCase;
2123 
2124   // SwitchStmt is followed by several trailing objects,
2125   // some of which optional. Note that it would be more convenient to
2126   // put the optional trailing objects at the end but this would change
2127   // the order in children().
2128   // The trailing objects are in order:
2129   //
2130   // * A "Stmt *" for the init statement.
2131   //    Present if and only if hasInitStorage().
2132   //
2133   // * A "Stmt *" for the condition variable.
2134   //    Present if and only if hasVarStorage(). This is in fact a "DeclStmt *".
2135   //
2136   // * A "Stmt *" for the condition.
2137   //    Always present. This is in fact an "Expr *".
2138   //
2139   // * A "Stmt *" for the body.
2140   //    Always present.
2141   enum { InitOffset = 0, BodyOffsetFromCond = 1 };
2142   enum { NumMandatoryStmtPtr = 2 };
2143   SourceLocation LParenLoc;
2144   SourceLocation RParenLoc;
2145 
numTrailingObjects(OverloadToken<Stmt * >)2146   unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
2147     return NumMandatoryStmtPtr + hasInitStorage() + hasVarStorage();
2148   }
2149 
initOffset()2150   unsigned initOffset() const { return InitOffset; }
varOffset()2151   unsigned varOffset() const { return InitOffset + hasInitStorage(); }
condOffset()2152   unsigned condOffset() const {
2153     return InitOffset + hasInitStorage() + hasVarStorage();
2154   }
bodyOffset()2155   unsigned bodyOffset() const { return condOffset() + BodyOffsetFromCond; }
2156 
2157   /// Build a switch statement.
2158   SwitchStmt(const ASTContext &Ctx, Stmt *Init, VarDecl *Var, Expr *Cond,
2159              SourceLocation LParenLoc, SourceLocation RParenLoc);
2160 
2161   /// Build a empty switch statement.
2162   explicit SwitchStmt(EmptyShell Empty, bool HasInit, bool HasVar);
2163 
2164 public:
2165   /// Create a switch statement.
2166   static SwitchStmt *Create(const ASTContext &Ctx, Stmt *Init, VarDecl *Var,
2167                             Expr *Cond, SourceLocation LParenLoc,
2168                             SourceLocation RParenLoc);
2169 
2170   /// Create an empty switch statement optionally with storage for
2171   /// an init expression and a condition variable.
2172   static SwitchStmt *CreateEmpty(const ASTContext &Ctx, bool HasInit,
2173                                  bool HasVar);
2174 
2175   /// True if this SwitchStmt has storage for an init statement.
hasInitStorage()2176   bool hasInitStorage() const { return SwitchStmtBits.HasInit; }
2177 
2178   /// True if this SwitchStmt has storage for a condition variable.
hasVarStorage()2179   bool hasVarStorage() const { return SwitchStmtBits.HasVar; }
2180 
getCond()2181   Expr *getCond() {
2182     return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[condOffset()]);
2183   }
2184 
getCond()2185   const Expr *getCond() const {
2186     return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[condOffset()]);
2187   }
2188 
setCond(Expr * Cond)2189   void setCond(Expr *Cond) {
2190     getTrailingObjects<Stmt *>()[condOffset()] = reinterpret_cast<Stmt *>(Cond);
2191   }
2192 
getBody()2193   Stmt *getBody() { return getTrailingObjects<Stmt *>()[bodyOffset()]; }
getBody()2194   const Stmt *getBody() const {
2195     return getTrailingObjects<Stmt *>()[bodyOffset()];
2196   }
2197 
setBody(Stmt * Body)2198   void setBody(Stmt *Body) {
2199     getTrailingObjects<Stmt *>()[bodyOffset()] = Body;
2200   }
2201 
getInit()2202   Stmt *getInit() {
2203     return hasInitStorage() ? getTrailingObjects<Stmt *>()[initOffset()]
2204                             : nullptr;
2205   }
2206 
getInit()2207   const Stmt *getInit() const {
2208     return hasInitStorage() ? getTrailingObjects<Stmt *>()[initOffset()]
2209                             : nullptr;
2210   }
2211 
setInit(Stmt * Init)2212   void setInit(Stmt *Init) {
2213     assert(hasInitStorage() &&
2214            "This switch statement has no storage for an init statement!");
2215     getTrailingObjects<Stmt *>()[initOffset()] = Init;
2216   }
2217 
2218   /// Retrieve the variable declared in this "switch" statement, if any.
2219   ///
2220   /// In the following example, "x" is the condition variable.
2221   /// \code
2222   /// switch (int x = foo()) {
2223   ///   case 0: break;
2224   ///   // ...
2225   /// }
2226   /// \endcode
2227   VarDecl *getConditionVariable();
getConditionVariable()2228   const VarDecl *getConditionVariable() const {
2229     return const_cast<SwitchStmt *>(this)->getConditionVariable();
2230   }
2231 
2232   /// Set the condition variable in this switch statement.
2233   /// The switch statement must have storage for it.
2234   void setConditionVariable(const ASTContext &Ctx, VarDecl *VD);
2235 
2236   /// If this SwitchStmt has a condition variable, return the faux DeclStmt
2237   /// associated with the creation of that condition variable.
getConditionVariableDeclStmt()2238   DeclStmt *getConditionVariableDeclStmt() {
2239     return hasVarStorage() ? static_cast<DeclStmt *>(
2240                                  getTrailingObjects<Stmt *>()[varOffset()])
2241                            : nullptr;
2242   }
2243 
getConditionVariableDeclStmt()2244   const DeclStmt *getConditionVariableDeclStmt() const {
2245     return hasVarStorage() ? static_cast<DeclStmt *>(
2246                                  getTrailingObjects<Stmt *>()[varOffset()])
2247                            : nullptr;
2248   }
2249 
getSwitchCaseList()2250   SwitchCase *getSwitchCaseList() { return FirstCase; }
getSwitchCaseList()2251   const SwitchCase *getSwitchCaseList() const { return FirstCase; }
setSwitchCaseList(SwitchCase * SC)2252   void setSwitchCaseList(SwitchCase *SC) { FirstCase = SC; }
2253 
getSwitchLoc()2254   SourceLocation getSwitchLoc() const { return SwitchStmtBits.SwitchLoc; }
setSwitchLoc(SourceLocation L)2255   void setSwitchLoc(SourceLocation L) { SwitchStmtBits.SwitchLoc = L; }
getLParenLoc()2256   SourceLocation getLParenLoc() const { return LParenLoc; }
setLParenLoc(SourceLocation Loc)2257   void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
getRParenLoc()2258   SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation Loc)2259   void setRParenLoc(SourceLocation Loc) { RParenLoc = Loc; }
2260 
setBody(Stmt * S,SourceLocation SL)2261   void setBody(Stmt *S, SourceLocation SL) {
2262     setBody(S);
2263     setSwitchLoc(SL);
2264   }
2265 
addSwitchCase(SwitchCase * SC)2266   void addSwitchCase(SwitchCase *SC) {
2267     assert(!SC->getNextSwitchCase() &&
2268            "case/default already added to a switch");
2269     SC->setNextSwitchCase(FirstCase);
2270     FirstCase = SC;
2271   }
2272 
2273   /// Set a flag in the SwitchStmt indicating that if the 'switch (X)' is a
2274   /// switch over an enum value then all cases have been explicitly covered.
setAllEnumCasesCovered()2275   void setAllEnumCasesCovered() { SwitchStmtBits.AllEnumCasesCovered = true; }
2276 
2277   /// Returns true if the SwitchStmt is a switch of an enum value and all cases
2278   /// have been explicitly covered.
isAllEnumCasesCovered()2279   bool isAllEnumCasesCovered() const {
2280     return SwitchStmtBits.AllEnumCasesCovered;
2281   }
2282 
getBeginLoc()2283   SourceLocation getBeginLoc() const { return getSwitchLoc(); }
getEndLoc()2284   SourceLocation getEndLoc() const LLVM_READONLY {
2285     return getBody() ? getBody()->getEndLoc()
2286                      : reinterpret_cast<const Stmt *>(getCond())->getEndLoc();
2287   }
2288 
2289   // Iterators
children()2290   child_range children() {
2291     return child_range(getTrailingObjects<Stmt *>(),
2292                        getTrailingObjects<Stmt *>() +
2293                            numTrailingObjects(OverloadToken<Stmt *>()));
2294   }
2295 
children()2296   const_child_range children() const {
2297     return const_child_range(getTrailingObjects<Stmt *>(),
2298                              getTrailingObjects<Stmt *>() +
2299                                  numTrailingObjects(OverloadToken<Stmt *>()));
2300   }
2301 
classof(const Stmt * T)2302   static bool classof(const Stmt *T) {
2303     return T->getStmtClass() == SwitchStmtClass;
2304   }
2305 };
2306 
2307 /// WhileStmt - This represents a 'while' stmt.
2308 class WhileStmt final : public Stmt,
2309                         private llvm::TrailingObjects<WhileStmt, Stmt *> {
2310   friend TrailingObjects;
2311 
2312   // WhileStmt is followed by several trailing objects,
2313   // some of which optional. Note that it would be more
2314   // convenient to put the optional trailing object at the end
2315   // but this would affect children().
2316   // The trailing objects are in order:
2317   //
2318   // * A "Stmt *" for the condition variable.
2319   //    Present if and only if hasVarStorage(). This is in fact a "DeclStmt *".
2320   //
2321   // * A "Stmt *" for the condition.
2322   //    Always present. This is in fact an "Expr *".
2323   //
2324   // * A "Stmt *" for the body.
2325   //    Always present.
2326   //
2327   enum { VarOffset = 0, BodyOffsetFromCond = 1 };
2328   enum { NumMandatoryStmtPtr = 2 };
2329 
2330   SourceLocation LParenLoc, RParenLoc;
2331 
varOffset()2332   unsigned varOffset() const { return VarOffset; }
condOffset()2333   unsigned condOffset() const { return VarOffset + hasVarStorage(); }
bodyOffset()2334   unsigned bodyOffset() const { return condOffset() + BodyOffsetFromCond; }
2335 
numTrailingObjects(OverloadToken<Stmt * >)2336   unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
2337     return NumMandatoryStmtPtr + hasVarStorage();
2338   }
2339 
2340   /// Build a while statement.
2341   WhileStmt(const ASTContext &Ctx, VarDecl *Var, Expr *Cond, Stmt *Body,
2342             SourceLocation WL, SourceLocation LParenLoc,
2343             SourceLocation RParenLoc);
2344 
2345   /// Build an empty while statement.
2346   explicit WhileStmt(EmptyShell Empty, bool HasVar);
2347 
2348 public:
2349   /// Create a while statement.
2350   static WhileStmt *Create(const ASTContext &Ctx, VarDecl *Var, Expr *Cond,
2351                            Stmt *Body, SourceLocation WL,
2352                            SourceLocation LParenLoc, SourceLocation RParenLoc);
2353 
2354   /// Create an empty while statement optionally with storage for
2355   /// a condition variable.
2356   static WhileStmt *CreateEmpty(const ASTContext &Ctx, bool HasVar);
2357 
2358   /// True if this WhileStmt has storage for a condition variable.
hasVarStorage()2359   bool hasVarStorage() const { return WhileStmtBits.HasVar; }
2360 
getCond()2361   Expr *getCond() {
2362     return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[condOffset()]);
2363   }
2364 
getCond()2365   const Expr *getCond() const {
2366     return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[condOffset()]);
2367   }
2368 
setCond(Expr * Cond)2369   void setCond(Expr *Cond) {
2370     getTrailingObjects<Stmt *>()[condOffset()] = reinterpret_cast<Stmt *>(Cond);
2371   }
2372 
getBody()2373   Stmt *getBody() { return getTrailingObjects<Stmt *>()[bodyOffset()]; }
getBody()2374   const Stmt *getBody() const {
2375     return getTrailingObjects<Stmt *>()[bodyOffset()];
2376   }
2377 
setBody(Stmt * Body)2378   void setBody(Stmt *Body) {
2379     getTrailingObjects<Stmt *>()[bodyOffset()] = Body;
2380   }
2381 
2382   /// Retrieve the variable declared in this "while" statement, if any.
2383   ///
2384   /// In the following example, "x" is the condition variable.
2385   /// \code
2386   /// while (int x = random()) {
2387   ///   // ...
2388   /// }
2389   /// \endcode
2390   VarDecl *getConditionVariable();
getConditionVariable()2391   const VarDecl *getConditionVariable() const {
2392     return const_cast<WhileStmt *>(this)->getConditionVariable();
2393   }
2394 
2395   /// Set the condition variable of this while statement.
2396   /// The while statement must have storage for it.
2397   void setConditionVariable(const ASTContext &Ctx, VarDecl *V);
2398 
2399   /// If this WhileStmt has a condition variable, return the faux DeclStmt
2400   /// associated with the creation of that condition variable.
getConditionVariableDeclStmt()2401   DeclStmt *getConditionVariableDeclStmt() {
2402     return hasVarStorage() ? static_cast<DeclStmt *>(
2403                                  getTrailingObjects<Stmt *>()[varOffset()])
2404                            : nullptr;
2405   }
2406 
getConditionVariableDeclStmt()2407   const DeclStmt *getConditionVariableDeclStmt() const {
2408     return hasVarStorage() ? static_cast<DeclStmt *>(
2409                                  getTrailingObjects<Stmt *>()[varOffset()])
2410                            : nullptr;
2411   }
2412 
getWhileLoc()2413   SourceLocation getWhileLoc() const { return WhileStmtBits.WhileLoc; }
setWhileLoc(SourceLocation L)2414   void setWhileLoc(SourceLocation L) { WhileStmtBits.WhileLoc = L; }
2415 
getLParenLoc()2416   SourceLocation getLParenLoc() const { return LParenLoc; }
setLParenLoc(SourceLocation L)2417   void setLParenLoc(SourceLocation L) { LParenLoc = L; }
getRParenLoc()2418   SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)2419   void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2420 
getBeginLoc()2421   SourceLocation getBeginLoc() const { return getWhileLoc(); }
getEndLoc()2422   SourceLocation getEndLoc() const LLVM_READONLY {
2423     return getBody()->getEndLoc();
2424   }
2425 
classof(const Stmt * T)2426   static bool classof(const Stmt *T) {
2427     return T->getStmtClass() == WhileStmtClass;
2428   }
2429 
2430   // Iterators
children()2431   child_range children() {
2432     return child_range(getTrailingObjects<Stmt *>(),
2433                        getTrailingObjects<Stmt *>() +
2434                            numTrailingObjects(OverloadToken<Stmt *>()));
2435   }
2436 
children()2437   const_child_range children() const {
2438     return const_child_range(getTrailingObjects<Stmt *>(),
2439                              getTrailingObjects<Stmt *>() +
2440                                  numTrailingObjects(OverloadToken<Stmt *>()));
2441   }
2442 };
2443 
2444 /// DoStmt - This represents a 'do/while' stmt.
2445 class DoStmt : public Stmt {
2446   enum { BODY, COND, END_EXPR };
2447   Stmt *SubExprs[END_EXPR];
2448   SourceLocation WhileLoc;
2449   SourceLocation RParenLoc; // Location of final ')' in do stmt condition.
2450 
2451 public:
DoStmt(Stmt * Body,Expr * Cond,SourceLocation DL,SourceLocation WL,SourceLocation RP)2452   DoStmt(Stmt *Body, Expr *Cond, SourceLocation DL, SourceLocation WL,
2453          SourceLocation RP)
2454       : Stmt(DoStmtClass), WhileLoc(WL), RParenLoc(RP) {
2455     setCond(Cond);
2456     setBody(Body);
2457     setDoLoc(DL);
2458   }
2459 
2460   /// Build an empty do-while statement.
DoStmt(EmptyShell Empty)2461   explicit DoStmt(EmptyShell Empty) : Stmt(DoStmtClass, Empty) {}
2462 
getCond()2463   Expr *getCond() { return reinterpret_cast<Expr *>(SubExprs[COND]); }
getCond()2464   const Expr *getCond() const {
2465     return reinterpret_cast<Expr *>(SubExprs[COND]);
2466   }
2467 
setCond(Expr * Cond)2468   void setCond(Expr *Cond) { SubExprs[COND] = reinterpret_cast<Stmt *>(Cond); }
2469 
getBody()2470   Stmt *getBody() { return SubExprs[BODY]; }
getBody()2471   const Stmt *getBody() const { return SubExprs[BODY]; }
setBody(Stmt * Body)2472   void setBody(Stmt *Body) { SubExprs[BODY] = Body; }
2473 
getDoLoc()2474   SourceLocation getDoLoc() const { return DoStmtBits.DoLoc; }
setDoLoc(SourceLocation L)2475   void setDoLoc(SourceLocation L) { DoStmtBits.DoLoc = L; }
getWhileLoc()2476   SourceLocation getWhileLoc() const { return WhileLoc; }
setWhileLoc(SourceLocation L)2477   void setWhileLoc(SourceLocation L) { WhileLoc = L; }
getRParenLoc()2478   SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)2479   void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2480 
getBeginLoc()2481   SourceLocation getBeginLoc() const { return getDoLoc(); }
getEndLoc()2482   SourceLocation getEndLoc() const { return getRParenLoc(); }
2483 
classof(const Stmt * T)2484   static bool classof(const Stmt *T) {
2485     return T->getStmtClass() == DoStmtClass;
2486   }
2487 
2488   // Iterators
children()2489   child_range children() {
2490     return child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2491   }
2492 
children()2493   const_child_range children() const {
2494     return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2495   }
2496 };
2497 
2498 /// ForStmt - This represents a 'for (init;cond;inc)' stmt.  Note that any of
2499 /// the init/cond/inc parts of the ForStmt will be null if they were not
2500 /// specified in the source.
2501 class ForStmt : public Stmt {
2502   enum { INIT, CONDVAR, COND, INC, BODY, END_EXPR };
2503   Stmt* SubExprs[END_EXPR]; // SubExprs[INIT] is an expression or declstmt.
2504   SourceLocation LParenLoc, RParenLoc;
2505 
2506 public:
2507   ForStmt(const ASTContext &C, Stmt *Init, Expr *Cond, VarDecl *condVar,
2508           Expr *Inc, Stmt *Body, SourceLocation FL, SourceLocation LP,
2509           SourceLocation RP);
2510 
2511   /// Build an empty for statement.
ForStmt(EmptyShell Empty)2512   explicit ForStmt(EmptyShell Empty) : Stmt(ForStmtClass, Empty) {}
2513 
getInit()2514   Stmt *getInit() { return SubExprs[INIT]; }
2515 
2516   /// Retrieve the variable declared in this "for" statement, if any.
2517   ///
2518   /// In the following example, "y" is the condition variable.
2519   /// \code
2520   /// for (int x = random(); int y = mangle(x); ++x) {
2521   ///   // ...
2522   /// }
2523   /// \endcode
2524   VarDecl *getConditionVariable() const;
2525   void setConditionVariable(const ASTContext &C, VarDecl *V);
2526 
2527   /// If this ForStmt has a condition variable, return the faux DeclStmt
2528   /// associated with the creation of that condition variable.
getConditionVariableDeclStmt()2529   const DeclStmt *getConditionVariableDeclStmt() const {
2530     return reinterpret_cast<DeclStmt*>(SubExprs[CONDVAR]);
2531   }
2532 
getCond()2533   Expr *getCond() { return reinterpret_cast<Expr*>(SubExprs[COND]); }
getInc()2534   Expr *getInc()  { return reinterpret_cast<Expr*>(SubExprs[INC]); }
getBody()2535   Stmt *getBody() { return SubExprs[BODY]; }
2536 
getInit()2537   const Stmt *getInit() const { return SubExprs[INIT]; }
getCond()2538   const Expr *getCond() const { return reinterpret_cast<Expr*>(SubExprs[COND]);}
getInc()2539   const Expr *getInc()  const { return reinterpret_cast<Expr*>(SubExprs[INC]); }
getBody()2540   const Stmt *getBody() const { return SubExprs[BODY]; }
2541 
setInit(Stmt * S)2542   void setInit(Stmt *S) { SubExprs[INIT] = S; }
setCond(Expr * E)2543   void setCond(Expr *E) { SubExprs[COND] = reinterpret_cast<Stmt*>(E); }
setInc(Expr * E)2544   void setInc(Expr *E) { SubExprs[INC] = reinterpret_cast<Stmt*>(E); }
setBody(Stmt * S)2545   void setBody(Stmt *S) { SubExprs[BODY] = S; }
2546 
getForLoc()2547   SourceLocation getForLoc() const { return ForStmtBits.ForLoc; }
setForLoc(SourceLocation L)2548   void setForLoc(SourceLocation L) { ForStmtBits.ForLoc = L; }
getLParenLoc()2549   SourceLocation getLParenLoc() const { return LParenLoc; }
setLParenLoc(SourceLocation L)2550   void setLParenLoc(SourceLocation L) { LParenLoc = L; }
getRParenLoc()2551   SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)2552   void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2553 
getBeginLoc()2554   SourceLocation getBeginLoc() const { return getForLoc(); }
getEndLoc()2555   SourceLocation getEndLoc() const { return getBody()->getEndLoc(); }
2556 
classof(const Stmt * T)2557   static bool classof(const Stmt *T) {
2558     return T->getStmtClass() == ForStmtClass;
2559   }
2560 
2561   // Iterators
children()2562   child_range children() {
2563     return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2564   }
2565 
children()2566   const_child_range children() const {
2567     return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2568   }
2569 };
2570 
2571 /// GotoStmt - This represents a direct goto.
2572 class GotoStmt : public Stmt {
2573   LabelDecl *Label;
2574   SourceLocation LabelLoc;
2575 
2576 public:
GotoStmt(LabelDecl * label,SourceLocation GL,SourceLocation LL)2577   GotoStmt(LabelDecl *label, SourceLocation GL, SourceLocation LL)
2578       : Stmt(GotoStmtClass), Label(label), LabelLoc(LL) {
2579     setGotoLoc(GL);
2580   }
2581 
2582   /// Build an empty goto statement.
GotoStmt(EmptyShell Empty)2583   explicit GotoStmt(EmptyShell Empty) : Stmt(GotoStmtClass, Empty) {}
2584 
getLabel()2585   LabelDecl *getLabel() const { return Label; }
setLabel(LabelDecl * D)2586   void setLabel(LabelDecl *D) { Label = D; }
2587 
getGotoLoc()2588   SourceLocation getGotoLoc() const { return GotoStmtBits.GotoLoc; }
setGotoLoc(SourceLocation L)2589   void setGotoLoc(SourceLocation L) { GotoStmtBits.GotoLoc = L; }
getLabelLoc()2590   SourceLocation getLabelLoc() const { return LabelLoc; }
setLabelLoc(SourceLocation L)2591   void setLabelLoc(SourceLocation L) { LabelLoc = L; }
2592 
getBeginLoc()2593   SourceLocation getBeginLoc() const { return getGotoLoc(); }
getEndLoc()2594   SourceLocation getEndLoc() const { return getLabelLoc(); }
2595 
classof(const Stmt * T)2596   static bool classof(const Stmt *T) {
2597     return T->getStmtClass() == GotoStmtClass;
2598   }
2599 
2600   // Iterators
children()2601   child_range children() {
2602     return child_range(child_iterator(), child_iterator());
2603   }
2604 
children()2605   const_child_range children() const {
2606     return const_child_range(const_child_iterator(), const_child_iterator());
2607   }
2608 };
2609 
2610 /// IndirectGotoStmt - This represents an indirect goto.
2611 class IndirectGotoStmt : public Stmt {
2612   SourceLocation StarLoc;
2613   Stmt *Target;
2614 
2615 public:
IndirectGotoStmt(SourceLocation gotoLoc,SourceLocation starLoc,Expr * target)2616   IndirectGotoStmt(SourceLocation gotoLoc, SourceLocation starLoc, Expr *target)
2617       : Stmt(IndirectGotoStmtClass), StarLoc(starLoc) {
2618     setTarget(target);
2619     setGotoLoc(gotoLoc);
2620   }
2621 
2622   /// Build an empty indirect goto statement.
IndirectGotoStmt(EmptyShell Empty)2623   explicit IndirectGotoStmt(EmptyShell Empty)
2624       : Stmt(IndirectGotoStmtClass, Empty) {}
2625 
setGotoLoc(SourceLocation L)2626   void setGotoLoc(SourceLocation L) { GotoStmtBits.GotoLoc = L; }
getGotoLoc()2627   SourceLocation getGotoLoc() const { return GotoStmtBits.GotoLoc; }
setStarLoc(SourceLocation L)2628   void setStarLoc(SourceLocation L) { StarLoc = L; }
getStarLoc()2629   SourceLocation getStarLoc() const { return StarLoc; }
2630 
getTarget()2631   Expr *getTarget() { return reinterpret_cast<Expr *>(Target); }
getTarget()2632   const Expr *getTarget() const {
2633     return reinterpret_cast<const Expr *>(Target);
2634   }
setTarget(Expr * E)2635   void setTarget(Expr *E) { Target = reinterpret_cast<Stmt *>(E); }
2636 
2637   /// getConstantTarget - Returns the fixed target of this indirect
2638   /// goto, if one exists.
2639   LabelDecl *getConstantTarget();
getConstantTarget()2640   const LabelDecl *getConstantTarget() const {
2641     return const_cast<IndirectGotoStmt *>(this)->getConstantTarget();
2642   }
2643 
getBeginLoc()2644   SourceLocation getBeginLoc() const { return getGotoLoc(); }
getEndLoc()2645   SourceLocation getEndLoc() const LLVM_READONLY { return Target->getEndLoc(); }
2646 
classof(const Stmt * T)2647   static bool classof(const Stmt *T) {
2648     return T->getStmtClass() == IndirectGotoStmtClass;
2649   }
2650 
2651   // Iterators
children()2652   child_range children() { return child_range(&Target, &Target + 1); }
2653 
children()2654   const_child_range children() const {
2655     return const_child_range(&Target, &Target + 1);
2656   }
2657 };
2658 
2659 /// ContinueStmt - This represents a continue.
2660 class ContinueStmt : public Stmt {
2661 public:
ContinueStmt(SourceLocation CL)2662   ContinueStmt(SourceLocation CL) : Stmt(ContinueStmtClass) {
2663     setContinueLoc(CL);
2664   }
2665 
2666   /// Build an empty continue statement.
ContinueStmt(EmptyShell Empty)2667   explicit ContinueStmt(EmptyShell Empty) : Stmt(ContinueStmtClass, Empty) {}
2668 
getContinueLoc()2669   SourceLocation getContinueLoc() const { return ContinueStmtBits.ContinueLoc; }
setContinueLoc(SourceLocation L)2670   void setContinueLoc(SourceLocation L) { ContinueStmtBits.ContinueLoc = L; }
2671 
getBeginLoc()2672   SourceLocation getBeginLoc() const { return getContinueLoc(); }
getEndLoc()2673   SourceLocation getEndLoc() const { return getContinueLoc(); }
2674 
classof(const Stmt * T)2675   static bool classof(const Stmt *T) {
2676     return T->getStmtClass() == ContinueStmtClass;
2677   }
2678 
2679   // Iterators
children()2680   child_range children() {
2681     return child_range(child_iterator(), child_iterator());
2682   }
2683 
children()2684   const_child_range children() const {
2685     return const_child_range(const_child_iterator(), const_child_iterator());
2686   }
2687 };
2688 
2689 /// BreakStmt - This represents a break.
2690 class BreakStmt : public Stmt {
2691 public:
BreakStmt(SourceLocation BL)2692   BreakStmt(SourceLocation BL) : Stmt(BreakStmtClass) {
2693     setBreakLoc(BL);
2694   }
2695 
2696   /// Build an empty break statement.
BreakStmt(EmptyShell Empty)2697   explicit BreakStmt(EmptyShell Empty) : Stmt(BreakStmtClass, Empty) {}
2698 
getBreakLoc()2699   SourceLocation getBreakLoc() const { return BreakStmtBits.BreakLoc; }
setBreakLoc(SourceLocation L)2700   void setBreakLoc(SourceLocation L) { BreakStmtBits.BreakLoc = L; }
2701 
getBeginLoc()2702   SourceLocation getBeginLoc() const { return getBreakLoc(); }
getEndLoc()2703   SourceLocation getEndLoc() const { return getBreakLoc(); }
2704 
classof(const Stmt * T)2705   static bool classof(const Stmt *T) {
2706     return T->getStmtClass() == BreakStmtClass;
2707   }
2708 
2709   // Iterators
children()2710   child_range children() {
2711     return child_range(child_iterator(), child_iterator());
2712   }
2713 
children()2714   const_child_range children() const {
2715     return const_child_range(const_child_iterator(), const_child_iterator());
2716   }
2717 };
2718 
2719 /// ReturnStmt - This represents a return, optionally of an expression:
2720 ///   return;
2721 ///   return 4;
2722 ///
2723 /// Note that GCC allows return with no argument in a function declared to
2724 /// return a value, and it allows returning a value in functions declared to
2725 /// return void.  We explicitly model this in the AST, which means you can't
2726 /// depend on the return type of the function and the presence of an argument.
2727 class ReturnStmt final
2728     : public Stmt,
2729       private llvm::TrailingObjects<ReturnStmt, const VarDecl *> {
2730   friend TrailingObjects;
2731 
2732   /// The return expression.
2733   Stmt *RetExpr;
2734 
2735   // ReturnStmt is followed optionally by a trailing "const VarDecl *"
2736   // for the NRVO candidate. Present if and only if hasNRVOCandidate().
2737 
2738   /// True if this ReturnStmt has storage for an NRVO candidate.
hasNRVOCandidate()2739   bool hasNRVOCandidate() const { return ReturnStmtBits.HasNRVOCandidate; }
2740 
numTrailingObjects(OverloadToken<const VarDecl * >)2741   unsigned numTrailingObjects(OverloadToken<const VarDecl *>) const {
2742     return hasNRVOCandidate();
2743   }
2744 
2745   /// Build a return statement.
2746   ReturnStmt(SourceLocation RL, Expr *E, const VarDecl *NRVOCandidate);
2747 
2748   /// Build an empty return statement.
2749   explicit ReturnStmt(EmptyShell Empty, bool HasNRVOCandidate);
2750 
2751 public:
2752   /// Create a return statement.
2753   static ReturnStmt *Create(const ASTContext &Ctx, SourceLocation RL, Expr *E,
2754                             const VarDecl *NRVOCandidate);
2755 
2756   /// Create an empty return statement, optionally with
2757   /// storage for an NRVO candidate.
2758   static ReturnStmt *CreateEmpty(const ASTContext &Ctx, bool HasNRVOCandidate);
2759 
getRetValue()2760   Expr *getRetValue() { return reinterpret_cast<Expr *>(RetExpr); }
getRetValue()2761   const Expr *getRetValue() const { return reinterpret_cast<Expr *>(RetExpr); }
setRetValue(Expr * E)2762   void setRetValue(Expr *E) { RetExpr = reinterpret_cast<Stmt *>(E); }
2763 
2764   /// Retrieve the variable that might be used for the named return
2765   /// value optimization.
2766   ///
2767   /// The optimization itself can only be performed if the variable is
2768   /// also marked as an NRVO object.
getNRVOCandidate()2769   const VarDecl *getNRVOCandidate() const {
2770     return hasNRVOCandidate() ? *getTrailingObjects<const VarDecl *>()
2771                               : nullptr;
2772   }
2773 
2774   /// Set the variable that might be used for the named return value
2775   /// optimization. The return statement must have storage for it,
2776   /// which is the case if and only if hasNRVOCandidate() is true.
setNRVOCandidate(const VarDecl * Var)2777   void setNRVOCandidate(const VarDecl *Var) {
2778     assert(hasNRVOCandidate() &&
2779            "This return statement has no storage for an NRVO candidate!");
2780     *getTrailingObjects<const VarDecl *>() = Var;
2781   }
2782 
getReturnLoc()2783   SourceLocation getReturnLoc() const { return ReturnStmtBits.RetLoc; }
setReturnLoc(SourceLocation L)2784   void setReturnLoc(SourceLocation L) { ReturnStmtBits.RetLoc = L; }
2785 
getBeginLoc()2786   SourceLocation getBeginLoc() const { return getReturnLoc(); }
getEndLoc()2787   SourceLocation getEndLoc() const LLVM_READONLY {
2788     return RetExpr ? RetExpr->getEndLoc() : getReturnLoc();
2789   }
2790 
classof(const Stmt * T)2791   static bool classof(const Stmt *T) {
2792     return T->getStmtClass() == ReturnStmtClass;
2793   }
2794 
2795   // Iterators
children()2796   child_range children() {
2797     if (RetExpr)
2798       return child_range(&RetExpr, &RetExpr + 1);
2799     return child_range(child_iterator(), child_iterator());
2800   }
2801 
children()2802   const_child_range children() const {
2803     if (RetExpr)
2804       return const_child_range(&RetExpr, &RetExpr + 1);
2805     return const_child_range(const_child_iterator(), const_child_iterator());
2806   }
2807 };
2808 
2809 /// AsmStmt is the base class for GCCAsmStmt and MSAsmStmt.
2810 class AsmStmt : public Stmt {
2811 protected:
2812   friend class ASTStmtReader;
2813 
2814   SourceLocation AsmLoc;
2815 
2816   /// True if the assembly statement does not have any input or output
2817   /// operands.
2818   bool IsSimple;
2819 
2820   /// If true, treat this inline assembly as having side effects.
2821   /// This assembly statement should not be optimized, deleted or moved.
2822   bool IsVolatile;
2823 
2824   unsigned NumOutputs;
2825   unsigned NumInputs;
2826   unsigned NumClobbers;
2827 
2828   Stmt **Exprs = nullptr;
2829 
AsmStmt(StmtClass SC,SourceLocation asmloc,bool issimple,bool isvolatile,unsigned numoutputs,unsigned numinputs,unsigned numclobbers)2830   AsmStmt(StmtClass SC, SourceLocation asmloc, bool issimple, bool isvolatile,
2831           unsigned numoutputs, unsigned numinputs, unsigned numclobbers)
2832       : Stmt (SC), AsmLoc(asmloc), IsSimple(issimple), IsVolatile(isvolatile),
2833         NumOutputs(numoutputs), NumInputs(numinputs),
2834         NumClobbers(numclobbers) {}
2835 
2836 public:
2837   /// Build an empty inline-assembly statement.
AsmStmt(StmtClass SC,EmptyShell Empty)2838   explicit AsmStmt(StmtClass SC, EmptyShell Empty) : Stmt(SC, Empty) {}
2839 
getAsmLoc()2840   SourceLocation getAsmLoc() const { return AsmLoc; }
setAsmLoc(SourceLocation L)2841   void setAsmLoc(SourceLocation L) { AsmLoc = L; }
2842 
isSimple()2843   bool isSimple() const { return IsSimple; }
setSimple(bool V)2844   void setSimple(bool V) { IsSimple = V; }
2845 
isVolatile()2846   bool isVolatile() const { return IsVolatile; }
setVolatile(bool V)2847   void setVolatile(bool V) { IsVolatile = V; }
2848 
getBeginLoc()2849   SourceLocation getBeginLoc() const LLVM_READONLY { return {}; }
getEndLoc()2850   SourceLocation getEndLoc() const LLVM_READONLY { return {}; }
2851 
2852   //===--- Asm String Analysis ---===//
2853 
2854   /// Assemble final IR asm string.
2855   std::string generateAsmString(const ASTContext &C) const;
2856 
2857   //===--- Output operands ---===//
2858 
getNumOutputs()2859   unsigned getNumOutputs() const { return NumOutputs; }
2860 
2861   /// getOutputConstraint - Return the constraint string for the specified
2862   /// output operand.  All output constraints are known to be non-empty (either
2863   /// '=' or '+').
2864   StringRef getOutputConstraint(unsigned i) const;
2865 
2866   /// isOutputPlusConstraint - Return true if the specified output constraint
2867   /// is a "+" constraint (which is both an input and an output) or false if it
2868   /// is an "=" constraint (just an output).
isOutputPlusConstraint(unsigned i)2869   bool isOutputPlusConstraint(unsigned i) const {
2870     return getOutputConstraint(i)[0] == '+';
2871   }
2872 
2873   const Expr *getOutputExpr(unsigned i) const;
2874 
2875   /// getNumPlusOperands - Return the number of output operands that have a "+"
2876   /// constraint.
2877   unsigned getNumPlusOperands() const;
2878 
2879   //===--- Input operands ---===//
2880 
getNumInputs()2881   unsigned getNumInputs() const { return NumInputs; }
2882 
2883   /// getInputConstraint - Return the specified input constraint.  Unlike output
2884   /// constraints, these can be empty.
2885   StringRef getInputConstraint(unsigned i) const;
2886 
2887   const Expr *getInputExpr(unsigned i) const;
2888 
2889   //===--- Other ---===//
2890 
getNumClobbers()2891   unsigned getNumClobbers() const { return NumClobbers; }
2892   StringRef getClobber(unsigned i) const;
2893 
classof(const Stmt * T)2894   static bool classof(const Stmt *T) {
2895     return T->getStmtClass() == GCCAsmStmtClass ||
2896       T->getStmtClass() == MSAsmStmtClass;
2897   }
2898 
2899   // Input expr iterators.
2900 
2901   using inputs_iterator = ExprIterator;
2902   using const_inputs_iterator = ConstExprIterator;
2903   using inputs_range = llvm::iterator_range<inputs_iterator>;
2904   using inputs_const_range = llvm::iterator_range<const_inputs_iterator>;
2905 
begin_inputs()2906   inputs_iterator begin_inputs() {
2907     return &Exprs[0] + NumOutputs;
2908   }
2909 
end_inputs()2910   inputs_iterator end_inputs() {
2911     return &Exprs[0] + NumOutputs + NumInputs;
2912   }
2913 
inputs()2914   inputs_range inputs() { return inputs_range(begin_inputs(), end_inputs()); }
2915 
begin_inputs()2916   const_inputs_iterator begin_inputs() const {
2917     return &Exprs[0] + NumOutputs;
2918   }
2919 
end_inputs()2920   const_inputs_iterator end_inputs() const {
2921     return &Exprs[0] + NumOutputs + NumInputs;
2922   }
2923 
inputs()2924   inputs_const_range inputs() const {
2925     return inputs_const_range(begin_inputs(), end_inputs());
2926   }
2927 
2928   // Output expr iterators.
2929 
2930   using outputs_iterator = ExprIterator;
2931   using const_outputs_iterator = ConstExprIterator;
2932   using outputs_range = llvm::iterator_range<outputs_iterator>;
2933   using outputs_const_range = llvm::iterator_range<const_outputs_iterator>;
2934 
begin_outputs()2935   outputs_iterator begin_outputs() {
2936     return &Exprs[0];
2937   }
2938 
end_outputs()2939   outputs_iterator end_outputs() {
2940     return &Exprs[0] + NumOutputs;
2941   }
2942 
outputs()2943   outputs_range outputs() {
2944     return outputs_range(begin_outputs(), end_outputs());
2945   }
2946 
begin_outputs()2947   const_outputs_iterator begin_outputs() const {
2948     return &Exprs[0];
2949   }
2950 
end_outputs()2951   const_outputs_iterator end_outputs() const {
2952     return &Exprs[0] + NumOutputs;
2953   }
2954 
outputs()2955   outputs_const_range outputs() const {
2956     return outputs_const_range(begin_outputs(), end_outputs());
2957   }
2958 
children()2959   child_range children() {
2960     return child_range(&Exprs[0], &Exprs[0] + NumOutputs + NumInputs);
2961   }
2962 
children()2963   const_child_range children() const {
2964     return const_child_range(&Exprs[0], &Exprs[0] + NumOutputs + NumInputs);
2965   }
2966 };
2967 
2968 /// This represents a GCC inline-assembly statement extension.
2969 class GCCAsmStmt : public AsmStmt {
2970   friend class ASTStmtReader;
2971 
2972   SourceLocation RParenLoc;
2973   StringLiteral *AsmStr;
2974 
2975   // FIXME: If we wanted to, we could allocate all of these in one big array.
2976   StringLiteral **Constraints = nullptr;
2977   StringLiteral **Clobbers = nullptr;
2978   IdentifierInfo **Names = nullptr;
2979   unsigned NumLabels = 0;
2980 
2981 public:
2982   GCCAsmStmt(const ASTContext &C, SourceLocation asmloc, bool issimple,
2983              bool isvolatile, unsigned numoutputs, unsigned numinputs,
2984              IdentifierInfo **names, StringLiteral **constraints, Expr **exprs,
2985              StringLiteral *asmstr, unsigned numclobbers,
2986              StringLiteral **clobbers, unsigned numlabels,
2987              SourceLocation rparenloc);
2988 
2989   /// Build an empty inline-assembly statement.
GCCAsmStmt(EmptyShell Empty)2990   explicit GCCAsmStmt(EmptyShell Empty) : AsmStmt(GCCAsmStmtClass, Empty) {}
2991 
getRParenLoc()2992   SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)2993   void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2994 
2995   //===--- Asm String Analysis ---===//
2996 
getAsmString()2997   const StringLiteral *getAsmString() const { return AsmStr; }
getAsmString()2998   StringLiteral *getAsmString() { return AsmStr; }
setAsmString(StringLiteral * E)2999   void setAsmString(StringLiteral *E) { AsmStr = E; }
3000 
3001   /// AsmStringPiece - this is part of a decomposed asm string specification
3002   /// (for use with the AnalyzeAsmString function below).  An asm string is
3003   /// considered to be a concatenation of these parts.
3004   class AsmStringPiece {
3005   public:
3006     enum Kind {
3007       String,  // String in .ll asm string form, "$" -> "$$" and "%%" -> "%".
3008       Operand  // Operand reference, with optional modifier %c4.
3009     };
3010 
3011   private:
3012     Kind MyKind;
3013     std::string Str;
3014     unsigned OperandNo;
3015 
3016     // Source range for operand references.
3017     CharSourceRange Range;
3018 
3019   public:
AsmStringPiece(const std::string & S)3020     AsmStringPiece(const std::string &S) : MyKind(String), Str(S) {}
AsmStringPiece(unsigned OpNo,const std::string & S,SourceLocation Begin,SourceLocation End)3021     AsmStringPiece(unsigned OpNo, const std::string &S, SourceLocation Begin,
3022                    SourceLocation End)
3023         : MyKind(Operand), Str(S), OperandNo(OpNo),
3024           Range(CharSourceRange::getCharRange(Begin, End)) {}
3025 
isString()3026     bool isString() const { return MyKind == String; }
isOperand()3027     bool isOperand() const { return MyKind == Operand; }
3028 
getString()3029     const std::string &getString() const { return Str; }
3030 
getOperandNo()3031     unsigned getOperandNo() const {
3032       assert(isOperand());
3033       return OperandNo;
3034     }
3035 
getRange()3036     CharSourceRange getRange() const {
3037       assert(isOperand() && "Range is currently used only for Operands.");
3038       return Range;
3039     }
3040 
3041     /// getModifier - Get the modifier for this operand, if present.  This
3042     /// returns '\0' if there was no modifier.
3043     char getModifier() const;
3044   };
3045 
3046   /// AnalyzeAsmString - Analyze the asm string of the current asm, decomposing
3047   /// it into pieces.  If the asm string is erroneous, emit errors and return
3048   /// true, otherwise return false.  This handles canonicalization and
3049   /// translation of strings from GCC syntax to LLVM IR syntax, and handles
3050   //// flattening of named references like %[foo] to Operand AsmStringPiece's.
3051   unsigned AnalyzeAsmString(SmallVectorImpl<AsmStringPiece> &Pieces,
3052                             const ASTContext &C, unsigned &DiagOffs) const;
3053 
3054   /// Assemble final IR asm string.
3055   std::string generateAsmString(const ASTContext &C) const;
3056 
3057   //===--- Output operands ---===//
3058 
getOutputIdentifier(unsigned i)3059   IdentifierInfo *getOutputIdentifier(unsigned i) const { return Names[i]; }
3060 
getOutputName(unsigned i)3061   StringRef getOutputName(unsigned i) const {
3062     if (IdentifierInfo *II = getOutputIdentifier(i))
3063       return II->getName();
3064 
3065     return {};
3066   }
3067 
3068   StringRef getOutputConstraint(unsigned i) const;
3069 
getOutputConstraintLiteral(unsigned i)3070   const StringLiteral *getOutputConstraintLiteral(unsigned i) const {
3071     return Constraints[i];
3072   }
getOutputConstraintLiteral(unsigned i)3073   StringLiteral *getOutputConstraintLiteral(unsigned i) {
3074     return Constraints[i];
3075   }
3076 
3077   Expr *getOutputExpr(unsigned i);
3078 
getOutputExpr(unsigned i)3079   const Expr *getOutputExpr(unsigned i) const {
3080     return const_cast<GCCAsmStmt*>(this)->getOutputExpr(i);
3081   }
3082 
3083   //===--- Input operands ---===//
3084 
getInputIdentifier(unsigned i)3085   IdentifierInfo *getInputIdentifier(unsigned i) const {
3086     return Names[i + NumOutputs];
3087   }
3088 
getInputName(unsigned i)3089   StringRef getInputName(unsigned i) const {
3090     if (IdentifierInfo *II = getInputIdentifier(i))
3091       return II->getName();
3092 
3093     return {};
3094   }
3095 
3096   StringRef getInputConstraint(unsigned i) const;
3097 
getInputConstraintLiteral(unsigned i)3098   const StringLiteral *getInputConstraintLiteral(unsigned i) const {
3099     return Constraints[i + NumOutputs];
3100   }
getInputConstraintLiteral(unsigned i)3101   StringLiteral *getInputConstraintLiteral(unsigned i) {
3102     return Constraints[i + NumOutputs];
3103   }
3104 
3105   Expr *getInputExpr(unsigned i);
3106   void setInputExpr(unsigned i, Expr *E);
3107 
getInputExpr(unsigned i)3108   const Expr *getInputExpr(unsigned i) const {
3109     return const_cast<GCCAsmStmt*>(this)->getInputExpr(i);
3110   }
3111 
3112   //===--- Labels ---===//
3113 
isAsmGoto()3114   bool isAsmGoto() const {
3115     return NumLabels > 0;
3116   }
3117 
getNumLabels()3118   unsigned getNumLabels() const {
3119     return NumLabels;
3120   }
3121 
getLabelIdentifier(unsigned i)3122   IdentifierInfo *getLabelIdentifier(unsigned i) const {
3123     return Names[i + NumOutputs + NumInputs];
3124   }
3125 
3126   AddrLabelExpr *getLabelExpr(unsigned i) const;
3127   StringRef getLabelName(unsigned i) const;
3128   using labels_iterator = CastIterator<AddrLabelExpr>;
3129   using const_labels_iterator = ConstCastIterator<AddrLabelExpr>;
3130   using labels_range = llvm::iterator_range<labels_iterator>;
3131   using labels_const_range = llvm::iterator_range<const_labels_iterator>;
3132 
begin_labels()3133   labels_iterator begin_labels() {
3134     return &Exprs[0] + NumOutputs + NumInputs;
3135   }
3136 
end_labels()3137   labels_iterator end_labels() {
3138     return &Exprs[0] + NumOutputs + NumInputs + NumLabels;
3139   }
3140 
labels()3141   labels_range labels() {
3142     return labels_range(begin_labels(), end_labels());
3143   }
3144 
begin_labels()3145   const_labels_iterator begin_labels() const {
3146     return &Exprs[0] + NumOutputs + NumInputs;
3147   }
3148 
end_labels()3149   const_labels_iterator end_labels() const {
3150     return &Exprs[0] + NumOutputs + NumInputs + NumLabels;
3151   }
3152 
labels()3153   labels_const_range labels() const {
3154     return labels_const_range(begin_labels(), end_labels());
3155   }
3156 
3157 private:
3158   void setOutputsAndInputsAndClobbers(const ASTContext &C,
3159                                       IdentifierInfo **Names,
3160                                       StringLiteral **Constraints,
3161                                       Stmt **Exprs,
3162                                       unsigned NumOutputs,
3163                                       unsigned NumInputs,
3164                                       unsigned NumLabels,
3165                                       StringLiteral **Clobbers,
3166                                       unsigned NumClobbers);
3167 
3168 public:
3169   //===--- Other ---===//
3170 
3171   /// getNamedOperand - Given a symbolic operand reference like %[foo],
3172   /// translate this into a numeric value needed to reference the same operand.
3173   /// This returns -1 if the operand name is invalid.
3174   int getNamedOperand(StringRef SymbolicName) const;
3175 
3176   StringRef getClobber(unsigned i) const;
3177 
getClobberStringLiteral(unsigned i)3178   StringLiteral *getClobberStringLiteral(unsigned i) { return Clobbers[i]; }
getClobberStringLiteral(unsigned i)3179   const StringLiteral *getClobberStringLiteral(unsigned i) const {
3180     return Clobbers[i];
3181   }
3182 
getBeginLoc()3183   SourceLocation getBeginLoc() const LLVM_READONLY { return AsmLoc; }
getEndLoc()3184   SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
3185 
classof(const Stmt * T)3186   static bool classof(const Stmt *T) {
3187     return T->getStmtClass() == GCCAsmStmtClass;
3188   }
3189 };
3190 
3191 /// This represents a Microsoft inline-assembly statement extension.
3192 class MSAsmStmt : public AsmStmt {
3193   friend class ASTStmtReader;
3194 
3195   SourceLocation LBraceLoc, EndLoc;
3196   StringRef AsmStr;
3197 
3198   unsigned NumAsmToks = 0;
3199 
3200   Token *AsmToks = nullptr;
3201   StringRef *Constraints = nullptr;
3202   StringRef *Clobbers = nullptr;
3203 
3204 public:
3205   MSAsmStmt(const ASTContext &C, SourceLocation asmloc,
3206             SourceLocation lbraceloc, bool issimple, bool isvolatile,
3207             ArrayRef<Token> asmtoks, unsigned numoutputs, unsigned numinputs,
3208             ArrayRef<StringRef> constraints,
3209             ArrayRef<Expr*> exprs, StringRef asmstr,
3210             ArrayRef<StringRef> clobbers, SourceLocation endloc);
3211 
3212   /// Build an empty MS-style inline-assembly statement.
MSAsmStmt(EmptyShell Empty)3213   explicit MSAsmStmt(EmptyShell Empty) : AsmStmt(MSAsmStmtClass, Empty) {}
3214 
getLBraceLoc()3215   SourceLocation getLBraceLoc() const { return LBraceLoc; }
setLBraceLoc(SourceLocation L)3216   void setLBraceLoc(SourceLocation L) { LBraceLoc = L; }
getEndLoc()3217   SourceLocation getEndLoc() const { return EndLoc; }
setEndLoc(SourceLocation L)3218   void setEndLoc(SourceLocation L) { EndLoc = L; }
3219 
hasBraces()3220   bool hasBraces() const { return LBraceLoc.isValid(); }
3221 
getNumAsmToks()3222   unsigned getNumAsmToks() { return NumAsmToks; }
getAsmToks()3223   Token *getAsmToks() { return AsmToks; }
3224 
3225   //===--- Asm String Analysis ---===//
getAsmString()3226   StringRef getAsmString() const { return AsmStr; }
3227 
3228   /// Assemble final IR asm string.
3229   std::string generateAsmString(const ASTContext &C) const;
3230 
3231   //===--- Output operands ---===//
3232 
getOutputConstraint(unsigned i)3233   StringRef getOutputConstraint(unsigned i) const {
3234     assert(i < NumOutputs);
3235     return Constraints[i];
3236   }
3237 
3238   Expr *getOutputExpr(unsigned i);
3239 
getOutputExpr(unsigned i)3240   const Expr *getOutputExpr(unsigned i) const {
3241     return const_cast<MSAsmStmt*>(this)->getOutputExpr(i);
3242   }
3243 
3244   //===--- Input operands ---===//
3245 
getInputConstraint(unsigned i)3246   StringRef getInputConstraint(unsigned i) const {
3247     assert(i < NumInputs);
3248     return Constraints[i + NumOutputs];
3249   }
3250 
3251   Expr *getInputExpr(unsigned i);
3252   void setInputExpr(unsigned i, Expr *E);
3253 
getInputExpr(unsigned i)3254   const Expr *getInputExpr(unsigned i) const {
3255     return const_cast<MSAsmStmt*>(this)->getInputExpr(i);
3256   }
3257 
3258   //===--- Other ---===//
3259 
getAllConstraints()3260   ArrayRef<StringRef> getAllConstraints() const {
3261     return llvm::makeArrayRef(Constraints, NumInputs + NumOutputs);
3262   }
3263 
getClobbers()3264   ArrayRef<StringRef> getClobbers() const {
3265     return llvm::makeArrayRef(Clobbers, NumClobbers);
3266   }
3267 
getAllExprs()3268   ArrayRef<Expr*> getAllExprs() const {
3269     return llvm::makeArrayRef(reinterpret_cast<Expr**>(Exprs),
3270                               NumInputs + NumOutputs);
3271   }
3272 
getClobber(unsigned i)3273   StringRef getClobber(unsigned i) const { return getClobbers()[i]; }
3274 
3275 private:
3276   void initialize(const ASTContext &C, StringRef AsmString,
3277                   ArrayRef<Token> AsmToks, ArrayRef<StringRef> Constraints,
3278                   ArrayRef<Expr*> Exprs, ArrayRef<StringRef> Clobbers);
3279 
3280 public:
getBeginLoc()3281   SourceLocation getBeginLoc() const LLVM_READONLY { return AsmLoc; }
3282 
classof(const Stmt * T)3283   static bool classof(const Stmt *T) {
3284     return T->getStmtClass() == MSAsmStmtClass;
3285   }
3286 
children()3287   child_range children() {
3288     return child_range(&Exprs[0], &Exprs[NumInputs + NumOutputs]);
3289   }
3290 
children()3291   const_child_range children() const {
3292     return const_child_range(&Exprs[0], &Exprs[NumInputs + NumOutputs]);
3293   }
3294 };
3295 
3296 class SEHExceptStmt : public Stmt {
3297   friend class ASTReader;
3298   friend class ASTStmtReader;
3299 
3300   SourceLocation  Loc;
3301   Stmt *Children[2];
3302 
3303   enum { FILTER_EXPR, BLOCK };
3304 
3305   SEHExceptStmt(SourceLocation Loc, Expr *FilterExpr, Stmt *Block);
SEHExceptStmt(EmptyShell E)3306   explicit SEHExceptStmt(EmptyShell E) : Stmt(SEHExceptStmtClass, E) {}
3307 
3308 public:
3309   static SEHExceptStmt* Create(const ASTContext &C,
3310                                SourceLocation ExceptLoc,
3311                                Expr *FilterExpr,
3312                                Stmt *Block);
3313 
getBeginLoc()3314   SourceLocation getBeginLoc() const LLVM_READONLY { return getExceptLoc(); }
3315 
getExceptLoc()3316   SourceLocation getExceptLoc() const { return Loc; }
getEndLoc()3317   SourceLocation getEndLoc() const { return getBlock()->getEndLoc(); }
3318 
getFilterExpr()3319   Expr *getFilterExpr() const {
3320     return reinterpret_cast<Expr*>(Children[FILTER_EXPR]);
3321   }
3322 
getBlock()3323   CompoundStmt *getBlock() const {
3324     return cast<CompoundStmt>(Children[BLOCK]);
3325   }
3326 
children()3327   child_range children() {
3328     return child_range(Children, Children+2);
3329   }
3330 
children()3331   const_child_range children() const {
3332     return const_child_range(Children, Children + 2);
3333   }
3334 
classof(const Stmt * T)3335   static bool classof(const Stmt *T) {
3336     return T->getStmtClass() == SEHExceptStmtClass;
3337   }
3338 };
3339 
3340 class SEHFinallyStmt : public Stmt {
3341   friend class ASTReader;
3342   friend class ASTStmtReader;
3343 
3344   SourceLocation  Loc;
3345   Stmt *Block;
3346 
3347   SEHFinallyStmt(SourceLocation Loc, Stmt *Block);
SEHFinallyStmt(EmptyShell E)3348   explicit SEHFinallyStmt(EmptyShell E) : Stmt(SEHFinallyStmtClass, E) {}
3349 
3350 public:
3351   static SEHFinallyStmt* Create(const ASTContext &C,
3352                                 SourceLocation FinallyLoc,
3353                                 Stmt *Block);
3354 
getBeginLoc()3355   SourceLocation getBeginLoc() const LLVM_READONLY { return getFinallyLoc(); }
3356 
getFinallyLoc()3357   SourceLocation getFinallyLoc() const { return Loc; }
getEndLoc()3358   SourceLocation getEndLoc() const { return Block->getEndLoc(); }
3359 
getBlock()3360   CompoundStmt *getBlock() const { return cast<CompoundStmt>(Block); }
3361 
children()3362   child_range children() {
3363     return child_range(&Block,&Block+1);
3364   }
3365 
children()3366   const_child_range children() const {
3367     return const_child_range(&Block, &Block + 1);
3368   }
3369 
classof(const Stmt * T)3370   static bool classof(const Stmt *T) {
3371     return T->getStmtClass() == SEHFinallyStmtClass;
3372   }
3373 };
3374 
3375 class SEHTryStmt : public Stmt {
3376   friend class ASTReader;
3377   friend class ASTStmtReader;
3378 
3379   bool IsCXXTry;
3380   SourceLocation  TryLoc;
3381   Stmt *Children[2];
3382 
3383   enum { TRY = 0, HANDLER = 1 };
3384 
3385   SEHTryStmt(bool isCXXTry, // true if 'try' otherwise '__try'
3386              SourceLocation TryLoc,
3387              Stmt *TryBlock,
3388              Stmt *Handler);
3389 
SEHTryStmt(EmptyShell E)3390   explicit SEHTryStmt(EmptyShell E) : Stmt(SEHTryStmtClass, E) {}
3391 
3392 public:
3393   static SEHTryStmt* Create(const ASTContext &C, bool isCXXTry,
3394                             SourceLocation TryLoc, Stmt *TryBlock,
3395                             Stmt *Handler);
3396 
getBeginLoc()3397   SourceLocation getBeginLoc() const LLVM_READONLY { return getTryLoc(); }
3398 
getTryLoc()3399   SourceLocation getTryLoc() const { return TryLoc; }
getEndLoc()3400   SourceLocation getEndLoc() const { return Children[HANDLER]->getEndLoc(); }
3401 
getIsCXXTry()3402   bool getIsCXXTry() const { return IsCXXTry; }
3403 
getTryBlock()3404   CompoundStmt* getTryBlock() const {
3405     return cast<CompoundStmt>(Children[TRY]);
3406   }
3407 
getHandler()3408   Stmt *getHandler() const { return Children[HANDLER]; }
3409 
3410   /// Returns 0 if not defined
3411   SEHExceptStmt  *getExceptHandler() const;
3412   SEHFinallyStmt *getFinallyHandler() const;
3413 
children()3414   child_range children() {
3415     return child_range(Children, Children+2);
3416   }
3417 
children()3418   const_child_range children() const {
3419     return const_child_range(Children, Children + 2);
3420   }
3421 
classof(const Stmt * T)3422   static bool classof(const Stmt *T) {
3423     return T->getStmtClass() == SEHTryStmtClass;
3424   }
3425 };
3426 
3427 /// Represents a __leave statement.
3428 class SEHLeaveStmt : public Stmt {
3429   SourceLocation LeaveLoc;
3430 
3431 public:
SEHLeaveStmt(SourceLocation LL)3432   explicit SEHLeaveStmt(SourceLocation LL)
3433       : Stmt(SEHLeaveStmtClass), LeaveLoc(LL) {}
3434 
3435   /// Build an empty __leave statement.
SEHLeaveStmt(EmptyShell Empty)3436   explicit SEHLeaveStmt(EmptyShell Empty) : Stmt(SEHLeaveStmtClass, Empty) {}
3437 
getLeaveLoc()3438   SourceLocation getLeaveLoc() const { return LeaveLoc; }
setLeaveLoc(SourceLocation L)3439   void setLeaveLoc(SourceLocation L) { LeaveLoc = L; }
3440 
getBeginLoc()3441   SourceLocation getBeginLoc() const LLVM_READONLY { return LeaveLoc; }
getEndLoc()3442   SourceLocation getEndLoc() const LLVM_READONLY { return LeaveLoc; }
3443 
classof(const Stmt * T)3444   static bool classof(const Stmt *T) {
3445     return T->getStmtClass() == SEHLeaveStmtClass;
3446   }
3447 
3448   // Iterators
children()3449   child_range children() {
3450     return child_range(child_iterator(), child_iterator());
3451   }
3452 
children()3453   const_child_range children() const {
3454     return const_child_range(const_child_iterator(), const_child_iterator());
3455   }
3456 };
3457 
3458 /// This captures a statement into a function. For example, the following
3459 /// pragma annotated compound statement can be represented as a CapturedStmt,
3460 /// and this compound statement is the body of an anonymous outlined function.
3461 /// @code
3462 /// #pragma omp parallel
3463 /// {
3464 ///   compute();
3465 /// }
3466 /// @endcode
3467 class CapturedStmt : public Stmt {
3468 public:
3469   /// The different capture forms: by 'this', by reference, capture for
3470   /// variable-length array type etc.
3471   enum VariableCaptureKind {
3472     VCK_This,
3473     VCK_ByRef,
3474     VCK_ByCopy,
3475     VCK_VLAType,
3476   };
3477 
3478   /// Describes the capture of either a variable, or 'this', or
3479   /// variable-length array type.
3480   class Capture {
3481     llvm::PointerIntPair<VarDecl *, 2, VariableCaptureKind> VarAndKind;
3482     SourceLocation Loc;
3483 
3484   public:
3485     friend class ASTStmtReader;
3486 
3487     /// Create a new capture.
3488     ///
3489     /// \param Loc The source location associated with this capture.
3490     ///
3491     /// \param Kind The kind of capture (this, ByRef, ...).
3492     ///
3493     /// \param Var The variable being captured, or null if capturing this.
3494     Capture(SourceLocation Loc, VariableCaptureKind Kind,
3495             VarDecl *Var = nullptr);
3496 
3497     /// Determine the kind of capture.
3498     VariableCaptureKind getCaptureKind() const;
3499 
3500     /// Retrieve the source location at which the variable or 'this' was
3501     /// first used.
getLocation()3502     SourceLocation getLocation() const { return Loc; }
3503 
3504     /// Determine whether this capture handles the C++ 'this' pointer.
capturesThis()3505     bool capturesThis() const { return getCaptureKind() == VCK_This; }
3506 
3507     /// Determine whether this capture handles a variable (by reference).
capturesVariable()3508     bool capturesVariable() const { return getCaptureKind() == VCK_ByRef; }
3509 
3510     /// Determine whether this capture handles a variable by copy.
capturesVariableByCopy()3511     bool capturesVariableByCopy() const {
3512       return getCaptureKind() == VCK_ByCopy;
3513     }
3514 
3515     /// Determine whether this capture handles a variable-length array
3516     /// type.
capturesVariableArrayType()3517     bool capturesVariableArrayType() const {
3518       return getCaptureKind() == VCK_VLAType;
3519     }
3520 
3521     /// Retrieve the declaration of the variable being captured.
3522     ///
3523     /// This operation is only valid if this capture captures a variable.
3524     VarDecl *getCapturedVar() const;
3525   };
3526 
3527 private:
3528   /// The number of variable captured, including 'this'.
3529   unsigned NumCaptures;
3530 
3531   /// The pointer part is the implicit the outlined function and the
3532   /// int part is the captured region kind, 'CR_Default' etc.
3533   llvm::PointerIntPair<CapturedDecl *, 2, CapturedRegionKind> CapDeclAndKind;
3534 
3535   /// The record for captured variables, a RecordDecl or CXXRecordDecl.
3536   RecordDecl *TheRecordDecl = nullptr;
3537 
3538   /// Construct a captured statement.
3539   CapturedStmt(Stmt *S, CapturedRegionKind Kind, ArrayRef<Capture> Captures,
3540                ArrayRef<Expr *> CaptureInits, CapturedDecl *CD, RecordDecl *RD);
3541 
3542   /// Construct an empty captured statement.
3543   CapturedStmt(EmptyShell Empty, unsigned NumCaptures);
3544 
getStoredStmts()3545   Stmt **getStoredStmts() { return reinterpret_cast<Stmt **>(this + 1); }
3546 
getStoredStmts()3547   Stmt *const *getStoredStmts() const {
3548     return reinterpret_cast<Stmt *const *>(this + 1);
3549   }
3550 
3551   Capture *getStoredCaptures() const;
3552 
setCapturedStmt(Stmt * S)3553   void setCapturedStmt(Stmt *S) { getStoredStmts()[NumCaptures] = S; }
3554 
3555 public:
3556   friend class ASTStmtReader;
3557 
3558   static CapturedStmt *Create(const ASTContext &Context, Stmt *S,
3559                               CapturedRegionKind Kind,
3560                               ArrayRef<Capture> Captures,
3561                               ArrayRef<Expr *> CaptureInits,
3562                               CapturedDecl *CD, RecordDecl *RD);
3563 
3564   static CapturedStmt *CreateDeserialized(const ASTContext &Context,
3565                                           unsigned NumCaptures);
3566 
3567   /// Retrieve the statement being captured.
getCapturedStmt()3568   Stmt *getCapturedStmt() { return getStoredStmts()[NumCaptures]; }
getCapturedStmt()3569   const Stmt *getCapturedStmt() const { return getStoredStmts()[NumCaptures]; }
3570 
3571   /// Retrieve the outlined function declaration.
3572   CapturedDecl *getCapturedDecl();
3573   const CapturedDecl *getCapturedDecl() const;
3574 
3575   /// Set the outlined function declaration.
3576   void setCapturedDecl(CapturedDecl *D);
3577 
3578   /// Retrieve the captured region kind.
3579   CapturedRegionKind getCapturedRegionKind() const;
3580 
3581   /// Set the captured region kind.
3582   void setCapturedRegionKind(CapturedRegionKind Kind);
3583 
3584   /// Retrieve the record declaration for captured variables.
getCapturedRecordDecl()3585   const RecordDecl *getCapturedRecordDecl() const { return TheRecordDecl; }
3586 
3587   /// Set the record declaration for captured variables.
setCapturedRecordDecl(RecordDecl * D)3588   void setCapturedRecordDecl(RecordDecl *D) {
3589     assert(D && "null RecordDecl");
3590     TheRecordDecl = D;
3591   }
3592 
3593   /// True if this variable has been captured.
3594   bool capturesVariable(const VarDecl *Var) const;
3595 
3596   /// An iterator that walks over the captures.
3597   using capture_iterator = Capture *;
3598   using const_capture_iterator = const Capture *;
3599   using capture_range = llvm::iterator_range<capture_iterator>;
3600   using capture_const_range = llvm::iterator_range<const_capture_iterator>;
3601 
captures()3602   capture_range captures() {
3603     return capture_range(capture_begin(), capture_end());
3604   }
captures()3605   capture_const_range captures() const {
3606     return capture_const_range(capture_begin(), capture_end());
3607   }
3608 
3609   /// Retrieve an iterator pointing to the first capture.
capture_begin()3610   capture_iterator capture_begin() { return getStoredCaptures(); }
capture_begin()3611   const_capture_iterator capture_begin() const { return getStoredCaptures(); }
3612 
3613   /// Retrieve an iterator pointing past the end of the sequence of
3614   /// captures.
capture_end()3615   capture_iterator capture_end() const {
3616     return getStoredCaptures() + NumCaptures;
3617   }
3618 
3619   /// Retrieve the number of captures, including 'this'.
capture_size()3620   unsigned capture_size() const { return NumCaptures; }
3621 
3622   /// Iterator that walks over the capture initialization arguments.
3623   using capture_init_iterator = Expr **;
3624   using capture_init_range = llvm::iterator_range<capture_init_iterator>;
3625 
3626   /// Const iterator that walks over the capture initialization
3627   /// arguments.
3628   using const_capture_init_iterator = Expr *const *;
3629   using const_capture_init_range =
3630       llvm::iterator_range<const_capture_init_iterator>;
3631 
capture_inits()3632   capture_init_range capture_inits() {
3633     return capture_init_range(capture_init_begin(), capture_init_end());
3634   }
3635 
capture_inits()3636   const_capture_init_range capture_inits() const {
3637     return const_capture_init_range(capture_init_begin(), capture_init_end());
3638   }
3639 
3640   /// Retrieve the first initialization argument.
capture_init_begin()3641   capture_init_iterator capture_init_begin() {
3642     return reinterpret_cast<Expr **>(getStoredStmts());
3643   }
3644 
capture_init_begin()3645   const_capture_init_iterator capture_init_begin() const {
3646     return reinterpret_cast<Expr *const *>(getStoredStmts());
3647   }
3648 
3649   /// Retrieve the iterator pointing one past the last initialization
3650   /// argument.
capture_init_end()3651   capture_init_iterator capture_init_end() {
3652     return capture_init_begin() + NumCaptures;
3653   }
3654 
capture_init_end()3655   const_capture_init_iterator capture_init_end() const {
3656     return capture_init_begin() + NumCaptures;
3657   }
3658 
getBeginLoc()3659   SourceLocation getBeginLoc() const LLVM_READONLY {
3660     return getCapturedStmt()->getBeginLoc();
3661   }
3662 
getEndLoc()3663   SourceLocation getEndLoc() const LLVM_READONLY {
3664     return getCapturedStmt()->getEndLoc();
3665   }
3666 
getSourceRange()3667   SourceRange getSourceRange() const LLVM_READONLY {
3668     return getCapturedStmt()->getSourceRange();
3669   }
3670 
classof(const Stmt * T)3671   static bool classof(const Stmt *T) {
3672     return T->getStmtClass() == CapturedStmtClass;
3673   }
3674 
3675   child_range children();
3676 
3677   const_child_range children() const;
3678 };
3679 
3680 } // namespace clang
3681 
3682 #endif // LLVM_CLANG_AST_STMT_H
3683