summaryrefslogtreecommitdiff
path: root/include/flang/AST/Decl.h
blob: a3248e3dc45a594f7a8ee8d8b1925a139178ddf7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
//===-- Decl.h - Declarations -----------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Classes for Fortran declarations.
//
//===----------------------------------------------------------------------===//

#ifndef FLANG_AST_DECL_H__
#define FLANG_AST_DECL_H__

#include "flang/AST/DeclarationName.h"
#include "flang/AST/Type.h"
#include "flang/AST/IntrinsicFunctions.h"
#include "flang/Basic/IdentifierTable.h"
#include "flang/Basic/SourceLocation.h"
#include "llvm/ADT/APSInt.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "flang/Basic/LLVM.h"

namespace llvm {
  class SourceMgr;
}

namespace flang {

class ASTContext;
class DeclSpec;
class IdentifierInfo;
class StoredDeclsMap;
class TypeLoc;
class BlockStmt;
class StorageSet;
class EquivalenceSet;
class CommonBlockSet;

// Decls
class DeclContext;
class TranslationUnitDecl;
class NamedDecl;
class TypeDecl;
class RecordDecl;
class ValueDecl;
class EnumConstantDecl;
class DeclaratorDecl;
class MainProgramDecl;
class FunctionDecl;
class SubroutineDecl;
class ModuleDecl;
class SubmoduleDecl;
class FieldDecl;
class VarDecl;
class FileScopeAsmDecl;

} // end flang namespace

namespace llvm {

// DeclContext* is only 4-byte aligned on 32-bit systems.
template<>
  class PointerLikeTypeTraits<flang::DeclContext*> {
  typedef flang::DeclContext* PT;
public:
  static inline void *getAsVoidPointer(PT P) { return P; }
  static inline PT getFromVoidPointer(void *P) {
    return static_cast<PT>(P);
  }
  enum { NumLowBitsAvailable = 2 };
};

} // end llvm namespace

namespace flang {

//===----------------------------------------------------------------------===//
/// Decl - Base class for declarations.
///
class Decl {
public:
  /// \brief Lists the kind of concrete classes of Decl.
  enum Kind {
#define DECL(DERIVED, BASE) DERIVED,
#define ABSTRACT_DECL(DECL)
#define DECL_RANGE(BASE, START, END) \
        first##BASE = START, last##BASE = END,
#define LAST_DECL_RANGE(BASE, START, END) \
        first##BASE = START, last##BASE = END
#include "flang/AST/DeclNodes.inc"
  };

private:
  friend class DeclContext;

  /// NextDeclInContext - The next declaration within the same lexical
  /// DeclContext. These pointers form the linked list that is traversed via
  /// DeclContext's decls_begin()/decls_end().
  Decl *NextDeclInContext;

  /// DeclCtx - The declaration context.
  DeclContext *DeclCtx;

  /// Loc - The location of this decl.
  SourceLocation Loc;

  /// DeclKind - The class of decl this is.
  unsigned DeclKind    : 8;

  /// InvalidDecl - This indicates a semantic error occurred.
  unsigned InvalidDecl : 1;

  /// HasAttrs - This indicates whether the decl has attributes or not.
  unsigned HasAttrs    : 1;

  /// Implicit - Whether this declaration was implicitly generated by
  /// the implementation rather than explicitly written by the user.
  unsigned Implicit    : 1;

  /// ImplicitType - Whether this declaration had the type that was
  /// set using the implicit typing rules rather than explicit ones.
  unsigned ImplicitType : 1;

protected:

  /// the kind of a sub declaration this is
  unsigned SubDeclKind : 4;

  unsigned CustomBoolAttr1 : 1;
  unsigned CustomBoolAttr2 : 1;
  unsigned CustomBoolAttr3 : 1;
  unsigned CustomBoolAttr4 : 1;

  Decl(Kind DK, DeclContext *DC, SourceLocation L)
    : NextDeclInContext(0), DeclCtx(DC), Loc(L), DeclKind(DK),
      InvalidDecl(false), HasAttrs(false), Implicit(false),
      ImplicitType(0),
      SubDeclKind(0) {}

  virtual ~Decl();

public:
  /// \brief Source range that this declaration covers.
  virtual SourceRange getSourceRange() const {
    return SourceRange(getLocation(), getLocation());
  }
  SourceLocation getLocStart() const { return getSourceRange().Start; }
  SourceLocation getLocEnd() const { return getSourceRange().End; }

  SourceLocation getLocation() const { return Loc; }
  void setLocation(SourceLocation L) { Loc = L; }

  Kind getKind() const { return static_cast<Kind>(DeclKind); }

  Decl *getNextDeclInContext() { return NextDeclInContext; }
  const Decl *getNextDeclInContext() const { return NextDeclInContext; }

