Subversion Repositories QNX 8.QNX8 LLVM/Clang compiler suite

Rev

Details | Last modification | View Log | RSS feed

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