  DeclContext *getDeclContext() { return DeclCtx; }
  const DeclContext *getDeclContext() const { return DeclCtx; }
  void setDeclContext(DeclContext *DC) { DeclCtx = DC; }

  TranslationUnitDecl *getTranslationUnitDecl();
  const TranslationUnitDecl *getTranslationUnitDecl() const {
    return const_cast<Decl*>(this)->getTranslationUnitDecl();
  }

  ASTContext &getASTContext() const;

  /// setInvalidDecl - Indicates the Decl had a semantic error. This
  /// allows for graceful error recovery.
  void setInvalidDecl(bool Invalid = true) { InvalidDecl = Invalid; }
  bool isInvalidDecl() const { return (bool)InvalidDecl; }

  /// isImplicit - Indicates whether the declaration was implicitly
  /// generated by the implementation. If false, this declaration
  /// was written explicitly in the source code.
  bool isImplicit() const { return Implicit; }
  void setImplicit(bool I = true) { Implicit = I; }

  /// isTypeImplicit - Indicates whether the type of this declaration
  /// set using the implicit typing rules.
  bool isTypeImplicit() const { return ImplicitType; }
  void setTypeImplicit(bool I = true) { ImplicitType = I; }

  void dump() const;
  void dump(llvm::raw_ostream &OS) const;

  // Implement isa/cast/dyncast/etc.
  static bool classof(const Decl *) { return true; }
  static DeclContext *castToDeclContext(const Decl *);
  static Decl *castFromDeclContext(const DeclContext *);
};

/// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
/// doing something to a specific decl.
class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
  const Decl *TheDecl;
  SourceLocation Loc;
  llvm::SourceMgr &SM;
  const char *Message;
public:
  PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
                       llvm::SourceMgr &sm, const char *Msg)
    : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}

  virtual void print(raw_ostream &OS) const;
};

class DeclContextLookupResult
  : public std::pair<NamedDecl**,NamedDecl**> {
public:
  DeclContextLookupResult(NamedDecl **I, NamedDecl **E)
    : std::pair<NamedDecl**,NamedDecl**>(I, E) {}
  DeclContextLookupResult()
    : std::pair<NamedDecl**,NamedDecl**>() {}

  using std::pair<NamedDecl**,NamedDecl**>::operator=;
};

class DeclContextLookupConstResult
  : public std::pair<NamedDecl*const*, NamedDecl*const*> {
public:
  DeclContextLookupConstResult(std::pair<NamedDecl**,NamedDecl**> R)
    : std::pair<NamedDecl*const*, NamedDecl*const*>(R) {}
  DeclContextLookupConstResult(NamedDecl * const *I, NamedDecl * const *E)
    : std::pair<NamedDecl*const*, NamedDecl*const*>(I, E) {}
  DeclContextLookupConstResult()
    : std::pair<NamedDecl*const*, NamedDecl*const*>() {}

  using std::pair<NamedDecl*const*,NamedDecl*const*>::operator=;
};

/// DeclContext - This is used only as base class of specific decl types that
/// can act as declaration contexts. These decls are (only the top classes
/// that directly derive from DeclContext are mentioned, not their subclasses):
///
///   TranslationUnitDecl
///   MainProgramDecl
///   FunctionDecl
///   SubroutineDecl
///   ModuleDecl
///   SubmoduleDecl
///   RecordDecl
///
class DeclContext {
  /// DeclKind - This indicates which class this is.
  unsigned DeclKind : 8;

  /// \brief Pointer to the data structure used to lookup declarations within
  /// this context.
  mutable StoredDeclsMap *LookupPtr;
protected:
  /// FirstDecl - The first declaration stored within this declaration
  /// context.
  mutable Decl *FirstDecl;

  /// LastDecl - The last declaration stored within this declaration
  /// context.
  mutable Decl *LastDecl;

  DeclContext(Decl::Kind K)
    : DeclKind(K), LookupPtr(0), FirstDecl(0), LastDecl(0) {}
public:
  ~DeclContext();

  DeclContext *getParent() {
    return Decl::castFromDeclContext(this)->getDeclContext();
  }
  const DeclContext *getParent() const {
    return const_cast<DeclContext*>(this)->getParent();
  }

  ASTContext &getParentASTContext() const {
    return Decl::castFromDeclContext(this)->getASTContext();
  }

  Decl::Kind getDeclKind() const {
    return static_cast<Decl::Kind>(DeclKind);
  }

  bool isTranslationUnit() const { return DeclKind == Decl::TranslationUnit; }
  bool isMainProgram() const { return DeclKind == Decl::MainProgram; }
  bool isFunction() const { return DeclKind == Decl::Function; }
  bool isModule() const { return DeclKind == Decl::Module; }
  bool isSubmodule() const { return DeclKind == Decl::Submodule; }
  bool isRecord() const { return DeclKind == Decl::Record; }

  /// \brief Retrieve the internal representation of the lookup structure.
  StoredDeclsMap *getLookupPtr() const { return LookupPtr; }

  /// decl_iterator - Iterates through the declarations stored within this
  /// context.
  class decl_iterator {
    /// Current - The current declaration.
    Decl *Current;

  public:
    typedef Decl*                     value_type;
    typedef Decl*                     reference;
    typedef Decl*                     pointer;
    typedef std::forward_iterator_tag iterator_category;
    typedef std::ptrdiff_t            difference_type;

    decl_iterator() : Current(0) { }
    explicit decl_iterator(Decl *C) : Current(C) { }

    reference operator*() const { return Current; }
    pointer operator->() const { return Current; }

    decl_iterator& operator++() {
      Current = Current->getNextDeclInContext();
      return *this;
    }

    decl_iterator operator++(int) {
      decl_iterator tmp(*this);
      ++(*this);
      return tmp;
    }

    friend bool operator==(decl_iterator x, decl_iterator y) {
      return x.Current == y.Current;
    }
    friend bool operator!=(decl_iterator x, decl_iterator y) {
      return x.Current != y.Current;
    }
  };

  /// decls_begin/decls_end - Iterate over the declarations stored in this
  /// context.
  decl_iterator decls_begin() const { return decl_iterator(FirstDecl); }
  decl_iterator decls_end() const   { return decl_iterator(); }
  bool decls_empty() const          { return !FirstDecl; }

  /// @brief Add the declaration D into this context.
  ///
  /// This routine should be invoked when the declaration D has first been
  /// declared, to place D into the context where it was (lexically)
  /// defined. Every declaration must be added to one (and only one!) context,
  /// where it can be visited via [decls_begin(), decls_end()). Once a
  /// declaration has been added to its lexical context, the corresponding
  /// DeclContext owns the declaration.
  ///
  /// If D is also a NamedDecl, it will be made visible within its semantic
  /// context via makeDeclVisibleInContext.
  void addDecl(Decl *D);

  /// @brief Removes a declaration from this context.
  void removeDecl(Decl *D);

  /// lookup_iterator - An iterator that provides access to the results of
  /// looking up a name within this context.
  typedef NamedDecl **lookup_iterator;

  /// lookup_const_iterator - An iterator that provides non-mutable access to
  /// the results of lookup up a name within this context.
  typedef NamedDecl * const *lookup_const_iterator;

  typedef DeclContextLookupResult lookup_result;
  typedef DeclContextLookupConstResult lookup_const_result;

  /// lookup - Find the declarations (if any) with the given Name in this
  /// context. Returns a range of iterators that contains all of the
  /// declarations with this name, with object, function, member, and enumerator
  /// names preceding any tag name. Note that this routine will not look into
  /// parent contexts.
  lookup_result lookup(DeclarationName Name);
  lookup_const_result lookup(DeclarationName Name) const {
    return const_cast<DeclContext*>(this)->lookup(Name);
  }

  /// @brief Makes a declaration visible within this context.
  ///
  /// This routine makes the declaration D visible to name lookup within this
  /// context and, if this is a transparent context, within its parent contexts
  /// up to the first enclosing non-transparent context. Making a declaration
  /// visible within a context does not transfer ownership of a declaration, and
  /// a declaration can be visible in many contexts that aren't its lexical
  /// context.
  void makeDeclVisibleInContext(NamedDecl *D);

  static bool classof(const Decl *D);
  static bool classof(const DeclContext *D) { return true; }
#define DECL(NAME, BASE)
#define DECL_CONTEXT(NAME) \
  static bool classof(const NAME##Decl *D) { return true; }
#include "flang/AST/DeclNodes.inc"

private:
  StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
  void buildLookup(DeclContext *DCtx);
  void makeDeclVisibleInContextImpl(NamedDecl *D);
};

/// \brief A container of type source information.
///
/// A client can read the relevant info using TypeLoc wrappers, e.g:
/// @code
/// TypeLoc TL = TypeSourceInfo->getTypeLoc();
/// if (PointerLoc *PL = dyn_cast<PointerLoc>(&TL))
///   PL->getStarLoc().print(OS, SrcMgr);
/// @endcode
///
class TypeSourceInfo {
  QualType Ty;
  // Contains a memory block after the class, used for type source information,
  // allocated by ASTContext.
  friend class ASTContext;
  TypeSourceInfo(QualType ty) : Ty(ty) { }
public:
  /// \brief Return the type wrapped by this type source info.
  QualType getType() const { return Ty; }
#if 0
  /// \brief Return the TypeLoc wrapper for the type source info.
  TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
#endif
};

/// TranslationUnitDecl - The top declaration context.
class TranslationUnitDecl : public Decl, public DeclContext {
  ASTContext &Ctx;

  explicit TranslationUnitDecl(ASTContext &ctx)
    : Decl(TranslationUnit, 0, SourceLocation()),
      DeclContext(TranslationUnit), Ctx(ctx) {}
public:
  ASTContext &getASTContext() const { return Ctx; }

  static TranslationUnitDecl *Create(ASTContext &C);

  // Implement isa/cast/dyncast/etc.
  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  static bool classof(const TranslationUnitDecl *D) { return true; }
  static bool classofKind(Kind K) { return K == TranslationUnit; }
  static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
    return static_cast<DeclContext*>(const_cast<TranslationUnitDecl*>(D));
  }
  static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
    return static_cast<TranslationUnitDecl*>(const_cast<DeclContext*>(DC));
  }
};

/// NamedDecl - This represents a decl with a name.
class NamedDecl : public Decl {
  /// Name - The name of this declaration, which is typically a normal
  /// identifier.
  DeclarationName Name;
  friend class ASTContext;
  friend class DeclContext;
protected:
  NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
    : Decl(DK, DC, L), Name(N) {}
public:
  /// getIdentifier - Get the identifier that names this declaration, if there
  /// is one.
  IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }

  /// getName - Get the name of identifier for this declaration as a StringRef.
  /// This requires that the declaration have a name and that it be a simple
  /// identifier.
  StringRef getName() const {
    assert(Name.isIdentifier() && "Name is not a simple identifier");
    return getIdentifier() ? getIdentifier()->getName() : "";
  }

  /// getDeclName - Get the actual, stored name of the declaration.
  DeclarationName getDeclName() const { return Name; }

  /// \brief Set the name of this declaration.
  void setDeclName(DeclarationName N) { Name = N; }

  // Implement isa/cast/dyncast/etc.
  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  static bool classof(const NamedDecl *D) { return true; }
  static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
};

/// TypeDecl - Represents a declaration of a type.
class TypeDecl : public NamedDecl {
  /// TypeForDecl - This indicates the Type object that represents this
  /// TypeDecl. It is a cache maintained by ASTContext::getTagDeclType.
  mutable const Type *TypeForDecl;

  /// LocStart - The start of the source range for this declaration.
  SourceLocation LocStart;

  friend class ASTContext;
  friend class DeclContext;
  friend class RecordDecl;
  friend class TagType;
protected:
  TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id,
           SourceLocation StartL = SourceLocation())
    : NamedDecl(DK, DC, L, Id), TypeForDecl(0), LocStart(StartL) {}

public:
  // Low-level accessor
  const Type *getTypeForDecl() const { return TypeForDecl; }
  void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }

  SourceLocation getLocStart() const { return LocStart; }
  void setLocStart(SourceLocation L) { LocStart = L; }

  virtual SourceRange getSourceRange() const {
    if (LocStart.isValid())
      return SourceRange(LocStart, getLocation());
    else
      return SourceRange(getLocation(), getLocation());
  }

  // Implement isa/cast/dyncast/etc.
  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  static bool classof(const TypeDecl *D) { return true; }
  static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
};

/// RecordDecl - Represents a structure. This decl will be marked invalid if
/// *any* members are invalid.
class RecordDecl : public TypeDecl, public DeclContext {
  /// IsDefinition - True if this is a definition ("struct foo {};"), false if
  /// it is a declaration ("struct foo;").
  bool IsDefinition : 1;

  /// IsBeingDefined - True if this is currently being defined.
  bool IsBeingDefined : 1;

  /// IsSequence - True if the SEQUENCE statement was used.
  bool IsSequence : 1;

  friend class DeclContext;
protected:
  RecordDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc,
             const IdentifierInfo *Id, RecordDecl *PrevDecl)
    : TypeDecl(DK, DC, IdLoc, Id), DeclContext(DK) {
    IsDefinition = false;
    IsBeingDefined = false;
    IsSequence = false;
  }
public:
  static RecordDecl *Create(const ASTContext &C, DeclContext *DC,
                            SourceLocation StartLoc, SourceLocation IdLoc,
                            const IdentifierInfo *Id, RecordDecl *PrevDecl = 0);

  /// getOuterLocStart - Return SourceLocation representing start of source range taking
  /// into account any outer template declarations.
  virtual SourceRange getSourceRange() const {
    if (LocStart.isValid())
      return SourceRange(LocStart, getLocation());
    else
      return SourceRange(getLocation(), getLocation());
  }

  // FIXME: Could be more than just 'this'.
  virtual RecordDecl *getCanonicalDecl() { return this; }
  const RecordDecl *getCanonicalDecl() const {
    return const_cast<RecordDecl*>(this)->getCanonicalDecl();
  }

  /// completeDefinition - Notes that the definition of this type is now
  /// complete.
  virtual void completeDefinition() {
    assert(!isDefinition() && "Cannot redefine record!");
    IsDefinition = true;
    IsBeingDefined = false;
  }

  /// isDefinition - Return true if this decl has its body specified.
  bool isDefinition() const { return IsDefinition; }

  /// isBeingDefined - Return true if this decl is currently being defined.
  bool isBeingDefined() const { return IsBeingDefined; }

  /// @brief Starts the definition of this struct declaration.
  ///
  /// This method should be invoked at the beginning of the definition of this
  /// struct declaration. It will set the struct type into a state where it is
  /// in the process of being defined.
  void startDefinition() { IsBeingDefined = true; }

  /// getDefinition - Returns the RecordDecl that actually defines this struct.
  /// When determining whether or not a struct is completely defined, one should
  /// use this method as opposed to 'isDefinition'. 'isDefinition' indicates
  /// whether or not a specific RecordDecl is defining declaration, not whether
  /// or not the struct type is defined. This method returns NULL if there is
  /// no RecordDecl that defines the struct.
  RecordDecl *getDefinition() const {
    return isDefinition() ? const_cast<RecordDecl*>(this) : 0;
  }

  void setDefinition(bool V) { IsDefinition = V; }

  bool isSequence() const {
    return IsSequence;
  }

  bool setIsSequence(bool V) { IsSequence = V; }

  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  static bool classof(const RecordDecl *D) { return true; }
  static bool classofKind(Kind K) { return K == Record; }

  static DeclContext *castToDeclContext(const RecordDecl *D) {
    return static_cast<DeclContext*>(const_cast<RecordDecl*>(D));
  }
  static RecordDecl *castFromDeclContext(const DeclContext *DC) {
    return static_cast<RecordDecl*>(const_cast<DeclContext*>(DC));
  }
};

/// ValueDecl - Represent the declaration of a variable (in which case it is an
/// lvalue), a function (in which case it is a function designator), or an enum
/// constant.
class ValueDecl : public NamedDecl {
  QualType DeclType;
protected:
  ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
            DeclarationName N, QualType T)
    : NamedDecl(DK, DC, L, N), DeclType(T) {}
public:

  QualType getType() const { return DeclType; }

  void setType(QualType newType) {
    DeclType = newType;
    setTypeImplicit(false);
  }

  // Implement isa/cast/dyncast/etc.
  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  static bool classof(const ValueDecl *D) { return true; }
  static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
};

/// EnumConstantDecl - An instance of this object exists for each enum constant
/// that is defined.
class EnumConstantDecl : public ValueDecl {
  Expr *Init;                   // An integer constant expression.
  llvm::APSInt Val;             // The value.
protected:
  EnumConstantDecl(DeclContext *DC, SourceLocation L,
                   IdentifierInfo *Id, QualType T, Expr *E,
                   const llvm::APSInt &V)
    : ValueDecl(EnumConstant, DC, L, Id, T), Init(E), Val(V) {}
public:
  static EnumConstantDecl *Create(ASTContext &C, DeclContext *DC,
                                  SourceLocation L, IdentifierInfo *Id,
                                  QualType T, Expr *E,
                                  const llvm::APSInt &V);

  const Expr *getInitExpr() const { return Init; }
  Expr *getInitExpr() { return Init; }
  const llvm::APSInt &getInitVal() const { return Val; }

  void setInitExpr(Expr *E) { Init = E; }
  void setInitVal(const llvm::APSInt &V) { Val = V; }

  SourceRange getSourceRange() const;

  // Implement isa/cast/dyncast/etc.
  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  static bool classof(const EnumConstantDecl *D) { return true; }
  static bool classofKind(Kind K) { return K == EnumConstant; }
};

/// \brief Represents a ValueDecl that came out of a declarator.
class DeclaratorDecl : public ValueDecl {
protected:
  DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
                 DeclarationName N, QualType T)
    : ValueDecl(DK, DC, L, N, T) {
  }
public:
  virtual SourceRange getSourceRange() const {
    // TODO
    return SourceRange();
  }

  // Implement isa/cast/dyncast/etc.
  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  static bool classof(const DeclaratorDecl *D) { return true; }
  static bool classofKind(Kind K) {
    return K >= firstDeclarator && K <= lastDeclarator;
  }
};

class MainProgramDecl : public DeclaratorDecl, public DeclContext {
  Stmt *Body;

  MainProgramDecl(DeclContext *DC, const DeclarationNameInfo &NameInfo)
    : DeclaratorDecl(MainProgram, DC, NameInfo.getLoc(), NameInfo.getName(),
                     QualType()),
      DeclContext(MainProgram),
      Body(nullptr) {}
public:
  static MainProgramDecl *Create(ASTContext &C, DeclContext *DC,
                                 const DeclarationNameInfo &NameInfo);

  void setBody(Stmt *S);
  Stmt *getBody() const { return Body; }

  // Implement isa/cast/dyncast/etc.
  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  static bool classof(const MainProgramDecl *D) { return true; }
  static bool classofKind(Kind K) { return K == MainProgram; }
  static DeclContext *castToDeclContext(const MainProgramDecl *D) {
    return static_cast<DeclContext *>(const_cast<MainProgramDecl*>(D));
  }
  static MainProgramDecl *castFromDeclContext(const DeclContext *DC) {
    return static_cast<MainProgramDecl *>(const_cast<DeclContext*>(DC));
  }
};

class FunctionDecl : public DeclaratorDecl, public DeclContext {
public:
  enum FunctionKind {
    NormalFunction,
    StatementFunction,
    Subroutine,
    External,
    ExternalArgument
  };

  enum Attributes {
    NoAttributes = 0,
    Recursive = 1
  };

private:
  unsigned ArgumentCount;
  VarDecl **Arguments;
  VarDecl *Result;
  llvm::PointerUnion<Stmt*,Expr*> Body;

  FunctionDecl(Kind DK, FunctionKind FK, DeclContext *DC,
               const DeclarationNameInfo &NameInfo, QualType T,
               int Attr)
    : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T),
      DeclContext(DK), ArgumentCount(0), Arguments(nullptr),
      Body((Stmt*)nullptr), Result(nullptr) {
      CustomBoolAttr1 = (Attr & Recursive) != 0;
      SubDeclKind = FK;
    }
public:
  static FunctionDecl *Create(ASTContext &C, FunctionKind FK,
                              DeclContext *DC,
                              const DeclarationNameInfo &NameInfo,
                              QualType ReturnType,
                              int Attr = NoAttributes);

  bool isNormalFunction() const { return SubDeclKind == NormalFunction; }
  bool isStatementFunction() const { return SubDeclKind == StatementFunction; }
  bool isSubroutine() const { return SubDeclKind == Subroutine; }
  bool isExternal() const {
    return SubDeclKind == External || SubDeclKind == ExternalArgument;
  }
  bool isExternalArgument() const {
    return SubDeclKind == ExternalArgument;
  }

  bool isRecursive() const { return CustomBoolAttr1 != 0; }

  ArrayRef<VarDecl*> getArguments() const {
    return ArrayRef<VarDecl*>(Arguments, ArgumentCount);
  }
  void setArguments(ASTContext &C, ArrayRef<VarDecl*> ArgumentList);

  /// Returns the variable that will be returned by this function
  VarDecl *getResult() const {
    return Result;
  }
  bool hasResult() const {
    return Result != nullptr;
  }
  void setResult(VarDecl *VD);

  void setBody(Stmt *S);
  void setBody(Expr *E);
  Stmt *getBody() const { return Body.get<Stmt*>(); }
  Expr *getBodyExpr() const { return Body.get<Expr*>(); }

  // Implement isa/cast/dyncast/etc.
  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  static bool classof(const FunctionDecl *D) { return true; }
  static bool classofKind(Kind K) { return K == Function; }
  static DeclContext *castToDeclContext(const FunctionDecl *D) {
    return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
  }
  static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
    return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
  }
};

/// SelfDecl - References a given declaration
/// in the context of the given declaration.
class SelfDecl : public DeclaratorDecl {
  DeclaratorDecl *SelfD;

  SelfDecl(DeclContext *DC, DeclaratorDecl *D)
    : DeclaratorDecl(Self, DC, D->getLocation(),
                     D->getIdentifier(),
                     D->getType()),
      SelfD(D) {}

public:
  static SelfDecl *Create(ASTContext &C, DeclContext *DC,
                          DeclaratorDecl *Self);

  DeclaratorDecl *getSelf() const {
    return SelfD;
  }

  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  static bool classof(const SelfDecl *D) { return true; }
  static bool classofKind(Kind K) { return K == Self; }
};

/// Represents an intrinsic function declaration.
class IntrinsicFunctionDecl : public DeclaratorDecl {
  intrinsic::FunctionKind Function;

  IntrinsicFunctionDecl(Kind DK, DeclContext *DC,
                        SourceLocation IDLoc, const IdentifierInfo *ID,
                        QualType T, intrinsic::FunctionKind Func)
    : DeclaratorDecl(DK, DC, IDLoc, ID, T),
      Function(Func) {
  }
public:
  static IntrinsicFunctionDecl *Create(ASTContext &C, DeclContext *DC,
                                       SourceLocation IDLoc, const IdentifierInfo *ID,
                                       QualType T, intrinsic::FunctionKind Function);

  intrinsic::FunctionKind getFunction() const {
    return Function;
  }

  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  static bool classof(const IntrinsicFunctionDecl *D) { return true; }
  static bool classofKind(Kind K) { return K == IntrinsicFunction; }
};

class ModuleDecl : public DeclaratorDecl, public DeclContext {
protected:
  ModuleDecl(Kind DK, DeclContext *DC, const DeclarationNameInfo &NameInfo,
             QualType T)
    : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T),
      DeclContext(DK) {
  }
public:

  // Implement isa/cast/dyncast/etc.
  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  static bool classof(const ModuleDecl *D) { return true; }
  static bool classofKind(Kind K) { return K == Module; }
  static DeclContext *castToDeclContext(const ModuleDecl *D) {
    return static_cast<DeclContext *>(const_cast<ModuleDecl*>(D));
  }
  static ModuleDecl *castFromDeclContext(const DeclContext *DC) {
    return static_cast<ModuleDecl *>(const_cast<DeclContext*>(DC));
  }
};

class SubmoduleDecl : public DeclaratorDecl, public DeclContext {
protected:
  SubmoduleDecl(Kind DK, DeclContext *DC, const DeclarationNameInfo &NameInfo,
                QualType T)
    : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T),
      DeclContext(DK) {
  }
public:

  // Implement isa/cast/dyncast/etc.
  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  static bool classof(const SubmoduleDecl *D) { return true; }
  static bool classofKind(Kind K) { return K == Submodule; }
  static DeclContext *castToDeclContext(const SubmoduleDecl *D) {
    return static_cast<DeclContext *>(const_cast<SubmoduleDecl*>(D));
  }
  static SubmoduleDecl *castFromDeclContext(const DeclContext *DC) {
    return static_cast<SubmoduleDecl *>(const_cast<DeclContext*>(DC));
  }
};

/// FieldDecl - An instance of this class is created by Sema::ActOnField to
/// represent a member of a struct.
class FieldDecl : public DeclaratorDecl {
  unsigned Idx;
protected:
  FieldDecl(Kind DK, DeclContext *DC, SourceLocation IdLoc, const IdentifierInfo *Id,
            QualType T)
    : DeclaratorDecl(DK, DC, IdLoc, Id, T), Idx(0) {}
public:
  static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
                           SourceLocation IdLoc, const IdentifierInfo *Id, QualType T);

  /// getParent - Returns the parent of this field declaration, which is the
  /// struct in which this method is defined.
  const RecordDecl *getParent() const {
    return RecordDecl::castFromDeclContext(getDeclContext());
  }
  RecordDecl *getParent() {
    return RecordDecl::castFromDeclContext(getDeclContext());
  }

  unsigned getIndex() const {
    return Idx;
  }
  void setIndex(unsigned I) {
    Idx = I;
  }

  SourceRange getSourceRange() const {
    return DeclaratorDecl::getSourceRange();
  }

  // Implement isa/cast/dyncast/etc.
  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  static bool classof(const FieldDecl *D) { return true; }
  static bool classofKind(Kind K) { return K == Field; }
};

/// VarDecl - An instance of this class is created to represent a variable
/// declaration or definition.
/// FIXME: document var kinds
class VarDecl : public DeclaratorDecl {
public:
  enum VarKind {
    UnusedSymbol = 0,
    LocalVariable,
    FunctionArgument,
    ParameterVariable,
    FunctionResult
  };
private:
  /// \brief The initializer for this variable.
  mutable Expr *Init;

  /// \brief The storage set for this variable.
  StorageSet *Storage;

  friend class ASTContext;  // ASTContext creates these.

protected:
  VarDecl(Kind DK, DeclContext *DC, SourceLocation IdLoc, const IdentifierInfo *ID,
          QualType T)
    : DeclaratorDecl(DK, DC, IdLoc, ID, T), Init(nullptr), Storage(nullptr) {}

public:
  static VarDecl *Create(ASTContext &C, DeclContext *DC,
                         SourceLocation IDLoc, const IdentifierInfo *ID,
                         QualType T);
  static VarDecl *CreateArgument(ASTContext &C, DeclContext *DC,
                                 SourceLocation IDLoc, const IdentifierInfo *ID);
  static VarDecl *CreateFunctionResult(ASTContext &C, DeclContext *DC,
                                       SourceLocation IDLoc, const IdentifierInfo *ID);

  void Profile(llvm::FoldingSetNodeID &ID) {
    Profile(ID, getIdentifier());
  }
  static void Profile(llvm::FoldingSetNodeID &ID, const IdentifierInfo *Info) {
    ID.AddPointer(Info);
  }

  inline Expr *getInit() const { return Init; }
  bool hasInit() const {
    return Init != nullptr;
  }
  void setInit(Expr *E) const;

  inline bool isUnusedSymbol() const {
    return SubDeclKind == UnusedSymbol;
  }
  inline bool isLocalVariable() const { return SubDeclKind == LocalVariable; }
  inline bool isParameter() const { return SubDeclKind == ParameterVariable; }
  inline bool isArgument() const { return SubDeclKind == FunctionArgument; }
  inline bool isFunctionResult() const { return SubDeclKind == FunctionResult; }

  void MutateIntoParameter(Expr *Value);
  void MarkUsedAsVariable (SourceLocation Loc);

  StorageSet *getStorageSet() const { return Storage; }
  bool hasStorageSet() const {
    return Storage != nullptr;
  }
  void setStorageSet(StorageSet *S) {
    Storage = S;
  }

  // Implement isa/cast/dyncast/etc.
  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  static bool classof(const VarDecl *D) { return true; }
  static bool classofKind(Kind K) { return K == Var; }
};

class FileScopeAsmDecl : public Decl {
  FileScopeAsmDecl(DeclContext *DC, SourceLocation StartL, SourceLocation EndL)
    : Decl(FileScopeAsm, DC, StartL) {}
public:
  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  static bool classof(const FileScopeAsmDecl *D) { return true; }
  static bool classofKind(Kind K) { return K == FileScopeAsm; }
};

class CommonBlockDecl : public NamedDecl {
  CommonBlockSet *Set;

  CommonBlockDecl(DeclContext *DC,
                  SourceLocation IDLoc, const IdentifierInfo *IDInfo)
    : NamedDecl(CommonBlock, DC, IDLoc, DeclarationName(IDInfo)),
      Set(nullptr) {}
public:
  static CommonBlockDecl *Create(ASTContext &C, DeclContext *DC,
                                 SourceLocation IDLoc, const IdentifierInfo *IDInfo);

  CommonBlockSet *getStorageSet() const {
    return Set;
  }
  void setStorageSet(CommonBlockSet *S) {
    Set = S;
  }

  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  static bool classof(const CommonBlockDecl *D) { return true; }
  static bool classofKind(Kind K) { return K == CommonBlock; }
};

static inline llvm::raw_ostream &operator<<(llvm::raw_ostream &O,
                                            const VarDecl &V) {
  return O << V.getIdentifier()->getName();
}

// Specialization selected when ToTy is not a known subclass of DeclContext.
template <class ToTy,
          bool IsKnownSubtype = ::llvm::is_base_of< DeclContext, ToTy>::value>
struct cast_convert_decl_context {
  static const ToTy *doit(const DeclContext *Val) {
    return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
  }

  static ToTy *doit(DeclContext *Val) {
    return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
  }
};

// Specialization selected when ToTy is a known subclass of DeclContext.
template <class ToTy>
struct cast_convert_decl_context<ToTy, true> {
  static const ToTy *doit(const DeclContext *Val) {
    return static_cast<const ToTy*>(Val);
  }

  static ToTy *doit(DeclContext *Val) {
    return static_cast<ToTy*>(Val);
  }
};

} // end flang namespace

namespace llvm {

/// isa<T>(DeclContext*)
template <typename To>
struct isa_impl<To, ::flang::DeclContext> {
  static bool doit(const ::flang::DeclContext &Val) {
    return To::classofKind(Val.getDeclKind());
  }
};

/// cast<T>(DeclContext*)
template<class ToTy>
struct cast_convert_val<ToTy,
                        const ::flang::DeclContext,const ::flang::DeclContext> {
  static const ToTy &doit(const ::flang::DeclContext &Val) {
    return *::flang::cast_convert_decl_context<ToTy>::doit(&Val);
  }
};
template<class ToTy>
struct cast_convert_val<ToTy, ::flang::DeclContext, ::flang::DeclContext> {
  static ToTy &doit(::flang::DeclContext &Val) {
    return *::flang::cast_convert_decl_context<ToTy>::doit(&Val);
  }
};
template<class ToTy>
struct cast_convert_val<ToTy,
                     const ::flang::DeclContext*, const ::flang::DeclContext*> {
  static const ToTy *doit(const ::flang::DeclContext *Val) {
    return ::flang::cast_convert_decl_context<ToTy>::doit(Val);
  }
};
template<class ToTy>
struct cast_convert_val<ToTy, ::flang::DeclContext*, ::flang::DeclContext*> {
  static ToTy *doit(::flang::DeclContext *Val) {
    return ::flang::cast_convert_decl_context<ToTy>::doit(Val);
  }
};

/// Implement cast_convert_val for Decl -> DeclContext conversions.
template<class FromTy>
struct cast_convert_val< ::flang::DeclContext, FromTy, FromTy> {
  static ::flang::DeclContext &doit(const FromTy &Val) {
    return *FromTy::castToDeclContext(&Val);
  }
};

template<class FromTy>
struct cast_convert_val< ::flang::DeclContext, FromTy*, FromTy*> {
  static ::flang::DeclContext *doit(const FromTy *Val) {
    return FromTy::castToDeclContext(Val);
  }
};

template<class FromTy>
struct cast_convert_val< const ::flang::DeclContext, FromTy, FromTy> {
  static const ::flang::DeclContext &doit(const FromTy &Val) {
    return *FromTy::castToDeclContext(&Val);
  }
};

template<class FromTy>
struct cast_convert_val< const ::flang::DeclContext, FromTy*, FromTy*> {
  static const ::flang::DeclContext *doit(const FromTy *Val) {
    return FromTy::castToDeclContext(Val);
  }
};

} // end namespace llvm

#endif // FLANG_AST_DECL_H__