Coverage Report

Created: 2020-11-24 06:42

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/include/clang/AST/Type.h
Line
Count
Source (jump to first uncovered line)
1
//===- Type.h - C Language Family Type Representation -----------*- 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
/// \file
10
/// C Language Family Type Representation
11
///
12
/// This file defines the clang::Type interface and subclasses, used to
13
/// represent types for languages in the C family.
14
//
15
//===----------------------------------------------------------------------===//
16
17
#ifndef LLVM_CLANG_AST_TYPE_H
18
#define LLVM_CLANG_AST_TYPE_H
19
20
#include "clang/AST/DependenceFlags.h"
21
#include "clang/AST/NestedNameSpecifier.h"
22
#include "clang/AST/TemplateName.h"
23
#include "clang/Basic/AddressSpaces.h"
24
#include "clang/Basic/AttrKinds.h"
25
#include "clang/Basic/Diagnostic.h"
26
#include "clang/Basic/ExceptionSpecificationType.h"
27
#include "clang/Basic/LLVM.h"
28
#include "clang/Basic/Linkage.h"
29
#include "clang/Basic/PartialDiagnostic.h"
30
#include "clang/Basic/SourceLocation.h"
31
#include "clang/Basic/Specifiers.h"
32
#include "clang/Basic/Visibility.h"
33
#include "llvm/ADT/APInt.h"
34
#include "llvm/ADT/APSInt.h"
35
#include "llvm/ADT/ArrayRef.h"
36
#include "llvm/ADT/FoldingSet.h"
37
#include "llvm/ADT/None.h"
38
#include "llvm/ADT/Optional.h"
39
#include "llvm/ADT/PointerIntPair.h"
40
#include "llvm/ADT/PointerUnion.h"
41
#include "llvm/ADT/StringRef.h"
42
#include "llvm/ADT/Twine.h"
43
#include "llvm/ADT/iterator_range.h"
44
#include "llvm/Support/Casting.h"
45
#include "llvm/Support/Compiler.h"
46
#include "llvm/Support/ErrorHandling.h"
47
#include "llvm/Support/PointerLikeTypeTraits.h"
48
#include "llvm/Support/TrailingObjects.h"
49
#include "llvm/Support/type_traits.h"
50
#include <cassert>
51
#include <cstddef>
52
#include <cstdint>
53
#include <cstring>
54
#include <string>
55
#include <type_traits>
56
#include <utility>
57
58
namespace clang {
59
60
class ExtQuals;
61
class QualType;
62
class ConceptDecl;
63
class TagDecl;
64
class TemplateParameterList;
65
class Type;
66
67
enum {
68
  TypeAlignmentInBits = 4,
69
  TypeAlignment = 1 << TypeAlignmentInBits
70
};
71
72
namespace serialization {
73
  template <class T> class AbstractTypeReader;
74
  template <class T> class AbstractTypeWriter;
75
}
76
77
} // namespace clang
78
79
namespace llvm {
80
81
  template <typename T>
82
  struct PointerLikeTypeTraits;
83
  template<>
84
  struct PointerLikeTypeTraits< ::clang::Type*> {
85
1.87G
    static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
86
87
75.5M
    static inline ::clang::Type *getFromVoidPointer(void *P) {
88
75.5M
      return static_cast< ::clang::Type*>(P);
89
75.5M
    }
90
91
    static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
92
  };
93
94
  template<>
95
  struct PointerLikeTypeTraits< ::clang::ExtQuals*> {
96
588k
    static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
97
98
1.81M
    static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
99
1.81M
      return static_cast< ::clang::ExtQuals*>(P);
100
1.81M
    }
101
102
    static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
103
  };
104
105
} // namespace llvm
106
107
namespace clang {
108
109
class ASTContext;
110
template <typename> class CanQual;
111
class CXXRecordDecl;
112
class DeclContext;
113
class EnumDecl;
114
class Expr;
115
class ExtQualsTypeCommonBase;
116
class FunctionDecl;
117
class IdentifierInfo;
118
class NamedDecl;
119
class ObjCInterfaceDecl;
120
class ObjCProtocolDecl;
121
class ObjCTypeParamDecl;
122
struct PrintingPolicy;
123
class RecordDecl;
124
class Stmt;
125
class TagDecl;
126
class TemplateArgument;
127
class TemplateArgumentListInfo;
128
class TemplateArgumentLoc;
129
class TemplateTypeParmDecl;
130
class TypedefNameDecl;
131
class UnresolvedUsingTypenameDecl;
132
133
using CanQualType = CanQual<Type>;
134
135
// Provide forward declarations for all of the *Type classes.
136
#define TYPE(Class, Base) class Class##Type;
137
#include "clang/AST/TypeNodes.inc"
138
139
/// The collection of all-type qualifiers we support.
140
/// Clang supports five independent qualifiers:
141
/// * C99: const, volatile, and restrict
142
/// * MS: __unaligned
143
/// * Embedded C (TR18037): address spaces
144
/// * Objective C: the GC attributes (none, weak, or strong)
145
class Qualifiers {
146
public:
147
  enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
148
    Const    = 0x1,
149
    Restrict = 0x2,
150
    Volatile = 0x4,
151
    CVRMask = Const | Volatile | Restrict
152
  };
153
154
  enum GC {
155
    GCNone = 0,
156
    Weak,
157
    Strong
158
  };
159
160
  enum ObjCLifetime {
161
    /// There is no lifetime qualification on this type.
162
    OCL_None,
163
164
    /// This object can be modified without requiring retains or
165
    /// releases.
166
    OCL_ExplicitNone,
167
168
    /// Assigning into this object requires the old value to be
169
    /// released and the new value to be retained.  The timing of the
170
    /// release of the old value is inexact: it may be moved to
171
    /// immediately after the last known point where the value is
172
    /// live.
173
    OCL_Strong,
174
175
    /// Reading or writing from this object requires a barrier call.
176
    OCL_Weak,
177
178
    /// Assigning into this object requires a lifetime extension.
179
    OCL_Autoreleasing
180
  };
181
182
  enum {
183
    /// The maximum supported address space number.
184
    /// 23 bits should be enough for anyone.
185
    MaxAddressSpace = 0x7fffffu,
186
187
    /// The width of the "fast" qualifier mask.
188
    FastWidth = 3,
189
190
    /// The fast qualifier mask.
191
    FastMask = (1 << FastWidth) - 1
192
  };
193
194
  /// Returns the common set of qualifiers while removing them from
195
  /// the given sets.
196
10.5M
  static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
197
    // If both are only CVR-qualified, bit operations are sufficient.
198
10.5M
    if (!(L.Mask & ~CVRMask) && 
!(R.Mask & ~CVRMask)10.5M
) {
199
10.5M
      Qualifiers Q;
200
10.5M
      Q.Mask = L.Mask & R.Mask;
201
10.5M
      L.Mask &= ~Q.Mask;
202
10.5M
      R.Mask &= ~Q.Mask;
203
10.5M
      return Q;
204
10.5M
    }
205
206
926
    Qualifiers Q;
207
926
    unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
208
926
    Q.addCVRQualifiers(CommonCRV);
209
926
    L.removeCVRQualifiers(CommonCRV);
210
926
    R.removeCVRQualifiers(CommonCRV);
211
212
926
    if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
213
918
      Q.setObjCGCAttr(L.getObjCGCAttr());
214
918
      L.removeObjCGCAttr();
215
918
      R.removeObjCGCAttr();
216
918
    }
217
218
926
    if (L.getObjCLifetime() == R.getObjCLifetime()) {
219
729
      Q.setObjCLifetime(L.getObjCLifetime());
220
729
      L.removeObjCLifetime();
221
729
      R.removeObjCLifetime();
222
729
    }
223
224
926
    if (L.getAddressSpace() == R.getAddressSpace()) {
225
210
      Q.setAddressSpace(L.getAddressSpace());
226
210
      L.removeAddressSpace();
227
210
      R.removeAddressSpace();
228
210
    }
229
926
    return Q;
230
926
  }
231
232
122M
  static Qualifiers fromFastMask(unsigned Mask) {
233
122M
    Qualifiers Qs;
234
122M
    Qs.addFastQualifiers(Mask);
235
122M
    return Qs;
236
122M
  }
237
238
4.96M
  static Qualifiers fromCVRMask(unsigned CVR) {
239
4.96M
    Qualifiers Qs;
240
4.96M
    Qs.addCVRQualifiers(CVR);
241
4.96M
    return Qs;
242
4.96M
  }
243
244
1.18M
  static Qualifiers fromCVRUMask(unsigned CVRU) {
245
1.18M
    Qualifiers Qs;
246
1.18M
    Qs.addCVRUQualifiers(CVRU);
247
1.18M
    return Qs;
248
1.18M
  }
249
250
  // Deserialize qualifiers from an opaque representation.
251
800k
  static Qualifiers fromOpaqueValue(unsigned opaque) {
252
800k
    Qualifiers Qs;
253
800k
    Qs.Mask = opaque;
254
800k
    return Qs;
255
800k
  }
256
257
  // Serialize these qualifiers into an opaque representation.
258
5.31M
  unsigned getAsOpaqueValue() const {
259
5.31M
    return Mask;
260
5.31M
  }
261
262
7.76M
  bool hasConst() const { return Mask & Const; }
263
557
  bool hasOnlyConst() const { return Mask == Const; }
264
90.1k
  void removeConst() { Mask &= ~Const; }
265
259k
  void addConst() { Mask |= Const; }
266
267
8.45M
  bool hasVolatile() const { return Mask & Volatile; }
268
26
  bool hasOnlyVolatile() const { return Mask == Volatile; }
269
1.64k
  void removeVolatile() { Mask &= ~Volatile; }
270
95.9k
  void addVolatile() { Mask |= Volatile; }
271
272
5.63M
  bool hasRestrict() const { return Mask & Restrict; }
273
20
  bool hasOnlyRestrict() const { return Mask == Restrict; }
274
1.11M
  void removeRestrict() { Mask &= ~Restrict; }
275
94.9k
  void addRestrict() { Mask |= Restrict; }
276
277
27
  bool hasCVRQualifiers() const { return getCVRQualifiers(); }
278
21.5M
  unsigned getCVRQualifiers() const { return Mask & CVRMask; }
279
46.4k
  unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); }
280
281
681k
  void setCVRQualifiers(unsigned mask) {
282
681k
    assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
283
681k
    Mask = (Mask & ~CVRMask) | mask;
284
681k
  }
285
3.32M
  void removeCVRQualifiers(unsigned mask) {
286
3.32M
    assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
287
3.32M
    Mask &= ~mask;
288
3.32M
  }
289
1.99M
  void removeCVRQualifiers() {
290
1.99M
    removeCVRQualifiers(CVRMask);
291
1.99M
  }
292
5.13M
  void addCVRQualifiers(unsigned mask) {
293
5.13M
    assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
294
5.13M
    Mask |= mask;
295
5.13M
  }
296
15.5M
  void addCVRUQualifiers(unsigned mask) {
297
15.5M
    assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits");
298
15.5M
    Mask |= mask;
299
15.5M
  }
300
301
25.8M
  bool hasUnaligned() const { return Mask & UMask; }
302
4.09M
  void setUnaligned(bool flag) {
303
4.09M
    Mask = (Mask & ~UMask) | (flag ? 
UMask154
: 0);
304
4.09M
  }
305
146k
  void removeUnaligned() { Mask &= ~UMask; }
306
0
  void addUnaligned() { Mask |= UMask; }
307
308
1.64M
  bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
309
32.9M
  GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
310
6.22M
  void setObjCGCAttr(GC type) {
311
6.22M
    Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
312
6.22M
  }
313
1.86M
  void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
314
255
  void addObjCGCAttr(GC type) {
315
255
    assert(type);
316
255
    setObjCGCAttr(type);
317
255
  }
318
264
  Qualifiers withoutObjCGCAttr() const {
319
264
    Qualifiers qs = *this;
320
264
    qs.removeObjCGCAttr();
321
264
    return qs;
322
264
  }
323
909
  Qualifiers withoutObjCLifetime() const {
324
909
    Qualifiers qs = *this;
325
909
    qs.removeObjCLifetime();
326
909
    return qs;
327
909
  }
328
3
  Qualifiers withoutAddressSpace() const {
329
3
    Qualifiers qs = *this;
330
3
    qs.removeAddressSpace();
331
3
    return qs;
332
3
  }
333
334
25.7M
  bool hasObjCLifetime() const { return Mask & LifetimeMask; }
335
84.0M
  ObjCLifetime getObjCLifetime() const {
336
84.0M
    return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
337
84.0M
  }
338
298k
  void setObjCLifetime(ObjCLifetime type) {
339
298k
    Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
340
298k
  }
341
252k
  void removeObjCLifetime() { setObjCLifetime(OCL_None); }
342
21.7k
  void addObjCLifetime(ObjCLifetime type) {
343
21.7k
    assert(type);
344
21.7k
    assert(!hasObjCLifetime());
345
21.7k
    Mask |= (type << LifetimeShift);
346
21.7k
  }
347
348
  /// True if the lifetime is neither None or ExplicitNone.
349
3.62M
  bool hasNonTrivialObjCLifetime() const {
350
3.62M
    ObjCLifetime lifetime = getObjCLifetime();
351
3.62M
    return (lifetime > OCL_ExplicitNone);
352
3.62M
  }
353
354
  /// True if the lifetime is either strong or weak.
355
170
  bool hasStrongOrWeakObjCLifetime() const {
356
170
    ObjCLifetime lifetime = getObjCLifetime();
357
170
    return (lifetime == OCL_Strong || 
lifetime == OCL_Weak168
);
358
170
  }
359
360
27.0M
  bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
361
146M
  LangAS getAddressSpace() const {
362
146M
    return static_cast<LangAS>(Mask >> AddressSpaceShift);
363
146M
  }
364
10
  bool hasTargetSpecificAddressSpace() const {
365
10
    return isTargetAddressSpace(getAddressSpace());
366
10
  }
367
  /// Get the address space attribute value to be printed by diagnostics.
368
10
  unsigned getAddressSpaceAttributePrintValue() const {
369
10
    auto Addr = getAddressSpace();
370
    // This function is not supposed to be used with language specific
371
    // address spaces. If that happens, the diagnostic message should consider
372
    // printing the QualType instead of the address space value.
373
10
    assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace());
374
10
    if (Addr != LangAS::Default)
375
10
      return toTargetAddressSpace(Addr);
376
    // TODO: The diagnostic messages where Addr may be 0 should be fixed
377
    // since it cannot differentiate the situation where 0 denotes the default
378
    // address space or user specified __attribute__((address_space(0))).
379
0
    return 0;
380
0
  }
381
616k
  void setAddressSpace(LangAS space) {
382
616k
    assert((unsigned)space <= MaxAddressSpace);
383
616k
    Mask = (Mask & ~AddressSpaceMask)
384
616k
         | (((uint32_t) space) << AddressSpaceShift);
385
616k
  }
386
68.7k
  void removeAddressSpace() { setAddressSpace(LangAS::Default); }
387
488k
  void addAddressSpace(LangAS space) {
388
488k
    assert(space != LangAS::Default);
389
488k
    setAddressSpace(space);
390
488k
  }
391
392
  // Fast qualifiers are those that can be allocated directly
393
  // on a QualType object.
394
1.50M
  bool hasFastQualifiers() const { return getFastQualifiers(); }
395
73.9M
  unsigned getFastQualifiers() const { return Mask & FastMask; }
396
0
  void setFastQualifiers(unsigned mask) {
397
0
    assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
398
0
    Mask = (Mask & ~FastMask) | mask;
399
0
  }
400
561k
  void removeFastQualifiers(unsigned mask) {
401
561k
    assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
402
561k
    Mask &= ~mask;
403
561k
  }
404
561k
  void removeFastQualifiers() {
405
561k
    removeFastQualifiers(FastMask);
406
561k
  }
407
783M
  void addFastQualifiers(unsigned mask) {
408
783M
    assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
409
783M
    Mask |= mask;
410
783M
  }
411
412
  /// Return true if the set contains any qualifiers which require an ExtQuals
413
  /// node to be allocated.
414
85.5M
  bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
415
0
  Qualifiers getNonFastQualifiers() const {
416
0
    Qualifiers Quals = *this;
417
0
    Quals.setFastQualifiers(0);
418
0
    return Quals;
419
0
  }
420
421
  /// Return true if the set contains any qualifiers.
422
22.1M
  bool hasQualifiers() const { return Mask; }
423
3.18M
  bool empty() const { return !Mask; }
424
425
  /// Add the qualifiers from the given set to this set.
426
22.1M
  void addQualifiers(Qualifiers Q) {
427
    // If the other set doesn't have any non-boolean qualifiers, just
428
    // bit-or it in.
429
22.1M
    if (!(Q.Mask & ~CVRMask))
430
22.1M
      Mask |= Q.Mask;
431
1.04k
    else {
432
1.04k
      Mask |= (Q.Mask & CVRMask);
433
1.04k
      if (Q.hasAddressSpace())
434
710
        addAddressSpace(Q.getAddressSpace());
435
1.04k
      if (Q.hasObjCGCAttr())
436
38
        addObjCGCAttr(Q.getObjCGCAttr());
437
1.04k
      if (Q.hasObjCLifetime())
438
294
        addObjCLifetime(Q.getObjCLifetime());
439
1.04k
    }
440
22.1M
  }
441
442
  /// Remove the qualifiers from the given set from this set.
443
19.6k
  void removeQualifiers(Qualifiers Q) {
444
    // If the other set doesn't have any non-boolean qualifiers, just
445
    // bit-and the inverse in.
446
19.6k
    if (!(Q.Mask & ~CVRMask))
447
19.5k
      Mask &= ~Q.Mask;
448
31
    else {
449
31
      Mask &= ~(Q.Mask & CVRMask);
450
31
      if (getObjCGCAttr() == Q.getObjCGCAttr())
451
31
        removeObjCGCAttr();
452
31
      if (getObjCLifetime() == Q.getObjCLifetime())
453
31
        removeObjCLifetime();
454
31
      if (getAddressSpace() == Q.getAddressSpace())
455
6
        removeAddressSpace();
456
31
    }
457
19.6k
  }
458
459
  /// Add the qualifiers from the given set to this set, given that
460
  /// they don't conflict.
461
849k
  void addConsistentQualifiers(Qualifiers qs) {
462
849k
    assert(getAddressSpace() == qs.getAddressSpace() ||
463
849k
           !hasAddressSpace() || !qs.hasAddressSpace());
464
849k
    assert(getObjCGCAttr() == qs.getObjCGCAttr() ||
465
849k
           !hasObjCGCAttr() || !qs.hasObjCGCAttr());
466
849k
    assert(getObjCLifetime() == qs.getObjCLifetime() ||
467
849k
           !hasObjCLifetime() || !qs.hasObjCLifetime());
468
849k
    Mask |= qs.Mask;
469
849k
  }
470
471
  /// Returns true if address space A is equal to or a superset of B.
472
  /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
473
  /// overlapping address spaces.
474
  /// CL1.1 or CL1.2:
475
  ///   every address space is a superset of itself.
476
  /// CL2.0 adds:
477
  ///   __generic is a superset of any address space except for __constant.
478
7.77M
  static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) {
479
    // Address spaces must match exactly.
480
7.77M
    return A == B ||
481
           // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
482
           // for __constant can be used as __generic.
483
5.66k
           (A == LangAS::opencl_generic && 
B != LangAS::opencl_constant1.87k
) ||
484
           // We also define global_device and global_host address spaces,
485
           // to distinguish global pointers allocated on host from pointers
486
           // allocated on device, which are a subset of __global.
487
4.04k
           (A == LangAS::opencl_global && 
(835
B == LangAS::opencl_global_device835
||
488
820
                                           B == LangAS::opencl_global_host)) ||
489
           // Consider pointer size address spaces to be equivalent to default.
490
4.01k
           ((isPtrSizeAddressSpace(A) || 
A == LangAS::Default4.01k
) &&
491
119
            (isPtrSizeAddressSpace(B) || 
B == LangAS::Default113
));
492
7.77M
  }
493
494
  /// Returns true if the address space in these qualifiers is equal to or
495
  /// a superset of the address space in the argument qualifiers.
496
6.08M
  bool isAddressSpaceSupersetOf(Qualifiers other) const {
497
6.08M
    return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace());
498
6.08M
  }
499
500
  /// Determines if these qualifiers compatibly include another set.
501
  /// Generally this answers the question of whether an object with the other
502
  /// qualifiers can be safely used as an object with these qualifiers.
503
6.00M
  bool compatiblyIncludes(Qualifiers other) const {
504
6.00M
    return isAddressSpaceSupersetOf(other) &&
505
           // ObjC GC qualifiers can match, be added, or be removed, but can't
506
           // be changed.
507
5.99M
           (getObjCGCAttr() == other.getObjCGCAttr() || 
!hasObjCGCAttr()18
||
508
15
            !other.hasObjCGCAttr()) &&
509
           // ObjC lifetime qualifiers must match exactly.
510
5.99M
           getObjCLifetime() == other.getObjCLifetime() &&
511
           // CVR qualifiers may subset.
512
5.99M
           (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
513
           // U qualifier may superset.
514
5.76M
           (!other.hasUnaligned() || 
hasUnaligned()35
);
515
6.00M
  }
516
517
  /// Determines if these qualifiers compatibly include another set of
518
  /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
519
  ///
520
  /// One set of Objective-C lifetime qualifiers compatibly includes the other
521
  /// if the lifetime qualifiers match, or if both are non-__weak and the
522
  /// including set also contains the 'const' qualifier, or both are non-__weak
523
  /// and one is None (which can only happen in non-ARC modes).
524
15.4k
  bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
525
15.4k
    if (getObjCLifetime() == other.getObjCLifetime())
526
15.2k
      return true;
527
528
280
    if (getObjCLifetime() == OCL_Weak || 
other.getObjCLifetime() == OCL_Weak229
)
529
128
      return false;
530
531
152
    if (getObjCLifetime() == OCL_None || 
other.getObjCLifetime() == OCL_None120
)
532
65
      return true;
533
534
87
    return hasConst();
535
87
  }
536
537
  /// Determine whether this set of qualifiers is a strict superset of
538
  /// another set of qualifiers, not considering qualifier compatibility.
539
  bool isStrictSupersetOf(Qualifiers Other) const;
540
541
2.59M
  bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
542
33.5M
  bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
543
544
22.1M
  explicit operator bool() const { return hasQualifiers(); }
545
546
22.1M
  Qualifiers &operator+=(Qualifiers R) {
547
22.1M
    addQualifiers(R);
548
22.1M
    return *this;
549
22.1M
  }
550
551
  // Union two qualifier sets.  If an enumerated qualifier appears
552
  // in both sets, use the one from the right.
553
833k
  friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
554
833k
    L += R;
555
833k
    return L;
556
833k
  }
557
558
19.6k
  Qualifiers &operator-=(Qualifiers R) {
559
19.6k
    removeQualifiers(R);
560
19.6k
    return *this;
561
19.6k
  }
562
563
  /// Compute the difference between two qualifier sets.
564
14.4k
  friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
565
14.4k
    L -= R;
566
14.4k
    return L;
567
14.4k
  }
568
569
  std::string getAsString() const;
570
  std::string getAsString(const PrintingPolicy &Policy) const;
571
572
  static std::string getAddrSpaceAsString(LangAS AS);
573
574
  bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
575
  void print(raw_ostream &OS, const PrintingPolicy &Policy,
576
             bool appendSpaceIfNonEmpty = false) const;
577
578
98.7M
  void Profile(llvm::FoldingSetNodeID &ID) const {
579
98.7M
    ID.AddInteger(Mask);
580
98.7M
  }
581
582
private:
583
  // bits:     |0 1 2|3|4 .. 5|6  ..  8|9   ...   31|
584
  //           |C R V|U|GCAttr|Lifetime|AddressSpace|
585
  uint32_t Mask = 0;
586
587
  static const uint32_t UMask = 0x8;
588
  static const uint32_t UShift = 3;
589
  static const uint32_t GCAttrMask = 0x30;
590
  static const uint32_t GCAttrShift = 4;
591
  static const uint32_t LifetimeMask = 0x1C0;
592
  static const uint32_t LifetimeShift = 6;
593
  static const uint32_t AddressSpaceMask =
594
      ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
595
  static const uint32_t AddressSpaceShift = 9;
596
};
597
598
/// A std::pair-like structure for storing a qualified type split
599
/// into its local qualifiers and its locally-unqualified type.
600
struct SplitQualType {
601
  /// The locally-unqualified type.
602
  const Type *Ty = nullptr;
603
604
  /// The local qualifiers.
605
  Qualifiers Quals;
606
607
  SplitQualType() = default;
608
59.7M
  SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
609
610
  SplitQualType getSingleStepDesugaredType() const; // end of this file
611
612
  // Make std::tie work.
613
636k
  std::pair<const Type *,Qualifiers> asPair() const {
614
636k
    return std::pair<const Type *, Qualifiers>(Ty, Quals);
615
636k
  }
616
617
0
  friend bool operator==(SplitQualType a, SplitQualType b) {
618
0
    return a.Ty == b.Ty && a.Quals == b.Quals;
619
0
  }
620
45.5k
  friend bool operator!=(SplitQualType a, SplitQualType b) {
621
45.5k
    return a.Ty != b.Ty || 
a.Quals != b.Quals43.2k
;
622
45.5k
  }
623
};
624
625
/// The kind of type we are substituting Objective-C type arguments into.
626
///
627
/// The kind of substitution affects the replacement of type parameters when
628
/// no concrete type information is provided, e.g., when dealing with an
629
/// unspecialized type.
630
enum class ObjCSubstitutionContext {
631
  /// An ordinary type.
632
  Ordinary,
633
634
  /// The result type of a method or function.
635
  Result,
636
637
  /// The parameter type of a method or function.
638
  Parameter,
639
640
  /// The type of a property.
641
  Property,
642
643
  /// The superclass of a type.
644
  Superclass,
645
};
646
647
/// A (possibly-)qualified type.
648
///
649
/// For efficiency, we don't store CV-qualified types as nodes on their
650
/// own: instead each reference to a type stores the qualifiers.  This
651
/// greatly reduces the number of nodes we need to allocate for types (for
652
/// example we only need one for 'int', 'const int', 'volatile int',
653
/// 'const volatile int', etc).
654
///
655
/// As an added efficiency bonus, instead of making this a pair, we
656
/// just store the two bits we care about in the low bits of the
657
/// pointer.  To handle the packing/unpacking, we make QualType be a
658
/// simple wrapper class that acts like a smart pointer.  A third bit
659
/// indicates whether there are extended qualifiers present, in which
660
/// case the pointer points to a special structure.
661
class QualType {
662
  friend class QualifierCollector;
663
664
  // Thankfully, these are efficiently composable.
665
  llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
666
                       Qualifiers::FastWidth> Value;
667
668
1.81M
  const ExtQuals *getExtQualsUnsafe() const {
669
1.81M
    return Value.getPointer().get<const ExtQuals*>();
670
1.81M
  }
671
672
74.9M
  const Type *getTypePtrUnsafe() const {
673
74.9M
    return Value.getPointer().get<const Type*>();
674
74.9M
  }
675
676
20.5G
  const ExtQualsTypeCommonBase *getCommonPtr() const {
677
20.5G
    assert(!isNull() && "Cannot retrieve a NULL type pointer");
678
20.5G
    auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
679
20.5G
    CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
680
20.5G
    return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
681
20.5G
  }
682
683
public:
684
8.35G
  QualType() = default;
685
1.86G
  QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
686
588k
  QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
687
688
5.34G
  unsigned getLocalFastQualifiers() const { return Value.getInt(); }
689
0
  void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
690
691
  /// Retrieves a pointer to the underlying (unqualified) type.
692
  ///
693
  /// This function requires that the type not be NULL. If the type might be
694
  /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
695
  const Type *getTypePtr() const;
696
697
  const Type *getTypePtrOrNull() const;
698
699
  /// Retrieves a pointer to the name of the base type.
700
  const IdentifierInfo *getBaseTypeIdentifier() const;
701
702
  /// Divides a QualType into its unqualified type and a set of local
703
  /// qualifiers.
704
  SplitQualType split() const;
705
706
1.86G
  void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
707
708
6.23G
  static QualType getFromOpaquePtr(const void *Ptr) {
709
6.23G
    QualType T;
710
6.23G
    T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
711
6.23G
    return T;
712
6.23G
  }
713
714
2.53M
  const Type &operator*() const {
715
2.53M
    return *getTypePtr();
716
2.53M
  }
717
718
6.46G
  const Type *operator->() const {
719
6.46G
    return getTypePtr();
720
6.46G
  }
721
722
  bool isCanonical() const;
723
  bool isCanonicalAsParam() const;
724
725
  /// Return true if this QualType doesn't point to a type yet.
726
23.9G
  bool isNull() const {
727
23.9G
    return Value.getPointer().isNull();
728
23.9G
  }
729
730
  /// Determine whether this particular QualType instance has the
731
  /// "const" qualifier set, without looking through typedefs that may have
732
  /// added "const" at a different level.
733
63.3M
  bool isLocalConstQualified() const {
734
63.3M
    return (getLocalFastQualifiers() & Qualifiers::Const);
735
63.3M
  }
736
737
  /// Determine whether this type is const-qualified.
738
  bool isConstQualified() const;
739
740
  /// Determine whether this particular QualType instance has the
741
  /// "restrict" qualifier set, without looking through typedefs that may have
742
  /// added "restrict" at a different level.
743
553k
  bool isLocalRestrictQualified() const {
744
553k
    return (getLocalFastQualifiers() & Qualifiers::Restrict);
745
553k
  }
746
747
  /// Determine whether this type is restrict-qualified.
748
  bool isRestrictQualified() const;
749
750
  /// Determine whether this particular QualType instance has the
751
  /// "volatile" qualifier set, without looking through typedefs that may have
752
  /// added "volatile" at a different level.
753
252M
  bool isLocalVolatileQualified() const {
754
252M
    return (getLocalFastQualifiers() & Qualifiers::Volatile);
755
252M
  }
756
757
  /// Determine whether this type is volatile-qualified.
758
  bool isVolatileQualified() const;
759
760
  /// Determine whether this particular QualType instance has any
761
  /// qualifiers, without looking through any typedefs that might add
762
  /// qualifiers at a different level.
763
3.33G
  bool hasLocalQualifiers() const {
764
3.33G
    return getLocalFastQualifiers() || 
hasLocalNonFastQualifiers()3.24G
;
765
3.33G
  }
766
767
  /// Determine whether this type has any qualifiers.
768
  bool hasQualifiers() const;
769
770
  /// Determine whether this particular QualType instance has any
771
  /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
772
  /// instance.
773
3.68G
  bool hasLocalNonFastQualifiers() const {
774
3.68G
    return Value.getPointer().is<const ExtQuals*>();
775
3.68G
  }
776
777
  /// Retrieve the set of qualifiers local to this particular QualType
778
  /// instance, not including any qualifiers acquired through typedefs or
779
  /// other sugar.
780
  Qualifiers getLocalQualifiers() const;
781
782
  /// Retrieve the set of qualifiers applied to this type.
783
  Qualifiers getQualifiers() const;
784
785
  /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
786
  /// local to this particular QualType instance, not including any qualifiers
787
  /// acquired through typedefs or other sugar.
788
40.0M
  unsigned getLocalCVRQualifiers() const {
789
40.0M
    return getLocalFastQualifiers();
790
40.0M
  }
791
792
  /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
793
  /// applied to this type.
794
  unsigned getCVRQualifiers() const;
795
796
15.7M
  bool isConstant(const ASTContext& Ctx) const {
797
15.7M
    return QualType::isConstant(*this, Ctx);
798
15.7M
  }
799
800
  /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
801
  bool isPODType(const ASTContext &Context) const;
802
803
  /// Return true if this is a POD type according to the rules of the C++98
804
  /// standard, regardless of the current compilation's language.
805
  bool isCXX98PODType(const ASTContext &Context) const;
806
807
  /// Return true if this is a POD type according to the more relaxed rules
808
  /// of the C++11 standard, regardless of the current compilation's language.
809
  /// (C++0x [basic.types]p9). Note that, unlike
810
  /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
811
  bool isCXX11PODType(const ASTContext &Context) const;
812
813
  /// Return true if this is a trivial type per (C++0x [basic.types]p9)
814
  bool isTrivialType(const ASTContext &Context) const;
815
816
  /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
817
  bool isTriviallyCopyableType(const ASTContext &Context) const;
818
819
820
  /// Returns true if it is a class and it might be dynamic.
821
  bool mayBeDynamicClass() const;
822
823
  /// Returns true if it is not a class or if the class might not be dynamic.
824
  bool mayBeNotDynamicClass() const;
825
826
  // Don't promise in the API that anything besides 'const' can be
827
  // easily added.
828
829
  /// Add the `const` type qualifier to this QualType.
830
281k
  void addConst() {
831
281k
    addFastQualifiers(Qualifiers::Const);
832
281k
  }
833
3.98M
  QualType withConst() const {
834
3.98M
    return withFastQualifiers(Qualifiers::Const);
835
3.98M
  }
836
837
  /// Add the `volatile` type qualifier to this QualType.
838
102
  void addVolatile() {
839
102
    addFastQualifiers(Qualifiers::Volatile);
840
102
  }
841
336
  QualType withVolatile() const {
842
336
    return withFastQualifiers(Qualifiers::Volatile);
843
336
  }
844
845
  /// Add the `restrict` qualifier to this QualType.
846
142
  void addRestrict() {
847
142
    addFastQualifiers(Qualifiers::Restrict);
848
142
  }
849
1.17M
  QualType withRestrict() const {
850
1.17M
    return withFastQualifiers(Qualifiers::Restrict);
851
1.17M
  }
852
853
4.40k
  QualType withCVRQualifiers(unsigned CVR) const {
854
4.40k
    return withFastQualifiers(CVR);
855
4.40k
  }
856
857
997M
  void addFastQualifiers(unsigned TQs) {
858
997M
    assert(!(TQs & ~Qualifiers::FastMask)
859
997M
           && "non-fast qualifier bits set in mask!");
860
997M
    Value.setInt(Value.getInt() | TQs);
861
997M
  }
862
863
  void removeLocalConst();
864
  void removeLocalVolatile();
865
  void removeLocalRestrict();
866
  void removeLocalCVRQualifiers(unsigned Mask);
867
868
13.6M
  void removeLocalFastQualifiers() { Value.setInt(0); }
869
77.6k
  void removeLocalFastQualifiers(unsigned Mask) {
870
77.6k
    assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers");
871
77.6k
    Value.setInt(Value.getInt() & ~Mask);
872
77.6k
  }
873
874
  // Creates a type with the given qualifiers in addition to any
875
  // qualifiers already on this type.
876
996M
  QualType withFastQualifiers(unsigned TQs) const {
877
996M
    QualType T = *this;
878
996M
    T.addFastQualifiers(TQs);
879
996M
    return T;
880
996M
  }
881
882
  // Creates a type with exactly the given fast qualifiers, removing
883
  // any existing fast qualifiers.
884
0
  QualType withExactLocalFastQualifiers(unsigned TQs) const {
885
0
    return withoutLocalFastQualifiers().withFastQualifiers(TQs);
886
0
  }
887
888
  // Removes fast qualifiers, but leaves any extended qualifiers in place.
889
60
  QualType withoutLocalFastQualifiers() const {
890
60
    QualType T = *this;
891
60
    T.removeLocalFastQualifiers();
892
60
    return T;
893
60
  }
894
895
  QualType getCanonicalType() const;
896
897
  /// Return this type with all of the instance-specific qualifiers
898
  /// removed, but without removing any qualifiers that may have been applied
899
  /// through typedefs.
900
91.4M
  QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
901
902
  /// Retrieve the unqualified variant of the given type,
903
  /// removing as little sugar as possible.
904
  ///
905
  /// This routine looks through various kinds of sugar to find the
906
  /// least-desugared type that is unqualified. For example, given:
907
  ///
908
  /// \code
909
  /// typedef int Integer;
910
  /// typedef const Integer CInteger;
911
  /// typedef CInteger DifferenceType;
912
  /// \endcode
913
  ///
914
  /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
915
  /// desugar until we hit the type \c Integer, which has no qualifiers on it.
916
  ///
917
  /// The resulting type might still be qualified if it's sugar for an array
918
  /// type.  To strip qualifiers even from within a sugared array type, use
919
  /// ASTContext::getUnqualifiedArrayType.
920
  inline QualType getUnqualifiedType() const;
921
922
  /// Retrieve the unqualified variant of the given type, removing as little
923
  /// sugar as possible.
924
  ///
925
  /// Like getUnqualifiedType(), but also returns the set of
926
  /// qualifiers that were built up.
927
  ///
928
  /// The resulting type might still be qualified if it's sugar for an array
929
  /// type.  To strip qualifiers even from within a sugared array type, use
930
  /// ASTContext::getUnqualifiedArrayType.
931
  inline SplitQualType getSplitUnqualifiedType() const;
932
933
  /// Determine whether this type is more qualified than the other
934
  /// given type, requiring exact equality for non-CVR qualifiers.
935
  bool isMoreQualifiedThan(QualType Other) const;
936
937
  /// Determine whether this type is at least as qualified as the other
938
  /// given type, requiring exact equality for non-CVR qualifiers.
939
  bool isAtLeastAsQualifiedAs(QualType Other) const;
940
941
  QualType getNonReferenceType() const;
942
943
  /// Determine the type of a (typically non-lvalue) expression with the
944
  /// specified result type.
945
  ///
946
  /// This routine should be used for expressions for which the return type is
947
  /// explicitly specified (e.g., in a cast or call) and isn't necessarily
948
  /// an lvalue. It removes a top-level reference (since there are no
949
  /// expressions of reference type) and deletes top-level cvr-qualifiers
950
  /// from non-class types (in C++) or all types (in C).
951
  QualType getNonLValueExprType(const ASTContext &Context) const;
952
953
  /// Remove an outer pack expansion type (if any) from this type. Used as part
954
  /// of converting the type of a declaration to the type of an expression that
955
  /// references that expression. It's meaningless for an expression to have a
956
  /// pack expansion type.
957
  QualType getNonPackExpansionType() const;
958
959
  /// Return the specified type with any "sugar" removed from
960
  /// the type.  This takes off typedefs, typeof's etc.  If the outer level of
961
  /// the type is already concrete, it returns it unmodified.  This is similar
962
  /// to getting the canonical type, but it doesn't remove *all* typedefs.  For
963
  /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
964
  /// concrete.
965
  ///
966
  /// Qualifiers are left in place.
967
976k
  QualType getDesugaredType(const ASTContext &Context) const {
968
976k
    return getDesugaredType(*this, Context);
969
976k
  }
970
971
22.1M
  SplitQualType getSplitDesugaredType() const {
972
22.1M
    return getSplitDesugaredType(*this);
973
22.1M
  }
974
975
  /// Return the specified type with one level of "sugar" removed from
976
  /// the type.
977
  ///
978
  /// This routine takes off the first typedef, typeof, etc. If the outer level
979
  /// of the type is already concrete, it returns it unmodified.
980
1.01k
  QualType getSingleStepDesugaredType(const ASTContext &Context) const {
981
1.01k
    return getSingleStepDesugaredTypeImpl(*this, Context);
982
1.01k
  }
983
984
  /// Returns the specified type after dropping any
985
  /// outer-level parentheses.
986
420
  QualType IgnoreParens() const {
987
420
    if (isa<ParenType>(*this))
988
32
      return QualType::IgnoreParens(*this);
989
388
    return *this;
990
388
  }
991
992
  /// Indicate whether the specified types and qualifiers are identical.
993
1.86G
  friend bool operator==(const QualType &LHS, const QualType &RHS) {
994
1.86G
    return LHS.Value == RHS.Value;
995
1.86G
  }
996
100M
  friend bool operator!=(const QualType &LHS, const QualType &RHS) {
997
100M
    return LHS.Value != RHS.Value;
998
100M
  }
999
36
  friend bool operator<(const QualType &LHS, const QualType &RHS) {
1000
36
    return LHS.Value < RHS.Value;
1001
36
  }
1002
1003
  static std::string getAsString(SplitQualType split,
1004
83.6k
                                 const PrintingPolicy &Policy) {
1005
83.6k
    return getAsString(split.Ty, split.Quals, Policy);
1006
83.6k
  }
1007
  static std::string getAsString(const Type *ty, Qualifiers qs,
1008
                                 const PrintingPolicy &Policy);
1009
1010
  std::string getAsString() const;
1011
  std::string getAsString(const PrintingPolicy &Policy) const;
1012
1013
  void print(raw_ostream &OS, const PrintingPolicy &Policy,
1014
             const Twine &PlaceHolder = Twine(),
1015
             unsigned Indentation = 0) const;
1016
1017
  static void print(SplitQualType split, raw_ostream &OS,
1018
                    const PrintingPolicy &policy, const Twine &PlaceHolder,
1019
1.46M
                    unsigned Indentation = 0) {
1020
1.46M
    return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
1021
1.46M
  }
1022
1023
  static void print(const Type *ty, Qualifiers qs,
1024
                    raw_ostream &OS, const PrintingPolicy &policy,
1025
                    const Twine &PlaceHolder,
1026
                    unsigned Indentation = 0);
1027
1028
  void getAsStringInternal(std::string &Str,
1029
                           const PrintingPolicy &Policy) const;
1030
1031
  static void getAsStringInternal(SplitQualType split, std::string &out,
1032
563k
                                  const PrintingPolicy &policy) {
1033
563k
    return getAsStringInternal(split.Ty, split.Quals, out, policy);
1034
563k
  }
1035
1036
  static void getAsStringInternal(const Type *ty, Qualifiers qs,
1037
                                  std::string &out,
1038
                                  const PrintingPolicy &policy);
1039
1040
  class StreamedQualTypeHelper {
1041
    const QualType &T;
1042
    const PrintingPolicy &Policy;
1043
    const Twine &PlaceHolder;
1044
    unsigned Indentation;
1045
1046
  public:
1047
    StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
1048
                           const Twine &PlaceHolder, unsigned Indentation)
1049
        : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1050
2.94k
          Indentation(Indentation) {}
1051
1052
    friend raw_ostream &operator<<(raw_ostream &OS,
1053
2.94k
                                   const StreamedQualTypeHelper &SQT) {
1054
2.94k
      SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1055
2.94k
      return OS;
1056
2.94k
    }
1057
  };
1058
1059
  StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
1060
                                const Twine &PlaceHolder = Twine(),
1061
2.94k
                                unsigned Indentation = 0) const {
1062
2.94k
    return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1063
2.94k
  }
1064
1065
  void dump(const char *s) const;
1066
  void dump() const;
1067
  void dump(llvm::raw_ostream &OS, const ASTContext &Context) const;
1068
1069
43.1M
  void Profile(llvm::FoldingSetNodeID &ID) const {
1070
43.1M
    ID.AddPointer(getAsOpaquePtr());
1071
43.1M
  }
1072
1073
  /// Check if this type has any address space qualifier.
1074
  inline bool hasAddressSpace() const;
1075
1076
  /// Return the address space of this type.
1077
  inline LangAS getAddressSpace() const;
1078
1079
  /// Returns true if address space qualifiers overlap with T address space
1080
  /// qualifiers.
1081
  /// OpenCL C defines conversion rules for pointers to different address spaces
1082
  /// and notion of overlapping address spaces.
1083
  /// CL1.1 or CL1.2:
1084
  ///   address spaces overlap iff they are they same.
1085
  /// OpenCL C v2.0 s6.5.5 adds:
1086
  ///   __generic overlaps with any address space except for __constant.
1087
8.43k
  bool isAddressSpaceOverlapping(QualType T) const {
1088
8.43k
    Qualifiers Q = getQualifiers();
1089
8.43k
    Qualifiers TQ = T.getQualifiers();
1090
    // Address spaces overlap if at least one of them is a superset of another
1091
8.43k
    return Q.isAddressSpaceSupersetOf(TQ) || 
TQ.isAddressSpaceSupersetOf(Q)264
;
1092
8.43k
  }
1093
1094
  /// Returns gc attribute of this type.
1095
  inline Qualifiers::GC getObjCGCAttr() const;
1096
1097
  /// true when Type is objc's weak.
1098
4.69M
  bool isObjCGCWeak() const {
1099
4.69M
    return getObjCGCAttr() == Qualifiers::Weak;
1100
4.69M
  }
1101
1102
  /// true when Type is objc's strong.
1103
1.92M
  bool isObjCGCStrong() const {
1104
1.92M
    return getObjCGCAttr() == Qualifiers::Strong;
1105
1.92M
  }
1106
1107
  /// Returns lifetime attribute of this type.
1108
44.8M
  Qualifiers::ObjCLifetime getObjCLifetime() const {
1109
44.8M
    return getQualifiers().getObjCLifetime();
1110
44.8M
  }
1111
1112
3.61M
  bool hasNonTrivialObjCLifetime() const {
1113
3.61M
    return getQualifiers().hasNonTrivialObjCLifetime();
1114
3.61M
  }
1115
1116
170
  bool hasStrongOrWeakObjCLifetime() const {
1117
170
    return getQualifiers().hasStrongOrWeakObjCLifetime();
1118
170
  }
1119
1120
  // true when Type is objc's weak and weak is enabled but ARC isn't.
1121
  bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1122
1123
  enum PrimitiveDefaultInitializeKind {
1124
    /// The type does not fall into any of the following categories. Note that
1125
    /// this case is zero-valued so that values of this enum can be used as a
1126
    /// boolean condition for non-triviality.
1127
    PDIK_Trivial,
1128
1129
    /// The type is an Objective-C retainable pointer type that is qualified
1130
    /// with the ARC __strong qualifier.
1131
    PDIK_ARCStrong,
1132
1133
    /// The type is an Objective-C retainable pointer type that is qualified
1134
    /// with the ARC __weak qualifier.
1135
    PDIK_ARCWeak,
1136
1137
    /// The type is a struct containing a field whose type is not PCK_Trivial.
1138
    PDIK_Struct
1139
  };
1140
1141
  /// Functions to query basic properties of non-trivial C struct types.
1142
1143
  /// Check if this is a non-trivial type that would cause a C struct
1144
  /// transitively containing this type to be non-trivial to default initialize
1145
  /// and return the kind.
1146
  PrimitiveDefaultInitializeKind
1147
  isNonTrivialToPrimitiveDefaultInitialize() const;
1148
1149
  enum PrimitiveCopyKind {
1150
    /// The type does not fall into any of the following categories. Note that
1151
    /// this case is zero-valued so that values of this enum can be used as a
1152
    /// boolean condition for non-triviality.
1153
    PCK_Trivial,
1154
1155
    /// The type would be trivial except that it is volatile-qualified. Types
1156
    /// that fall into one of the other non-trivial cases may additionally be
1157
    /// volatile-qualified.
1158
    PCK_VolatileTrivial,
1159
1160
    /// The type is an Objective-C retainable pointer type that is qualified
1161
    /// with the ARC __strong qualifier.
1162
    PCK_ARCStrong,
1163
1164
    /// The type is an Objective-C retainable pointer type that is qualified
1165
    /// with the ARC __weak qualifier.
1166
    PCK_ARCWeak,
1167
1168
    /// The type is a struct containing a field whose type is neither
1169
    /// PCK_Trivial nor PCK_VolatileTrivial.
1170
    /// Note that a C++ struct type does not necessarily match this; C++ copying
1171
    /// semantics are too complex to express here, in part because they depend
1172
    /// on the exact constructor or assignment operator that is chosen by
1173
    /// overload resolution to do the copy.
1174
    PCK_Struct
1175
  };
1176
1177
  /// Check if this is a non-trivial type that would cause a C struct
1178
  /// transitively containing this type to be non-trivial to copy and return the
1179
  /// kind.
1180
  PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const;
1181
1182
  /// Check if this is a non-trivial type that would cause a C struct
1183
  /// transitively containing this type to be non-trivial to destructively
1184
  /// move and return the kind. Destructive move in this context is a C++-style
1185
  /// move in which the source object is placed in a valid but unspecified state
1186
  /// after it is moved, as opposed to a truly destructive move in which the
1187
  /// source object is placed in an uninitialized state.
1188
  PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const;
1189
1190
  enum DestructionKind {
1191
    DK_none,
1192
    DK_cxx_destructor,
1193
    DK_objc_strong_lifetime,
1194
    DK_objc_weak_lifetime,
1195
    DK_nontrivial_c_struct
1196
  };
1197
1198
  /// Returns a nonzero value if objects of this type require
1199
  /// non-trivial work to clean up after.  Non-zero because it's
1200
  /// conceivable that qualifiers (objc_gc(weak)?) could make
1201
  /// something require destruction.
1202
18.4M
  DestructionKind isDestructedType() const {
1203
18.4M
    return isDestructedTypeImpl(*this);
1204
18.4M
  }
1205
1206
  /// Check if this is or contains a C union that is non-trivial to
1207
  /// default-initialize, which is a union that has a member that is non-trivial
1208
  /// to default-initialize. If this returns true,
1209
  /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct.
1210
  bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const;
1211
1212
  /// Check if this is or contains a C union that is non-trivial to destruct,
1213
  /// which is a union that has a member that is non-trivial to destruct. If
1214
  /// this returns true, isDestructedType returns DK_nontrivial_c_struct.
1215
  bool hasNonTrivialToPrimitiveDestructCUnion() const;
1216
1217
  /// Check if this is or contains a C union that is non-trivial to copy, which
1218
  /// is a union that has a member that is non-trivial to copy. If this returns
1219
  /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct.
1220
  bool hasNonTrivialToPrimitiveCopyCUnion() const;
1221
1222
  /// Determine whether expressions of the given type are forbidden
1223
  /// from being lvalues in C.
1224
  ///
1225
  /// The expression types that are forbidden to be lvalues are:
1226
  ///   - 'void', but not qualified void
1227
  ///   - function types
1228
  ///
1229
  /// The exact rule here is C99 6.3.2.1:
1230
  ///   An lvalue is an expression with an object type or an incomplete
1231
  ///   type other than void.
1232
  bool isCForbiddenLValueType() const;
1233
1234
  /// Substitute type arguments for the Objective-C type parameters used in the
1235
  /// subject type.
1236
  ///
1237
  /// \param ctx ASTContext in which the type exists.
1238
  ///
1239
  /// \param typeArgs The type arguments that will be substituted for the
1240
  /// Objective-C type parameters in the subject type, which are generally
1241
  /// computed via \c Type::getObjCSubstitutions. If empty, the type
1242
  /// parameters will be replaced with their bounds or id/Class, as appropriate
1243
  /// for the context.
1244
  ///
1245
  /// \param context The context in which the subject type was written.
1246
  ///
1247
  /// \returns the resulting type.
1248
  QualType substObjCTypeArgs(ASTContext &ctx,
1249
                             ArrayRef<QualType> typeArgs,
1250
                             ObjCSubstitutionContext context) const;
1251
1252
  /// Substitute type arguments from an object type for the Objective-C type
1253
  /// parameters used in the subject type.
1254
  ///
1255
  /// This operation combines the computation of type arguments for
1256
  /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1257
  /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1258
  /// callers that need to perform a single substitution in isolation.
1259
  ///
1260
  /// \param objectType The type of the object whose member type we're
1261
  /// substituting into. For example, this might be the receiver of a message
1262
  /// or the base of a property access.
1263
  ///
1264
  /// \param dc The declaration context from which the subject type was
1265
  /// retrieved, which indicates (for example) which type parameters should
1266
  /// be substituted.
1267
  ///
1268
  /// \param context The context in which the subject type was written.
1269
  ///
1270
  /// \returns the subject type after replacing all of the Objective-C type
1271
  /// parameters with their corresponding arguments.
1272
  QualType substObjCMemberType(QualType objectType,
1273
                               const DeclContext *dc,
1274
                               ObjCSubstitutionContext context) const;
1275
1276
  /// Strip Objective-C "__kindof" types from the given type.
1277
  QualType stripObjCKindOfType(const ASTContext &ctx) const;
1278
1279
  /// Remove all qualifiers including _Atomic.
1280
  QualType getAtomicUnqualifiedType() const;
1281
1282
private:
1283
  // These methods are implemented in a separate translation unit;
1284
  // "static"-ize them to avoid creating temporary QualTypes in the
1285
  // caller.
1286
  static bool isConstant(QualType T, const ASTContext& Ctx);
1287
  static QualType getDesugaredType(QualType T, const ASTContext &Context);
1288
  static SplitQualType getSplitDesugaredType(QualType T);
1289
  static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1290
  static QualType getSingleStepDesugaredTypeImpl(QualType type,
1291
                                                 const ASTContext &C);
1292
  static QualType IgnoreParens(QualType T);
1293
  static DestructionKind isDestructedTypeImpl(QualType type);
1294
1295
  /// Check if \param RD is or contains a non-trivial C union.
1296
  static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD);
1297
  static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD);
1298
  static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD);
1299
};
1300
1301
} // namespace clang
1302
1303
namespace llvm {
1304
1305
/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1306
/// to a specific Type class.
1307
template<> struct simplify_type< ::clang::QualType> {
1308
  using SimpleType = const ::clang::Type *;
1309
1310
7.80G
  static SimpleType getSimplifiedValue(::clang::QualType Val) {
1311
7.80G
    return Val.getTypePtr();
1312
7.80G
  }
1313
};
1314
1315
// Teach SmallPtrSet that QualType is "basically a pointer".
1316
template<>
1317
struct PointerLikeTypeTraits<clang::QualType> {
1318
72.6M
  static inline void *getAsVoidPointer(clang::QualType P) {
1319
72.6M
    return P.getAsOpaquePtr();
1320
72.6M
  }
1321
1322
95.7M
  static inline clang::QualType getFromVoidPointer(void *P) {
1323
95.7M
    return clang::QualType::getFromOpaquePtr(P);
1324
95.7M
  }
1325
1326
  // Various qualifiers go in low bits.
1327
  static constexpr int NumLowBitsAvailable = 0;
1328
};
1329
1330
} // namespace llvm
1331
1332
namespace clang {
1333
1334
/// Base class that is common to both the \c ExtQuals and \c Type
1335
/// classes, which allows \c QualType to access the common fields between the
1336
/// two.
1337
class ExtQualsTypeCommonBase {
1338
  friend class ExtQuals;
1339
  friend class QualType;
1340
  friend class Type;
1341
1342
  /// The "base" type of an extended qualifiers type (\c ExtQuals) or
1343
  /// a self-referential pointer (for \c Type).
1344
  ///
1345
  /// This pointer allows an efficient mapping from a QualType to its
1346
  /// underlying type pointer.
1347
  const Type *const BaseType;
1348
1349
  /// The canonical type of this type.  A QualType.
1350
  QualType CanonicalType;
1351
1352
  ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1353
70.1M
      : BaseType(baseType), CanonicalType(canon) {}
1354
};
1355
1356
/// We can encode up to four bits in the low bits of a
1357
/// type pointer, but there are many more type qualifiers that we want
1358
/// to be able to apply to an arbitrary type.  Therefore we have this
1359
/// struct, intended to be heap-allocated and used by QualType to
1360
/// store qualifiers.
1361
///
1362
/// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1363
/// in three low bits on the QualType pointer; a fourth bit records whether
1364
/// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1365
/// Objective-C GC attributes) are much more rare.
1366
class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1367
  // NOTE: changing the fast qualifiers should be straightforward as
1368
  // long as you don't make 'const' non-fast.
1369
  // 1. Qualifiers:
1370
  //    a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1371
  //       Fast qualifiers must occupy the low-order bits.
1372
  //    b) Update Qualifiers::FastWidth and FastMask.
1373
  // 2. QualType:
1374
  //    a) Update is{Volatile,Restrict}Qualified(), defined inline.
1375
  //    b) Update remove{Volatile,Restrict}, defined near the end of
1376
  //       this header.
1377
  // 3. ASTContext:
1378
  //    a) Update get{Volatile,Restrict}Type.
1379
1380
  /// The immutable set of qualifiers applied by this node. Always contains
1381
  /// extended qualifiers.
1382
  Qualifiers Quals;
1383
1384
26.4k
  ExtQuals *this_() { return this; }
1385
1386
public:
1387
  ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1388
      : ExtQualsTypeCommonBase(baseType,
1389
                               canon.isNull() ? QualType(this_(), 0) : canon),
1390
45.0k
        Quals(quals) {
1391
45.0k
    assert(Quals.hasNonFastQualifiers()
1392
45.0k
           && "ExtQuals created with no fast qualifiers");
1393
45.0k
    assert(!Quals.hasFastQualifiers()
1394
45.0k
           && "ExtQuals created with fast qualifiers");
1395
45.0k
  }
1396
1397
2.33M
  Qualifiers getQualifiers() const { return Quals; }
1398
1399
0
  bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1400
0
  Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1401
1402
0
  bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1403
0
  Qualifiers::ObjCLifetime getObjCLifetime() const {
1404
0
    return Quals.getObjCLifetime();
1405
0
  }
1406
1407
0
  bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1408
0
  LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1409
1410
1.08M
  const Type *getBaseType() const { return BaseType; }
1411
1412
public:
1413
894k
  void Profile(llvm::FoldingSetNodeID &ID) const {
1414
894k
    Profile(ID, getBaseType(), Quals);
1415
894k
  }
1416
1417
  static void Profile(llvm::FoldingSetNodeID &ID,
1418
                      const Type *BaseType,
1419
1.45M
                      Qualifiers Quals) {
1420
1.45M
    assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!");
1421
1.45M
    ID.AddPointer(BaseType);
1422
1.45M
    Quals.Profile(ID);
1423
1.45M
  }
1424
};
1425
1426
/// The kind of C++11 ref-qualifier associated with a function type.
1427
/// This determines whether a member function's "this" object can be an
1428
/// lvalue, rvalue, or neither.
1429
enum RefQualifierKind {
1430
  /// No ref-qualifier was provided.
1431
  RQ_None = 0,
1432
1433
  /// An lvalue ref-qualifier was provided (\c &).
1434
  RQ_LValue,
1435
1436
  /// An rvalue ref-qualifier was provided (\c &&).
1437
  RQ_RValue
1438
};
1439
1440
/// Which keyword(s) were used to create an AutoType.
1441
enum class AutoTypeKeyword {
1442
  /// auto
1443
  Auto,
1444
1445
  /// decltype(auto)
1446
  DecltypeAuto,
1447
1448
  /// __auto_type (GNU extension)
1449
  GNUAutoType
1450
};
1451
1452
/// The base class of the type hierarchy.
1453
///
1454
/// A central concept with types is that each type always has a canonical
1455
/// type.  A canonical type is the type with any typedef names stripped out
1456
/// of it or the types it references.  For example, consider:
1457
///
1458
///  typedef int  foo;
1459
///  typedef foo* bar;
1460
///    'int *'    'foo *'    'bar'
1461
///
1462
/// There will be a Type object created for 'int'.  Since int is canonical, its
1463
/// CanonicalType pointer points to itself.  There is also a Type for 'foo' (a
1464
/// TypedefType).  Its CanonicalType pointer points to the 'int' Type.  Next
1465
/// there is a PointerType that represents 'int*', which, like 'int', is
1466
/// canonical.  Finally, there is a PointerType type for 'foo*' whose canonical
1467
/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1468
/// is also 'int*'.
1469
///
1470
/// Non-canonical types are useful for emitting diagnostics, without losing
1471
/// information about typedefs being used.  Canonical types are useful for type
1472
/// comparisons (they allow by-pointer equality tests) and useful for reasoning
1473
/// about whether something has a particular form (e.g. is a function type),
1474
/// because they implicitly, recursively, strip all typedefs out of a type.
1475
///
1476
/// Types, once created, are immutable.
1477
///
1478
class alignas(8) Type : public ExtQualsTypeCommonBase {
1479
public:
1480
  enum TypeClass {
1481
#define TYPE(Class, Base) Class,
1482
#define LAST_TYPE(Class) TypeLast = Class
1483
#define ABSTRACT_TYPE(Class, Base)
1484
#include "clang/AST/TypeNodes.inc"
1485
  };
1486
1487
private:
1488
  /// Bitfields required by the Type class.
1489
  class TypeBitfields {
1490
    friend class Type;
1491
    template <class T> friend class TypePropertyCache;
1492
1493
    /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1494
    unsigned TC : 8;
1495
1496
    /// Store information on the type dependency.
1497
    unsigned Dependence : llvm::BitWidth<TypeDependence>;
1498
1499
    /// True if the cache (i.e. the bitfields here starting with
1500
    /// 'Cache') is valid.
1501
    mutable unsigned CacheValid : 1;
1502
1503
    /// Linkage of this type.
1504
    mutable unsigned CachedLinkage : 3;
1505
1506
    /// Whether this type involves and local or unnamed types.
1507
    mutable unsigned CachedLocalOrUnnamed : 1;
1508
1509
    /// Whether this type comes from an AST file.
1510
    mutable unsigned FromAST : 1;
1511
1512
18.5M
    bool isCacheValid() const {
1513
18.5M
      return CacheValid;
1514
18.5M
    }
1515
1516
7.28M
    Linkage getLinkage() const {
1517
7.28M
      assert(isCacheValid() && "getting linkage from invalid cache");
1518
7.28M
      return static_cast<Linkage>(CachedLinkage);
1519
7.28M
    }
1520
1521
2.64M
    bool hasLocalOrUnnamedType() const {
1522
2.64M
      assert(isCacheValid() && "getting linkage from invalid cache");
1523
2.64M
      return CachedLocalOrUnnamed;
1524
2.64M
    }
1525
  };
1526
  enum { NumTypeBits = 8 + llvm::BitWidth<TypeDependence> + 6 };
1527
1528
protected:
1529
  // These classes allow subclasses to somewhat cleanly pack bitfields
1530
  // into Type.
1531
1532
  class ArrayTypeBitfields {
1533
    friend class ArrayType;
1534
1535
    unsigned : NumTypeBits;
1536
1537
    /// CVR qualifiers from declarations like
1538
    /// 'int X[static restrict 4]'. For function parameters only.
1539
    unsigned IndexTypeQuals : 3;
1540
1541
    /// Storage class qualifiers from declarations like
1542
    /// 'int X[static restrict 4]'. For function parameters only.
1543
    /// Actually an ArrayType::ArraySizeModifier.
1544
    unsigned SizeModifier : 3;
1545
  };
1546
1547
  class ConstantArrayTypeBitfields {
1548
    friend class ConstantArrayType;
1549
1550
    unsigned : NumTypeBits + 3 + 3;
1551
1552
    /// Whether we have a stored size expression.
1553
    unsigned HasStoredSizeExpr : 1;
1554
  };
1555
1556
  class BuiltinTypeBitfields {
1557
    friend class BuiltinType;
1558
1559
    unsigned : NumTypeBits;
1560
1561
    /// The kind (BuiltinType::Kind) of builtin type this is.
1562
    unsigned Kind : 8;
1563
  };
1564
1565
  /// FunctionTypeBitfields store various bits belonging to FunctionProtoType.
1566
  /// Only common bits are stored here. Additional uncommon bits are stored
1567
  /// in a trailing object after FunctionProtoType.
1568
  class FunctionTypeBitfields {
1569
    friend class FunctionProtoType;
1570
    friend class FunctionType;
1571
1572
    unsigned : NumTypeBits;
1573
1574
    /// Extra information which affects how the function is called, like
1575
    /// regparm and the calling convention.
1576
    unsigned ExtInfo : 13;
1577
1578
    /// The ref-qualifier associated with a \c FunctionProtoType.
1579
    ///
1580
    /// This is a value of type \c RefQualifierKind.
1581
    unsigned RefQualifier : 2;
1582
1583
    /// Used only by FunctionProtoType, put here to pack with the
1584
    /// other bitfields.
1585
    /// The qualifiers are part of FunctionProtoType because...
1586
    ///
1587
    /// C++ 8.3.5p4: The return type, the parameter type list and the
1588
    /// cv-qualifier-seq, [...], are part of the function type.
1589
    unsigned FastTypeQuals : Qualifiers::FastWidth;
1590
    /// Whether this function has extended Qualifiers.
1591
    unsigned HasExtQuals : 1;
1592
1593
    /// The number of parameters this function has, not counting '...'.
1594
    /// According to [implimits] 8 bits should be enough here but this is
1595
    /// somewhat easy to exceed with metaprogramming and so we would like to
1596
    /// keep NumParams as wide as reasonably possible.
1597
    unsigned NumParams : 16;
1598
1599
    /// The type of exception specification this function has.
1600
    unsigned ExceptionSpecType : 4;
1601
1602
    /// Whether this function has extended parameter information.
1603
    unsigned HasExtParameterInfos : 1;
1604
1605
    /// Whether the function is variadic.
1606
    unsigned Variadic : 1;
1607
1608
    /// Whether this function has a trailing return type.
1609
    unsigned HasTrailingReturn : 1;
1610
  };
1611
1612
  class ObjCObjectTypeBitfields {
1613
    friend class ObjCObjectType;
1614
1615
    unsigned : NumTypeBits;
1616
1617
    /// The number of type arguments stored directly on this object type.
1618
    unsigned NumTypeArgs : 7;
1619
1620
    /// The number of protocols stored directly on this object type.
1621
    unsigned NumProtocols : 6;
1622
1623
    /// Whether this is a "kindof" type.
1624
    unsigned IsKindOf : 1;
1625
  };
1626
1627
  class ReferenceTypeBitfields {
1628
    friend class ReferenceType;
1629
1630
    unsigned : NumTypeBits;
1631
1632
    /// True if the type was originally spelled with an lvalue sigil.
1633
    /// This is never true of rvalue references but can also be false
1634
    /// on lvalue references because of C++0x [dcl.typedef]p9,
1635
    /// as follows:
1636
    ///
1637
    ///   typedef int &ref;    // lvalue, spelled lvalue
1638
    ///   typedef int &&rvref; // rvalue
1639
    ///   ref &a;              // lvalue, inner ref, spelled lvalue
1640
    ///   ref &&a;             // lvalue, inner ref
1641
    ///   rvref &a;            // lvalue, inner ref, spelled lvalue
1642
    ///   rvref &&a;           // rvalue, inner ref
1643
    unsigned SpelledAsLValue : 1;
1644
1645
    /// True if the inner type is a reference type.  This only happens
1646
    /// in non-canonical forms.
1647
    unsigned InnerRef : 1;
1648
  };
1649
1650
  class TypeWithKeywordBitfields {
1651
    friend class TypeWithKeyword;
1652
1653
    unsigned : NumTypeBits;
1654
1655
    /// An ElaboratedTypeKeyword.  8 bits for efficient access.
1656
    unsigned Keyword : 8;
1657
  };
1658
1659
  enum { NumTypeWithKeywordBits = 8 };
1660
1661
  class ElaboratedTypeBitfields {
1662
    friend class ElaboratedType;
1663
1664
    unsigned : NumTypeBits;
1665
    unsigned : NumTypeWithKeywordBits;
1666
1667
    /// Whether the ElaboratedType has a trailing OwnedTagDecl.
1668
    unsigned HasOwnedTagDecl : 1;
1669
  };
1670
1671
  class VectorTypeBitfields {
1672
    friend class VectorType;
1673
    friend class DependentVectorType;
1674
1675
    unsigned : NumTypeBits;
1676
1677
    /// The kind of vector, either a generic vector type or some
1678
    /// target-specific vector type such as for AltiVec or Neon.
1679
    unsigned VecKind : 3;
1680
    /// The number of elements in the vector.
1681
    uint32_t NumElements;
1682
  };
1683
1684
  class AttributedTypeBitfields {
1685
    friend class AttributedType;
1686
1687
    unsigned : NumTypeBits;
1688
1689
    /// An AttributedType::Kind
1690
    unsigned AttrKind : 32 - NumTypeBits;
1691
  };
1692
1693
  class AutoTypeBitfields {
1694
    friend class AutoType;
1695
1696
    unsigned : NumTypeBits;
1697
1698
    /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1699
    /// or '__auto_type'?  AutoTypeKeyword value.
1700
    unsigned Keyword : 2;
1701
1702
    /// The number of template arguments in the type-constraints, which is
1703
    /// expected to be able to hold at least 1024 according to [implimits].
1704
    /// However as this limit is somewhat easy to hit with template
1705
    /// metaprogramming we'd prefer to keep it as large as possible.
1706
    /// At the moment it has been left as a non-bitfield since this type
1707
    /// safely fits in 64 bits as an unsigned, so there is no reason to
1708
    /// introduce the performance impact of a bitfield.
1709
    unsigned NumArgs;
1710
  };
1711
1712
  class SubstTemplateTypeParmPackTypeBitfields {
1713
    friend class SubstTemplateTypeParmPackType;
1714
1715
    unsigned : NumTypeBits;
1716
1717
    /// The number of template arguments in \c Arguments, which is
1718
    /// expected to be able to hold at least 1024 according to [implimits].
1719
    /// However as this limit is somewhat easy to hit with template
1720
    /// metaprogramming we'd prefer to keep it as large as possible.
1721
    /// At the moment it has been left as a non-bitfield since this type
1722
    /// safely fits in 64 bits as an unsigned, so there is no reason to
1723
    /// introduce the performance impact of a bitfield.
1724
    unsigned NumArgs;
1725
  };
1726
1727
  class TemplateSpecializationTypeBitfields {
1728
    friend class TemplateSpecializationType;
1729
1730
    unsigned : NumTypeBits;
1731
1732
    /// Whether this template specialization type is a substituted type alias.
1733
    unsigned TypeAlias : 1;
1734
1735
    /// The number of template arguments named in this class template
1736
    /// specialization, which is expected to be able to hold at least 1024
1737
    /// according to [implimits]. However, as this limit is somewhat easy to
1738
    /// hit with template metaprogramming we'd prefer to keep it as large
1739
    /// as possible. At the moment it has been left as a non-bitfield since
1740
    /// this type safely fits in 64 bits as an unsigned, so there is no reason
1741
    /// to introduce the performance impact of a bitfield.
1742
    unsigned NumArgs;
1743
  };
1744
1745
  class DependentTemplateSpecializationTypeBitfields {
1746
    friend class DependentTemplateSpecializationType;
1747
1748
    unsigned : NumTypeBits;
1749
    unsigned : NumTypeWithKeywordBits;
1750
1751
    /// The number of template arguments named in this class template
1752
    /// specialization, which is expected to be able to hold at least 1024
1753
    /// according to [implimits]. However, as this limit is somewhat easy to
1754
    /// hit with template metaprogramming we'd prefer to keep it as large
1755
    /// as possible. At the moment it has been left as a non-bitfield since
1756
    /// this type safely fits in 64 bits as an unsigned, so there is no reason
1757
    /// to introduce the performance impact of a bitfield.
1758
    unsigned NumArgs;
1759
  };
1760
1761
  class PackExpansionTypeBitfields {
1762
    friend class PackExpansionType;
1763
1764
    unsigned : NumTypeBits;
1765
1766
    /// The number of expansions that this pack expansion will
1767
    /// generate when substituted (+1), which is expected to be able to
1768
    /// hold at least 1024 according to [implimits]. However, as this limit
1769
    /// is somewhat easy to hit with template metaprogramming we'd prefer to
1770
    /// keep it as large as possible. At the moment it has been left as a
1771
    /// non-bitfield since this type safely fits in 64 bits as an unsigned, so
1772
    /// there is no reason to introduce the performance impact of a bitfield.
1773
    ///
1774
    /// This field will only have a non-zero value when some of the parameter
1775
    /// packs that occur within the pattern have been substituted but others
1776
    /// have not.
1777
    unsigned NumExpansions;
1778
  };
1779
1780
  union {
1781
    TypeBitfields TypeBits;
1782
    ArrayTypeBitfields ArrayTypeBits;
1783
    ConstantArrayTypeBitfields ConstantArrayTypeBits;
1784
    AttributedTypeBitfields AttributedTypeBits;
1785
    AutoTypeBitfields AutoTypeBits;
1786
    BuiltinTypeBitfields BuiltinTypeBits;
1787
    FunctionTypeBitfields FunctionTypeBits;
1788
    ObjCObjectTypeBitfields ObjCObjectTypeBits;
1789
    ReferenceTypeBitfields ReferenceTypeBits;
1790
    TypeWithKeywordBitfields TypeWithKeywordBits;
1791
    ElaboratedTypeBitfields ElaboratedTypeBits;
1792
    VectorTypeBitfields VectorTypeBits;
1793
    SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits;
1794
    TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits;
1795
    DependentTemplateSpecializationTypeBitfields
1796
      DependentTemplateSpecializationTypeBits;
1797
    PackExpansionTypeBitfields PackExpansionTypeBits;
1798
  };
1799
1800
private:
1801
  template <class T> friend class TypePropertyCache;
1802
1803
  /// Set whether this type comes from an AST file.
1804
7.81M
  void setFromAST(bool V = true) const {
1805
7.81M
    TypeBits.FromAST = V;
1806
7.81M
  }
1807
1808
protected:
1809
  friend class ASTContext;
1810
1811
  Type(TypeClass tc, QualType canon, TypeDependence Dependence)
1812
      : ExtQualsTypeCommonBase(this,
1813
70.1M
                               canon.isNull() ? QualType(this_(), 0) : canon) {
1814
70.1M
    static_assert(sizeof(*this) <= 8 + sizeof(ExtQualsTypeCommonBase),
1815
70.1M
                  "changing bitfields changed sizeof(Type)!");
1816
70.1M
    static_assert(alignof(decltype(*this)) % sizeof(void *) == 0,
1817
70.1M
                  "Insufficient alignment!");
1818
70.1M
    TypeBits.TC = tc;
1819
70.1M
    TypeBits.Dependence = static_cast<unsigned>(Dependence);
1820
70.1M
    TypeBits.CacheValid = false;
1821
70.1M
    TypeBits.CachedLocalOrUnnamed = false;
1822
70.1M
    TypeBits.CachedLinkage = NoLinkage;
1823
70.1M
    TypeBits.FromAST = false;
1824
70.1M
  }
1825
1826
  // silence VC++ warning C4355: 'this' : used in base member initializer list
1827
22.4M
  Type *this_() { return this; }
1828
1829
62.2M
  void setDependence(TypeDependence D) {
1830
62.2M
    TypeBits.Dependence = static_cast<unsigned>(D);
1831
62.2M
  }
1832
1833
62.2M
  void addDependence(TypeDependence D) { setDependence(getDependence() | D); }
1834
1835
public:
1836
  friend class ASTReader;
1837
  friend class ASTWriter;
1838
  template <class T> friend class serialization::AbstractTypeReader;
1839
  template <class T> friend class serialization::AbstractTypeWriter;
1840
1841
  Type(const Type &) = delete;
1842
  Type(Type &&) = delete;
1843
  Type &operator=(const Type &) = delete;
1844
  Type &operator=(Type &&) = delete;
1845
1846
18.6G
  TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1847
1848
  /// Whether this type comes from an AST file.
1849
4.34k
  bool isFromAST() const { return TypeBits.FromAST; }
1850
1851
  /// Whether this type is or contains an unexpanded parameter
1852
  /// pack, used to support C++0x variadic templates.
1853
  ///
1854
  /// A type that contains a parameter pack shall be expanded by the
1855
  /// ellipsis operator at some point. For example, the typedef in the
1856
  /// following example contains an unexpanded parameter pack 'T':
1857
  ///
1858
  /// \code
1859
  /// template<typename ...T>
1860
  /// struct X {
1861
  ///   typedef T* pointer_types; // ill-formed; T is a parameter pack.
1862
  /// };
1863
  /// \endcode
1864
  ///
1865
  /// Note that this routine does not specify which
1866
22.6M
  bool containsUnexpandedParameterPack() const {
1867
22.6M
    return getDependence() & TypeDependence::UnexpandedPack;
1868
22.6M
  }
1869
1870
  /// Determines if this type would be canonical if it had no further
1871
  /// qualification.
1872
1.08G
  bool isCanonicalUnqualified() const {
1873
1.08G
    return CanonicalType == QualType(this, 0);
1874
1.08G
  }
1875
1876
  /// Pull a single level of sugar off of this locally-unqualified type.
1877
  /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1878
  /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1879
  QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1880
1881
  /// As an extension, we classify types as one of "sized" or "sizeless";
1882
  /// every type is one or the other.  Standard types are all sized;
1883
  /// sizeless types are purely an extension.
1884
  ///
1885
  /// Sizeless types contain data with no specified size, alignment,
1886
  /// or layout.
1887
  bool isSizelessType() const;
1888
  bool isSizelessBuiltinType() const;
1889
1890
  /// Determines if this is a sizeless type supported by the
1891
  /// 'arm_sve_vector_bits' type attribute, which can be applied to a single
1892
  /// SVE vector or predicate, excluding tuple types such as svint32x4_t.
1893
  bool isVLSTBuiltinType() const;
1894
1895
  /// Returns the representative type for the element of an SVE builtin type.
1896
  /// This is used to represent fixed-length SVE vectors created with the
1897
  /// 'arm_sve_vector_bits' type attribute as VectorType.
1898
  QualType getSveEltType(const ASTContext &Ctx) const;
1899
1900
  /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1901
  /// object types, function types, and incomplete types.
1902
1903
  /// Return true if this is an incomplete type.
1904
  /// A type that can describe objects, but which lacks information needed to
1905
  /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1906
  /// routine will need to determine if the size is actually required.
1907
  ///
1908
  /// Def If non-null, and the type refers to some kind of declaration
1909
  /// that can be completed (such as a C struct, C++ class, or Objective-C
1910
  /// class), will be set to the declaration.
1911
  bool isIncompleteType(NamedDecl **Def = nullptr) const;
1912
1913
  /// Return true if this is an incomplete or object
1914
  /// type, in other words, not a function type.
1915
572k
  bool isIncompleteOrObjectType() const {
1916
572k
    return !isFunctionType();
1917
572k
  }
1918
1919
  /// Determine whether this type is an object type.
1920
636k
  bool isObjectType() const {
1921
    // C++ [basic.types]p8:
1922
    //   An object type is a (possibly cv-qualified) type that is not a
1923
    //   function type, not a reference type, and not a void type.
1924
636k
    return !isReferenceType() && 
!isFunctionType()614k
&&
!isVoidType()471k
;
1925
636k
  }
1926
1927
  /// Return true if this is a literal type
1928
  /// (C++11 [basic.types]p10)
1929
  bool isLiteralType(const ASTContext &Ctx) const;
1930
1931
  /// Determine if this type is a structural type, per C++20 [temp.param]p7.
1932
  bool isStructuralType() const;
1933
1934
  /// Test if this type is a standard-layout type.
1935
  /// (C++0x [basic.type]p9)
1936
  bool isStandardLayoutType() const;
1937
1938
  /// Helper methods to distinguish type categories. All type predicates
1939
  /// operate on the canonical type, ignoring typedefs and qualifiers.
1940
1941
  /// Returns true if the type is a builtin type.
1942
  bool isBuiltinType() const;
1943
1944
  /// Test for a particular builtin type.
1945
  bool isSpecificBuiltinType(unsigned K) const;
1946
1947
  /// Test for a type which does not represent an actual type-system type but
1948
  /// is instead used as a placeholder for various convenient purposes within
1949
  /// Clang.  All such types are BuiltinTypes.
1950
  bool isPlaceholderType() const;
1951
  const BuiltinType *getAsPlaceholderType() const;
1952
1953
  /// Test for a specific placeholder type.
1954
  bool isSpecificPlaceholderType(unsigned K) const;
1955
1956
  /// Test for a placeholder type other than Overload; see
1957
  /// BuiltinType::isNonOverloadPlaceholderType.
1958
  bool isNonOverloadPlaceholderType() const;
1959
1960
  /// isIntegerType() does *not* include complex integers (a GCC extension).
1961
  /// isComplexIntegerType() can be used to test for complex integers.
1962
  bool isIntegerType() const;     // C99 6.2.5p17 (int, char, bool, enum)
1963
  bool isEnumeralType() const;
1964
1965
  /// Determine whether this type is a scoped enumeration type.
1966
  bool isScopedEnumeralType() const;
1967
  bool isBooleanType() const;
1968
  bool isCharType() const;
1969
  bool isWideCharType() const;
1970
  bool isChar8Type() const;
1971
  bool isChar16Type() const;
1972
  bool isChar32Type() const;
1973
  bool isAnyCharacterType() const;
1974
  bool isIntegralType(const ASTContext &Ctx) const;
1975
1976
  /// Determine whether this type is an integral or enumeration type.
1977
  bool isIntegralOrEnumerationType() const;
1978
1979
  /// Determine whether this type is an integral or unscoped enumeration type.
1980
  bool isIntegralOrUnscopedEnumerationType() const;
1981
  bool isUnscopedEnumerationType() const;
1982
1983
  /// Floating point categories.
1984
  bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1985
  /// isComplexType() does *not* include complex integers (a GCC extension).
1986
  /// isComplexIntegerType() can be used to test for complex integers.
1987
  bool isComplexType() const;      // C99 6.2.5p11 (complex)
1988
  bool isAnyComplexType() const;   // C99 6.2.5p11 (complex) + Complex Int.
1989
  bool isFloatingType() const;     // C99 6.2.5p11 (real floating + complex)
1990
  bool isHalfType() const;         // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1991
  bool isFloat16Type() const;      // C11 extension ISO/IEC TS 18661
1992
  bool isBFloat16Type() const;
1993
  bool isFloat128Type() const;
1994
  bool isRealType() const;         // C99 6.2.5p17 (real floating + integer)
1995
  bool isArithmeticType() const;   // C99 6.2.5p18 (integer + floating)
1996
  bool isVoidType() const;         // C99 6.2.5p19
1997
  bool isScalarType() const;       // C99 6.2.5p21 (arithmetic + pointers)
1998
  bool isAggregateType() const;
1999
  bool isFundamentalType() const;
2000
  bool isCompoundType() const;
2001
2002
  // Type Predicates: Check to see if this type is structurally the specified
2003
  // type, ignoring typedefs and qualifiers.
2004
  bool isFunctionType() const;
2005
2.69k
  bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
2006
71.0M
  bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
2007
  bool isPointerType() const;
2008
  bool isAnyPointerType() const;   // Any C pointer or ObjC object pointer
2009
  bool isBlockPointerType() const;
2010
  bool isVoidPointerType() const;
2011
  bool isReferenceType() const;
2012
  bool isLValueReferenceType() const;
2013
  bool isRValueReferenceType() const;
2014
  bool isObjectPointerType() const;
2015
  bool isFunctionPointerType() const;
2016
  bool isFunctionReferenceType() const;
2017
  bool isMemberPointerType() const;
2018
  bool isMemberFunctionPointerType() const;
2019
  bool isMemberDataPointerType() const;
2020
  bool isArrayType() const;
2021
  bool isConstantArrayType() const;
2022
  bool isIncompleteArrayType() const;
2023
  bool isVariableArrayType() const;
2024
  bool isDependentSizedArrayType() const;
2025
  bool isRecordType() const;
2026
  bool isClassType() const;
2027
  bool isStructureType() const;
2028
  bool isObjCBoxableRecordType() const;
2029
  bool isInterfaceType() const;
2030
  bool isStructureOrClassType() const;
2031
  bool isUnionType() const;
2032
  bool isComplexIntegerType() const;            // GCC _Complex integer type.
2033
  bool isVectorType() const;                    // GCC vector type.
2034
  bool isExtVectorType() const;                 // Extended vector type.
2035
  bool isMatrixType() const;                    // Matrix type.
2036
  bool isConstantMatrixType() const;            // Constant matrix type.
2037
  bool isDependentAddressSpaceType() const;     // value-dependent address space qualifier
2038
  bool isObjCObjectPointerType() const;         // pointer to ObjC object
2039
  bool isObjCRetainableType() const;            // ObjC object or block pointer
2040
  bool isObjCLifetimeType() const;              // (array of)* retainable type
2041
  bool isObjCIndirectLifetimeType() const;      // (pointer to)* lifetime type
2042
  bool isObjCNSObjectType() const;              // __attribute__((NSObject))
2043
  bool isObjCIndependentClassType() const;      // __attribute__((objc_independent_class))
2044
  // FIXME: change this to 'raw' interface type, so we can used 'interface' type
2045
  // for the common case.
2046
  bool isObjCObjectType() const;                // NSString or typeof(*(id)0)
2047
  bool isObjCQualifiedInterfaceType() const;    // NSString<foo>
2048
  bool isObjCQualifiedIdType() const;           // id<foo>
2049
  bool isObjCQualifiedClassType() const;        // Class<foo>
2050
  bool isObjCObjectOrInterfaceType() const;
2051
  bool isObjCIdType() const;                    // id
2052
  bool isDecltypeType() const;
2053
  /// Was this type written with the special inert-in-ARC __unsafe_unretained
2054
  /// qualifier?
2055
  ///
2056
  /// This approximates the answer to the following question: if this
2057
  /// translation unit were compiled in ARC, would this type be qualified
2058
  /// with __unsafe_unretained?
2059
82
  bool isObjCInertUnsafeUnretainedType() const {
2060
82
    return hasAttr(attr::ObjCInertUnsafeUnretained);
2061
82
  }
2062
2063
  /// Whether the type is Objective-C 'id' or a __kindof type of an
2064
  /// object type, e.g., __kindof NSView * or __kindof id
2065
  /// <NSCopying>.
2066
  ///
2067
  /// \param bound Will be set to the bound on non-id subtype types,
2068
  /// which will be (possibly specialized) Objective-C class type, or
2069
  /// null for 'id.
2070
  bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
2071
                                  const ObjCObjectType *&bound) const;
2072
2073
  bool isObjCClassType() const;                 // Class
2074
2075
  /// Whether the type is Objective-C 'Class' or a __kindof type of an
2076
  /// Class type, e.g., __kindof Class <NSCopying>.
2077
  ///
2078
  /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
2079
  /// here because Objective-C's type system cannot express "a class
2080
  /// object for a subclass of NSFoo".
2081
  bool isObjCClassOrClassKindOfType() const;
2082
2083
  bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
2084
  bool isObjCSelType() const;                 // Class
2085
  bool isObjCBuiltinType() const;               // 'id' or 'Class'
2086
  bool isObjCARCBridgableType() const;
2087
  bool isCARCBridgableType() const;
2088
  bool isTemplateTypeParmType() const;          // C++ template type parameter
2089
  bool isNullPtrType() const;                   // C++11 std::nullptr_t
2090
  bool isNothrowT() const;                      // C++   std::nothrow_t
2091
  bool isAlignValT() const;                     // C++17 std::align_val_t
2092
  bool isStdByteType() const;                   // C++17 std::byte
2093
  bool isAtomicType() const;                    // C11 _Atomic()
2094
  bool isUndeducedAutoType() const;             // C++11 auto or
2095
                                                // C++14 decltype(auto)
2096
2097
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2098
  bool is##Id##Type() const;
2099
#include "clang/Basic/OpenCLImageTypes.def"
2100
2101
  bool isImageType() const;                     // Any OpenCL image type
2102
2103
  bool isSamplerT() const;                      // OpenCL sampler_t
2104
  bool isEventT() const;                        // OpenCL event_t
2105
  bool isClkEventT() const;                     // OpenCL clk_event_t
2106
  bool isQueueT() const;                        // OpenCL queue_t
2107
  bool isReserveIDT() const;                    // OpenCL reserve_id_t
2108
2109
#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2110
  bool is##Id##Type() const;
2111
#include "clang/Basic/OpenCLExtensionTypes.def"
2112
  // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension
2113
  bool isOCLIntelSubgroupAVCType() const;
2114
  bool isOCLExtOpaqueType() const;              // Any OpenCL extension type
2115
2116
  bool isPipeType() const;                      // OpenCL pipe type
2117
  bool isExtIntType() const;                    // Extended Int Type
2118
  bool isOpenCLSpecificType() const;            // Any OpenCL specific type
2119
2120
  /// Determines if this type, which must satisfy
2121
  /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
2122
  /// than implicitly __strong.
2123
  bool isObjCARCImplicitlyUnretainedType() const;
2124
2125
  /// Check if the type is the CUDA device builtin surface type.
2126
  bool isCUDADeviceBuiltinSurfaceType() const;
2127
  /// Check if the type is the CUDA device builtin texture type.
2128
  bool isCUDADeviceBuiltinTextureType() const;
2129
2130
  /// Return the implicit lifetime for this type, which must not be dependent.
2131
  Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
2132
2133
  enum ScalarTypeKind {
2134
    STK_CPointer,
2135
    STK_BlockPointer,
2136
    STK_ObjCObjectPointer,
2137
    STK_MemberPointer,
2138
    STK_Bool,
2139
    STK_Integral,
2140
    STK_Floating,
2141
    STK_IntegralComplex,
2142
    STK_FloatingComplex,
2143
    STK_FixedPoint
2144
  };
2145
2146
  /// Given that this is a scalar type, classify it.
2147
  ScalarTypeKind getScalarTypeKind() const;
2148
2149
774M
  TypeDependence getDependence() const {
2150
774M
    return static_cast<TypeDependence>(TypeBits.Dependence);
2151
774M
  }
2152
2153
  /// Whether this type is an error type.
2154
76.5M
  bool containsErrors() const {
2155
76.5M
    return getDependence() & TypeDependence::Error;
2156
76.5M
  }
2157
2158
  /// Whether this type is a dependent type, meaning that its definition
2159
  /// somehow depends on a template parameter (C++ [temp.dep.type]).
2160
264M
  bool isDependentType() const {
2161
264M
    return getDependence() & TypeDependence::Dependent;
2162
264M
  }
2163
2164
  /// Determine whether this type is an instantiation-dependent type,
2165
  /// meaning that the type involves a template parameter (even if the
2166
  /// definition does not actually depend on the type substituted for that
2167
  /// template parameter).
2168
50.8M
  bool isInstantiationDependentType() const {
2169
50.8M
    return getDependence() & TypeDependence::Instantiation;
2170
50.8M
  }
2171
2172
  /// Determine whether this type is an undeduced type, meaning that
2173
  /// it somehow involves a C++11 'auto' type or similar which has not yet been
2174
  /// deduced.
2175
  bool isUndeducedType() const;
2176
2177
  /// Whether this type is a variably-modified type (C99 6.7.5).
2178
100M
  bool isVariablyModifiedType() const {
2179
100M
    return getDependence() & TypeDependence::VariablyModified;
2180
100M
  }
2181
2182
  /// Whether this type involves a variable-length array type
2183
  /// with a definite size.
2184
  bool hasSizedVLAType() const;
2185
2186
  /// Whether this type is or contains a local or unnamed type.
2187
  bool hasUnnamedOrLocalType() const;
2188
2189
  bool isOverloadableType() const;
2190
2191
  /// Determine wither this type is a C++ elaborated-type-specifier.
2192
  bool isElaboratedTypeSpecifier() const;
2193
2194
  bool canDecayToPointerType() const;
2195
2196
  /// Whether this type is represented natively as a pointer.  This includes
2197
  /// pointers, references, block pointers, and Objective-C interface,
2198
  /// qualified id, and qualified interface types, as well as nullptr_t.
2199
  bool hasPointerRepresentation() const;
2200
2201
  /// Whether this type can represent an objective pointer type for the
2202
  /// purpose of GC'ability
2203
  bool hasObjCPointerRepresentation() const;
2204
2205
  /// Determine whether this type has an integer representation
2206
  /// of some sort, e.g., it is an integer type or a vector.
2207
  bool hasIntegerRepresentation() const;
2208
2209
  /// Determine whether this type has an signed integer representation
2210
  /// of some sort, e.g., it is an signed integer type or a vector.
2211
  bool hasSignedIntegerRepresentation() const;
2212
2213
  /// Determine whether this type has an unsigned integer representation
2214
  /// of some sort, e.g., it is an unsigned integer type or a vector.
2215
  bool hasUnsignedIntegerRepresentation() const;
2216
2217
  /// Determine whether this type has a floating-point representation
2218
  /// of some sort, e.g., it is a floating-point type or a vector thereof.
2219
  bool hasFloatingRepresentation() const;
2220
2221
  // Type Checking Functions: Check to see if this type is structurally the
2222
  // specified type, ignoring typedefs and qualifiers, and return a pointer to
2223
  // the best type we can.
2224
  const RecordType *getAsStructureType() const;
2225
  /// NOTE: getAs*ArrayType are methods on ASTContext.
2226
  const RecordType *getAsUnionType() const;
2227
  const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
2228
  const ObjCObjectType *getAsObjCInterfaceType() const;
2229
2230
  // The following is a convenience method that returns an ObjCObjectPointerType
2231
  // for object declared using an interface.
2232
  const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
2233
  const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
2234
  const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
2235
  const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
2236
2237
  /// Retrieves the CXXRecordDecl that this type refers to, either
2238
  /// because the type is a RecordType or because it is the injected-class-name
2239
  /// type of a class template or class template partial specialization.
2240
  CXXRecordDecl *getAsCXXRecordDecl() const;
2241
2242
  /// Retrieves the RecordDecl this type refers to.
2243
  RecordDecl *getAsRecordDecl() const;
2244
2245
  /// Retrieves the TagDecl that this type refers to, either
2246
  /// because the type is a TagType or because it is the injected-class-name
2247
  /// type of a class template or class template partial specialization.
2248
  TagDecl *getAsTagDecl() const;
2249
2250
  /// If this is a pointer or reference to a RecordType, return the
2251
  /// CXXRecordDecl that the type refers to.
2252
  ///
2253
  /// If this is not a pointer or reference, or the type being pointed to does
2254
  /// not refer to a CXXRecordDecl, returns NULL.
2255
  const CXXRecordDecl *getPointeeCXXRecordDecl() const;
2256
2257
  /// Get the DeducedType whose type will be deduced for a variable with
2258
  /// an initializer of this type. This looks through declarators like pointer
2259
  /// types, but not through decltype or typedefs.
2260
  DeducedType *getContainedDeducedType() const;
2261
2262
  /// Get the AutoType whose type will be deduced for a variable with
2263
  /// an initializer of this type. This looks through declarators like pointer
2264
  /// types, but not through decltype or typedefs.
2265
3.17M
  AutoType *getContainedAutoType() const {
2266
3.17M
    return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2267
3.17M
  }
2268
2269
  /// Determine whether this type was written with a leading 'auto'
2270
  /// corresponding to a trailing return type (possibly for a nested
2271
  /// function type within a pointer to function type or similar).
2272
  bool hasAutoForTrailingReturnType() const;
2273
2274
  /// Member-template getAs<specific type>'.  Look through sugar for
2275
  /// an instance of \<specific type>.   This scheme will eventually
2276
  /// replace the specific getAsXXXX methods above.
2277
  ///
2278
  /// There are some specializations of this member template listed
2279
  /// immediately following this class.
2280
  template <typename T> const T *getAs() const;
2281
2282
  /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2283
  /// of sugar (parens, attributes, etc) for an instance of \<specific type>.
2284
  /// This is used when you need to walk over sugar nodes that represent some
2285
  /// kind of type adjustment from a type that was written as a \<specific type>
2286
  /// to another type that is still canonically a \<specific type>.
2287
  template <typename T> const T *getAsAdjusted() const;
2288
2289
  /// A variant of getAs<> for array types which silently discards
2290
  /// qualifiers from the outermost type.
2291
  const ArrayType *getAsArrayTypeUnsafe() const;
2292
2293
  /// Member-template castAs<specific type>.  Look through sugar for
2294
  /// the underlying instance of \<specific type>.
2295
  ///
2296
  /// This method has the same relationship to getAs<T> as cast<T> has
2297
  /// to dyn_cast<T>; which is to say, the underlying type *must*
2298
  /// have the intended type, and this method will never return null.
2299
  template <typename T> const T *castAs() const;
2300
2301
  /// A variant of castAs<> for array type which silently discards
2302
  /// qualifiers from the outermost type.
2303
  const ArrayType *castAsArrayTypeUnsafe() const;
2304
2305
  /// Determine whether this type had the specified attribute applied to it
2306
  /// (looking through top-level type sugar).
2307
  bool hasAttr(attr::Kind AK) const;
2308
2309
  /// Get the base element type of this type, potentially discarding type
2310
  /// qualifiers.  This should never be used when type qualifiers
2311
  /// are meaningful.
2312
  const Type *getBaseElementTypeUnsafe() const;
2313
2314
  /// If this is an array type, return the element type of the array,
2315
  /// potentially with type qualifiers missing.
2316
  /// This should never be used when type qualifiers are meaningful.
2317
  const Type *getArrayElementTypeNoTypeQual() const;
2318
2319
  /// If this is a pointer type, return the pointee type.
2320
  /// If this is an array type, return the array element type.
2321
  /// This should never be used when type qualifiers are meaningful.
2322
  const Type *getPointeeOrArrayElementType() const;
2323
2324
  /// If this is a pointer, ObjC object pointer, or block
2325
  /// pointer, this returns the respective pointee.
2326
  QualType getPointeeType() const;
2327
2328
  /// Return the specified type with any "sugar" removed from the type,
2329
  /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2330
  const Type *getUnqualifiedDesugaredType() const;
2331
2332
  /// More type predicates useful for type checking/promotion
2333
  bool isPromotableIntegerType() const; // C99 6.3.1.1p2
2334
2335
  /// Return true if this is an integer type that is
2336
  /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2337
  /// or an enum decl which has a signed representation.
2338
  bool isSignedIntegerType() const;
2339
2340
  /// Return true if this is an integer type that is
2341
  /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2342
  /// or an enum decl which has an unsigned representation.
2343
  bool isUnsignedIntegerType() const;
2344
2345
  /// Determines whether this is an integer type that is signed or an
2346
  /// enumeration types whose underlying type is a signed integer type.
2347
  bool isSignedIntegerOrEnumerationType() const;
2348
2349
  /// Determines whether this is an integer type that is unsigned or an
2350
  /// enumeration types whose underlying type is a unsigned integer type.
2351
  bool isUnsignedIntegerOrEnumerationType() const;
2352
2353
  /// Return true if this is a fixed point type according to
2354
  /// ISO/IEC JTC1 SC22 WG14 N1169.
2355
  bool isFixedPointType() const;
2356
2357
  /// Return true if this is a fixed point or integer type.
2358
  bool isFixedPointOrIntegerType() const;
2359
2360
  /// Return true if this is a saturated fixed point type according to
2361
  /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2362
  bool isSaturatedFixedPointType() const;
2363
2364
  /// Return true if this is a saturated fixed point type according to
2365
  /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2366
  bool isUnsaturatedFixedPointType() const;
2367
2368
  /// Return true if this is a fixed point type that is signed according
2369
  /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2370
  bool isSignedFixedPointType() const;
2371
2372
  /// Return true if this is a fixed point type that is unsigned according
2373
  /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2374
  bool isUnsignedFixedPointType() const;
2375
2376
  /// Return true if this is not a variable sized type,
2377
  /// according to the rules of C99 6.7.5p3.  It is not legal to call this on
2378
  /// incomplete types.
2379
  bool isConstantSizeType() const;
2380
2381
  /// Returns true if this type can be represented by some
2382
  /// set of type specifiers.
2383
  bool isSpecifierType() const;
2384
2385
  /// Determine the linkage of this type.
2386
  Linkage getLinkage() const;
2387
2388
  /// Determine the visibility of this type.
2389
2.10k
  Visibility getVisibility() const {
2390
2.10k
    return getLinkageAndVisibility().getVisibility();
2391
2.10k
  }
2392
2393
  /// Return true if the visibility was explicitly set is the code.
2394
0
  bool isVisibilityExplicit() const {
2395
0
    return getLinkageAndVisibility().isVisibilityExplicit();
2396
0
  }
2397
2398
  /// Determine the linkage and visibility of this type.
2399
  LinkageInfo getLinkageAndVisibility() const;
2400
2401
  /// True if the computed linkage is valid. Used for consistency
2402
  /// checking. Should always return true.
2403
  bool isLinkageValid() const;
2404
2405
  /// Determine the nullability of the given type.
2406
  ///
2407
  /// Note that nullability is only captured as sugar within the type
2408
  /// system, not as part of the canonical type, so nullability will
2409
  /// be lost by canonicalization and desugaring.
2410
  Optional<NullabilityKind> getNullability(const ASTContext &context) const;
2411
2412
  /// Determine whether the given type can have a nullability
2413
  /// specifier applied to it, i.e., if it is any kind of pointer type.
2414
  ///
2415
  /// \param ResultIfUnknown The value to return if we don't yet know whether
2416
  ///        this type can have nullability because it is dependent.
2417
  bool canHaveNullability(bool ResultIfUnknown = true) const;
2418
2419
  /// Retrieve the set of substitutions required when accessing a member
2420
  /// of the Objective-C receiver type that is declared in the given context.
2421
  ///
2422
  /// \c *this is the type of the object we're operating on, e.g., the
2423
  /// receiver for a message send or the base of a property access, and is
2424
  /// expected to be of some object or object pointer type.
2425
  ///
2426
  /// \param dc The declaration context for which we are building up a
2427
  /// substitution mapping, which should be an Objective-C class, extension,
2428
  /// category, or method within.
2429
  ///
2430
  /// \returns an array of type arguments that can be substituted for
2431
  /// the type parameters of the given declaration context in any type described
2432
  /// within that context, or an empty optional to indicate that no
2433
  /// substitution is required.
2434
  Optional<ArrayRef<QualType>>
2435
  getObjCSubstitutions(const DeclContext *dc) const;
2436
2437
  /// Determines if this is an ObjC interface type that may accept type
2438
  /// parameters.
2439
  bool acceptsObjCTypeParams() const;
2440
2441
  const char *getTypeClassName() const;
2442
2443
592M
  QualType getCanonicalTypeInternal() const {
2444
592M
    return CanonicalType;
2445
592M
  }
2446
2447
  CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2448
  void dump() const;
2449
  void dump(llvm::raw_ostream &OS, const ASTContext &Context) const;
2450
};
2451
2452
/// This will check for a TypedefType by removing any existing sugar
2453
/// until it reaches a TypedefType or a non-sugared type.
2454
template <> const TypedefType *Type::getAs() const;
2455
2456
/// This will check for a TemplateSpecializationType by removing any
2457
/// existing sugar until it reaches a TemplateSpecializationType or a
2458
/// non-sugared type.
2459
template <> const TemplateSpecializationType *Type::getAs() const;
2460
2461
/// This will check for an AttributedType by removing any existing sugar
2462
/// until it reaches an AttributedType or a non-sugared type.
2463
template <> const AttributedType *Type::getAs() const;
2464
2465
// We can do canonical leaf types faster, because we don't have to
2466
// worry about preserving child type decoration.
2467
#define TYPE(Class, Base)
2468
#define LEAF_TYPE(Class) \
2469
1.17G
template <> inline const Class##Type *Type::getAs() const { \
2470
1.17G
  return dyn_cast<Class##Type>(CanonicalType); \
2471
1.17G
} \
clang::BuiltinType const* clang::Type::getAs<clang::BuiltinType>() const
Line
Count
Source
2469
780M
template <> inline const Class##Type *Type::getAs() const { \
2470
780M
  return dyn_cast<Class##Type>(CanonicalType); \
2471
780M
} \
clang::EnumType const* clang::Type::getAs<clang::EnumType>() const
Line
Count
Source
2469
89.9M
template <> inline const Class##Type *Type::getAs() const { \
2470
89.9M
  return dyn_cast<Class##Type>(CanonicalType); \
2471
89.9M
} \
clang::InjectedClassNameType const* clang::Type::getAs<clang::InjectedClassNameType>() const
Line
Count
Source
2469
158M
template <> inline const Class##Type *Type::getAs() const { \
2470
158M
  return dyn_cast<Class##Type>(CanonicalType); \
2471
158M
} \
clang::ObjCInterfaceType const* clang::Type::getAs<clang::ObjCInterfaceType>() const
Line
Count
Source
2469
53.8M
template <> inline const Class##Type *Type::getAs() const { \
2470
53.8M
  return dyn_cast<Class##Type>(CanonicalType); \
2471
53.8M
} \
clang::RecordType const* clang::Type::getAs<clang::RecordType>() const
Line
Count
Source
2469
86.7M
template <> inline const Class##Type *Type::getAs() const { \
2470
86.7M
  return dyn_cast<Class##Type>(CanonicalType); \
2471
86.7M
} \
clang::TemplateTypeParmType const* clang::Type::getAs<clang::TemplateTypeParmType>() const
Line
Count
Source
2469
3.23M
template <> inline const Class##Type *Type::getAs() const { \
2470
3.23M
  return dyn_cast<Class##Type>(CanonicalType); \
2471
3.23M
} \
2472
212M
template <> inline const Class##Type *Type::castAs() const { \
2473
212M
  return cast<Class##Type>(CanonicalType); \
2474
212M
}
clang::BuiltinType const* clang::Type::castAs<clang::BuiltinType>() const
Line
Count
Source
2472
2.29M
template <> inline const Class##Type *Type::castAs() const { \
2473
2.29M
  return cast<Class##Type>(CanonicalType); \
2474
2.29M
}
clang::EnumType const* clang::Type::castAs<clang::EnumType>() const
Line
Count
Source
2472
4.58k
template <> inline const Class##Type *Type::castAs() const { \
2473
4.58k
  return cast<Class##Type>(CanonicalType); \
2474
4.58k
}
Unexecuted instantiation: clang::InjectedClassNameType const* clang::Type::castAs<clang::InjectedClassNameType>() const
clang::ObjCInterfaceType const* clang::Type::castAs<clang::ObjCInterfaceType>() const
Line
Count
Source
2472
24.6k
template <> inline const Class##Type *Type::castAs() const { \
2473
24.6k
  return cast<Class##Type>(CanonicalType); \
2474
24.6k
}
clang::RecordType const* clang::Type::castAs<clang::RecordType>() const
Line
Count
Source
2472
12.2M
template <> inline const Class##Type *Type::castAs() const { \
2473
12.2M
  return cast<Class##Type>(CanonicalType); \
2474
12.2M
}
clang::TemplateTypeParmType const* clang::Type::castAs<clang::TemplateTypeParmType>() const
Line
Count
Source
2472
198M
template <> inline const Class##Type *Type::castAs() const { \
2473
198M
  return cast<Class##Type>(CanonicalType); \
2474
198M
}
2475
#include "clang/AST/TypeNodes.inc"
2476
2477
/// This class is used for builtin types like 'int'.  Builtin
2478
/// types are always canonical and have a literal name field.
2479
class BuiltinType : public Type {
2480
public:
2481
  enum Kind {
2482
// OpenCL image types
2483
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2484
#include "clang/Basic/OpenCLImageTypes.def"
2485
// OpenCL extension types
2486
#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id,
2487
#include "clang/Basic/OpenCLExtensionTypes.def"
2488
// SVE Types
2489
#define SVE_TYPE(Name, Id, SingletonId) Id,
2490
#include "clang/Basic/AArch64SVEACLETypes.def"
2491
// PPC MMA Types
2492
#define PPC_MMA_VECTOR_TYPE(Name, Id, Size) Id,
2493
#include "clang/Basic/PPCTypes.def"
2494
// All other builtin types
2495
#define BUILTIN_TYPE(Id, SingletonId) Id,
2496
#define LAST_BUILTIN_TYPE(Id) LastKind = Id
2497
#include "clang/AST/BuiltinTypes.def"
2498
  };
2499
2500
private:
2501
  friend class ASTContext; // ASTContext creates these.
2502
2503
  BuiltinType(Kind K)
2504
      : Type(Builtin, QualType(),
2505
             K == Dependent ? TypeDependence::DependentInstantiation
2506
5.38M
                            : TypeDependence::None) {
2507
5.38M
    BuiltinTypeBits.Kind = K;
2508
5.38M
  }
2509
2510
public:
2511
1.42G
  Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2512
  StringRef getName(const PrintingPolicy &Policy) const;
2513
2514
3.08k
  const char *getNameAsCString(const PrintingPolicy &Policy) const {
2515
    // The StringRef is null-terminated.
2516
3.08k
    StringRef str = getName(Policy);
2517
3.08k
    assert(!str.empty() && str.data()[str.size()] == '\0');
2518
3.08k
    return str.data();
2519
3.08k
  }
2520
2521
37.9M
  bool isSugared() const { return false; }
2522
0
  QualType desugar() const { return QualType(this, 0); }
2523
2524
4.18M
  bool isInteger() const {
2525
4.18M
    return getKind() >= Bool && 
getKind() <= Int1284.18M
;
2526
4.18M
  }
2527
2528
95.6k
  bool isSignedInteger() const {
2529
95.6k
    return getKind() >= Char_S && 
getKind() <= Int12859.0k
;
2530
95.6k
  }
2531
2532
3.02M
  bool isUnsignedInteger() const {
2533
3.02M
    return getKind() >= Bool && getKind() <= UInt128;
2534
3.02M
  }
2535
2536
7.69M
  bool isFloatingPoint() const {
2537
7.69M
    return getKind() >= Half && 
getKind() <= Float1284.32M
;
2538
7.69M
  }
2539
2540
  /// Determines whether the given kind corresponds to a placeholder type.
2541
68.1M
  static bool isPlaceholderTypeKind(Kind K) {
2542
68.1M
    return K >= Overload;
2543
68.1M
  }
2544
2545
  /// Determines whether this type is a placeholder type, i.e. a type
2546
  /// which cannot appear in arbitrary positions in a fully-formed
2547
  /// expression.
2548
63.3M
  bool isPlaceholderType() const {
2549
63.3M
    return isPlaceholderTypeKind(getKind());
2550
63.3M
  }
2551
2552
  /// Determines whether this type is a placeholder type other than
2553
  /// Overload.  Most placeholder types require only syntactic
2554
  /// information about their context in order to be resolved (e.g.
2555
  /// whether it is a call expression), which means they can (and
2556
  /// should) be resolved in an earlier "phase" of analysis.
2557
  /// Overload expressions sometimes pick up further information
2558
  /// from their context, like whether the context expects a
2559
  /// specific function-pointer type, and so frequently need
2560
  /// special treatment.
2561
4.63M
  bool isNonOverloadPlaceholderType() const {
2562
4.63M
    return getKind() > Overload;
2563
4.63M
  }
2564
2565
2.69G
  static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2566
};
2567
2568
/// Complex values, per C99 6.2.5p11.  This supports the C99 complex
2569
/// types (_Complex float etc) as well as the GCC integer complex extensions.
2570
class ComplexType : public Type, public llvm::FoldingSetNode {
2571
  friend class ASTContext; // ASTContext creates these.
2572
2573
  QualType ElementType;
2574
2575
  ComplexType(QualType Element, QualType CanonicalPtr)
2576
      : Type(Complex, CanonicalPtr, Element->getDependence()),
2577
344k
        ElementType(Element) {}
2578
2579
public:
2580
51.0k
  QualType getElementType() const { return ElementType; }
2581
2582
12.3k
  bool isSugared() const { return false; }
2583
0
  QualType desugar() const { return QualType(this, 0); }
2584
2585
20.8k
  void Profile(llvm::FoldingSetNodeID &ID) {
2586
20.8k
    Profile(ID, getElementType());
2587
20.8k
  }
2588
2589
377k
  static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2590
377k
    ID.AddPointer(Element.getAsOpaquePtr());
2591
377k
  }
2592
2593
73.1M
  static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2594
};
2595
2596
/// Sugar for parentheses used when specifying types.
2597
class ParenType : public Type, public llvm::FoldingSetNode {
2598
  friend class ASTContext; // ASTContext creates these.
2599
2600
  QualType Inner;
2601
2602
  ParenType(QualType InnerType, QualType CanonType)
2603
241k
      : Type(Paren, CanonType, InnerType->getDependence()), Inner(InnerType) {}
2604
2605
public:
2606
3.60M
  QualType getInnerType() const { return Inner; }
2607
2608
477k
  bool isSugared() const { return true; }
2609
478k
  QualType desugar() const { return getInnerType(); }
2610
2611
989k
  void Profile(llvm::FoldingSetNodeID &ID) {
2612
989k
    Profile(ID, getInnerType());
2613
989k
  }
2614
2615
1.36M
  static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2616
1.36M
    Inner.Profile(ID);
2617
1.36M
  }
2618
2619
24.6M
  static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2620
};
2621
2622
/// PointerType - C99 6.7.5.1 - Pointer Declarators.
2623
class PointerType : public Type, public llvm::FoldingSetNode {
2624
  friend class ASTContext; // ASTContext creates these.
2625
2626
  QualType PointeeType;
2627
2628
  PointerType(QualType Pointee, QualType CanonicalPtr)
2629
      : Type(Pointer, CanonicalPtr, Pointee->getDependence()),
2630
4.69M
        PointeeType(Pointee) {}
2631
2632
public:
2633
111M
  QualType getPointeeType() const { return PointeeType; }
2634
2635
18.2M
  bool isSugared() const { return false; }
2636
0
  QualType desugar() const { return QualType(this, 0); }
2637
2638
34.9M
  void Profile(llvm::FoldingSetNodeID &ID) {
2639
34.9M
    Profile(ID, getPointeeType());
2640
34.9M
  }
2641
2642
56.7M
  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2643
56.7M
    ID.AddPointer(Pointee.getAsOpaquePtr());
2644
56.7M
  }
2645
2646
790M
  static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2647
};
2648
2649
/// Represents a type which was implicitly adjusted by the semantic
2650
/// engine for arbitrary reasons.  For example, array and function types can
2651
/// decay, and function types can have their calling conventions adjusted.
2652
class AdjustedType : public Type, public llvm::FoldingSetNode {
2653
  QualType OriginalTy;
2654
  QualType AdjustedTy;
2655
2656
protected:
2657
  friend class ASTContext; // ASTContext creates these.
2658
2659
  AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2660
               QualType CanonicalPtr)
2661
      : Type(TC, CanonicalPtr, OriginalTy->getDependence()),
2662
35.2k
        OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2663
2664
public:
2665
32.9k
  QualType getOriginalType() const { return OriginalTy; }
2666
50.7k
  QualType getAdjustedType() const { return AdjustedTy; }
2667
2668
59.0k
  bool isSugared() const { return true; }
2669
59.1k
  QualType desugar() const { return AdjustedTy; }
2670
2671
107k
  void Profile(llvm::FoldingSetNodeID &ID) {
2672
107k
    Profile(ID, OriginalTy, AdjustedTy);
2673
107k
  }
2674
2675
208k
  static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2676
208k
    ID.AddPointer(Orig.getAsOpaquePtr());
2677
208k
    ID.AddPointer(New.getAsOpaquePtr());
2678
208k
  }
2679
2680
37.3M
  static bool classof(const Type *T) {
2681
37.3M
    return T->getTypeClass() == Adjusted || 
T->getTypeClass() == Decayed37.3M
;
2682
37.3M
  }
2683
};
2684
2685
/// Represents a pointer type decayed from an array or function type.
2686
class DecayedType : public AdjustedType {
2687
  friend class ASTContext; // ASTContext creates these.
2688
2689
  inline
2690
  DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2691
2692
public:
2693
98
  QualType getDecayedType() const { return getAdjustedType(); }
2694
2695
  inline QualType getPointeeType() const;
2696
2697
12.1M
  static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2698
};
2699
2700
/// Pointer to a block type.
2701
/// This type is to represent types syntactically represented as
2702
/// "void (^)(int)", etc. Pointee is required to always be a function type.
2703
class BlockPointerType : public Type, public llvm::FoldingSetNode {
2704
  friend class ASTContext; // ASTContext creates these.
2705
2706
  // Block is some kind of pointer type
2707
  QualType PointeeType;
2708
2709
  BlockPointerType(QualType Pointee, QualType CanonicalCls)
2710
      : Type(BlockPointer, CanonicalCls, Pointee->getDependence()),
2711
81.3k
        PointeeType(Pointee) {}
2712
2713
public:
2714
  // Get the pointee type. Pointee is required to always be a function type.
2715
669k
  QualType getPointeeType() const { return PointeeType; }
2716
2717
173k
  bool isSugared() const { return false; }
2718
0
  QualType desugar() const { return QualType(this, 0); }
2719
2720
226k
  void Profile(llvm::FoldingSetNodeID &ID) {
2721
226k
      Profile(ID, getPointeeType());
2722
226k
  }
2723
2724
349k
  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2725
349k
      ID.AddPointer(Pointee.getAsOpaquePtr());
2726
349k
  }
2727
2728
181M
  static bool classof(const Type *T) {
2729
181M
    return T->getTypeClass() == BlockPointer;
2730
181M
  }
2731
};
2732
2733
/// Base for LValueReferenceType and RValueReferenceType
2734
class ReferenceType : public Type, public llvm::FoldingSetNode {
2735
  QualType PointeeType;
2736
2737
protected:
2738
  ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2739
                bool SpelledAsLValue)
2740
      : Type(tc, CanonicalRef, Referencee->getDependence()),
2741
2.69M
        PointeeType(Referencee) {
2742
2.69M
    ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2743
2.69M
    ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2744
2.69M
  }
2745
2746
public:
2747
20.8M
  bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2748
18.4M
  bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2749
2750
29.3M
  QualType getPointeeTypeAsWritten() const { return PointeeType; }
2751
2752
17.2M
  QualType getPointeeType() const {
2753
    // FIXME: this might strip inner qualifiers; okay?
2754
17.2M
    const ReferenceType *T = this;
2755
17.4M
    while (T->isInnerRef())
2756
152k
      T = T->PointeeType->castAs<ReferenceType>();
2757
17.2M
    return T->PointeeType;
2758
17.2M
  }
2759
2760
18.9M
  void Profile(llvm::FoldingSetNodeID &ID) {
2761
18.9M
    Profile(ID, PointeeType, isSpelledAsLValue());
2762
18.9M
  }
2763
2764
  static void Profile(llvm::FoldingSetNodeID &ID,
2765
                      QualType Referencee,
2766
28.8M
                      bool SpelledAsLValue) {
2767
28.8M
    ID.AddPointer(Referencee.getAsOpaquePtr());
2768
28.8M
    ID.AddBoolean(SpelledAsLValue);
2769
28.8M
  }
2770
2771
545M
  static bool classof(const Type *T) {
2772
545M
    return T->getTypeClass() == LValueReference ||
2773
485M
           T->getTypeClass() == RValueReference;
2774
545M
  }
2775
};
2776
2777
/// An lvalue reference type, per C++11 [dcl.ref].
2778
class LValueReferenceType : public ReferenceType {
2779
  friend class ASTContext; // ASTContext creates these
2780
2781
  LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2782
                      bool SpelledAsLValue)
2783
      : ReferenceType(LValueReference, Referencee, CanonicalRef,
2784
2.11M
                      SpelledAsLValue) {}
2785
2786
public:
2787
1.71M
  bool isSugared() const { return false; }
2788
0
  QualType desugar() const { return QualType(this, 0); }
2789
2790
37.9M
  static bool classof(const Type *T) {
2791
37.9M
    return T->getTypeClass() == LValueReference;
2792
37.9M
  }
2793
};
2794
2795
/// An rvalue reference type, per C++11 [dcl.ref].
2796
class RValueReferenceType : public ReferenceType {
2797
  friend class ASTContext; // ASTContext creates these
2798
2799
  RValueReferenceType(QualType Referencee, QualType CanonicalRef)
2800
579k
       : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
2801
2802
public:
2803
274k
  bool isSugared() const { return false; }
2804
0
  QualType desugar() const { return QualType(this, 0); }
2805
2806
18.6M
  static bool classof(const Type *T) {
2807
18.6M
    return T->getTypeClass() == RValueReference;
2808
18.6M
  }
2809
};
2810
2811
/// A pointer to member type per C++ 8.3.3 - Pointers to members.
2812
///
2813
/// This includes both pointers to data members and pointer to member functions.
2814
class MemberPointerType : public Type, public llvm::FoldingSetNode {
2815
  friend class ASTContext; // ASTContext creates these.
2816
2817
  QualType PointeeType;
2818
2819
  /// The class of which the pointee is a member. Must ultimately be a
2820
  /// RecordType, but could be a typedef or a template parameter too.
2821
  const Type *Class;
2822
2823
  MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
2824
      : Type(MemberPointer, CanonicalPtr,
2825
             (Cls->getDependence() & ~TypeDependence::VariablyModified) |
2826
                 Pointee->getDependence()),
2827
45.1k
        PointeeType(Pointee), Class(Cls) {}
2828
2829
public:
2830
566k
  QualType getPointeeType() const { return PointeeType; }
2831
2832
  /// Returns true if the member type (i.e. the pointee type) is a
2833
  /// function type rather than a data-member type.
2834
5.14k
  bool isMemberFunctionPointer() const {
2835
5.14k
    return PointeeType->isFunctionProtoType();
2836
5.14k
  }
2837
2838
  /// Returns true if the member type (i.e. the pointee type) is a
2839
  /// data type rather than a function type.
2840
795
  bool isMemberDataPointer() const {
2841
795
    return !PointeeType->isFunctionProtoType();
2842
795
  }
2843
2844
226k
  const Type *getClass() const { return Class; }
2845
  CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2846
2847
44.2k
  bool isSugared() const { return false; }
2848
0
  QualType desugar() const { return QualType(this, 0); }
2849
2850
68.4k
  void Profile(llvm::FoldingSetNodeID &ID) {
2851
68.4k
    Profile(ID, getPointeeType(), getClass());
2852
68.4k
  }
2853
2854
  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2855
129k
                      const Type *Class) {
2856
129k
    ID.AddPointer(Pointee.getAsOpaquePtr());
2857
129k
    ID.AddPointer(Class);
2858
129k
  }
2859
2860
304M
  static bool classof(const Type *T) {
2861
304M
    return T->getTypeClass() == MemberPointer;
2862
304M
  }
2863
};
2864
2865
/// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2866
class ArrayType : public Type, public llvm::FoldingSetNode {
2867
public:
2868
  /// Capture whether this is a normal array (e.g. int X[4])
2869
  /// an array with a static size (e.g. int X[static 4]), or an array
2870
  /// with a star size (e.g. int X[*]).
2871
  /// 'static' is only allowed on function parameters.
2872
  enum ArraySizeModifier {
2873
    Normal, Static, Star
2874
  };
2875
2876
private:
2877
  /// The element type of the array.
2878
  QualType ElementType;
2879
2880
protected:
2881
  friend class ASTContext; // ASTContext creates these.
2882
2883
  ArrayType(TypeClass tc, QualType et, QualType can, ArraySizeModifier sm,
2884
            unsigned tq, const Expr *sz = nullptr);
2885
2886
public:
2887
14.6M
  QualType getElementType() const { return ElementType; }
2888
2889
7.71M
  ArraySizeModifier getSizeModifier() const {
2890
7.71M
    return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2891
7.71M
  }
2892
2893
509k
  Qualifiers getIndexTypeQualifiers() const {
2894
509k
    return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2895
509k
  }
2896
2897
8.19M
  unsigned getIndexTypeCVRQualifiers() const {
2898
8.19M
    return ArrayTypeBits.IndexTypeQuals;
2899
8.19M
  }
2900
2901
738M
  static bool classof(const Type *T) {
2902
738M
    return T->getTypeClass() == ConstantArray ||
2903
719M
           T->getTypeClass() == VariableArray ||
2904
719M
           T->getTypeClass() == IncompleteArray ||
2905
718M
           T->getTypeClass() == DependentSizedArray;
2906
738M
  }
2907
};
2908
2909
/// Represents the canonical version of C arrays with a specified constant size.
2910
/// For example, the canonical type for 'int A[4 + 4*100]' is a
2911
/// ConstantArrayType where the element type is 'int' and the size is 404.
2912
class ConstantArrayType final
2913
    : public ArrayType,
2914
      private llvm::TrailingObjects<ConstantArrayType, const Expr *> {
2915
  friend class ASTContext; // ASTContext creates these.
2916
  friend TrailingObjects;
2917
2918
  llvm::APInt Size; // Allows us to unique the type.
2919
2920
  ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2921
                    const Expr *sz, ArraySizeModifier sm, unsigned tq)
2922
520k
      : ArrayType(ConstantArray, et, can, sm, tq, sz), Size(size) {
2923
520k
    ConstantArrayTypeBits.HasStoredSizeExpr = sz != nullptr;
2924
520k
    if (ConstantArrayTypeBits.HasStoredSizeExpr) {
2925
14
      assert(!can.isNull() && "canonical constant array should not have size");
2926
14
      *getTrailingObjects<const Expr*>() = sz;
2927
14
    }
2928
520k
  }
2929
2930
0
  unsigned numTrailingObjects(OverloadToken<const Expr*>) const {
2931
0
    return ConstantArrayTypeBits.HasStoredSizeExpr;
2932
0
  }
2933
2934
public:
2935
8.20M
  const llvm::APInt &getSize() const { return Size; }
2936
7.57M
  const Expr *getSizeExpr() const {
2937
7.57M
    return ConstantArrayTypeBits.HasStoredSizeExpr
2938
52
               ? *getTrailingObjects<const Expr *>()
2939
7.57M
               : nullptr;
2940
7.57M
  }
2941
1.79M
  bool isSugared() const { return false; }
2942
0
  QualType desugar() const { return QualType(this, 0); }
2943
2944
  /// Determine the number of bits required to address a member of
2945
  // an array with the given element type and number of elements.
2946
  static unsigned getNumAddressingBits(const ASTContext &Context,
2947
                                       QualType ElementType,
2948
                                       const llvm::APInt &NumElements);
2949
2950
  /// Determine the maximum number of active bits that an array's size
2951
  /// can require, which limits the maximum size of the array.
2952
  static unsigned getMaxSizeBits(const ASTContext &Context);
2953
2954
7.50M
  void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
2955
7.50M
    Profile(ID, Ctx, getElementType(), getSize(), getSizeExpr(),
2956
7.50M
            getSizeModifier(), getIndexTypeCVRQualifiers());
2957
7.50M
  }
2958
2959
  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx,
2960
                      QualType ET, const llvm::APInt &ArraySize,
2961
                      const Expr *SizeExpr, ArraySizeModifier SizeMod,
2962
                      unsigned TypeQuals);
2963
2964
17.6M
  static bool classof(const Type *T) {
2965
17.6M
    return T->getTypeClass() == ConstantArray;
2966
17.6M
  }
2967
};
2968
2969
/// Represents a C array with an unspecified size.  For example 'int A[]' has
2970
/// an IncompleteArrayType where the element type is 'int' and the size is
2971
/// unspecified.
2972
class IncompleteArrayType : public ArrayType {
2973
  friend class ASTContext; // ASTContext creates these.
2974
2975
  IncompleteArrayType(QualType et, QualType can,
2976
                      ArraySizeModifier sm, unsigned tq)
2977
53.3k
      : ArrayType(IncompleteArray, et, can, sm, tq) {}
2978
2979
public:
2980
  friend class StmtIteratorBase;
2981
2982
83.1k
  bool isSugared() const { return false; }
2983
0
  QualType desugar() const { return QualType(this, 0); }
2984
2985
25.7M
  static bool classof(const Type *T) {
2986
25.7M
    return T->getTypeClass() == IncompleteArray;
2987
25.7M
  }
2988
2989
76.1k
  void Profile(llvm::FoldingSetNodeID &ID) {
2990
76.1k
    Profile(ID, getElementType(), getSizeModifier(),
2991
76.1k
            getIndexTypeCVRQualifiers());
2992
76.1k
  }
2993
2994
  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2995
172k
                      ArraySizeModifier SizeMod, unsigned TypeQuals) {
2996
172k
    ID.AddPointer(ET.getAsOpaquePtr());
2997
172k
    ID.AddInteger(SizeMod);
2998
172k
    ID.AddInteger(TypeQuals);
2999
172k
  }
3000
};
3001
3002
/// Represents a C array with a specified size that is not an
3003
/// integer-constant-expression.  For example, 'int s[x+foo()]'.
3004
/// Since the size expression is an arbitrary expression, we store it as such.
3005
///
3006
/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
3007
/// should not be: two lexically equivalent variable array types could mean
3008
/// different things, for example, these variables do not have the same type
3009
/// dynamically:
3010
///
3011
/// void foo(int x) {
3012
///   int Y[x];
3013
///   ++x;
3014
///   int Z[x];
3015
/// }
3016
class VariableArrayType : public ArrayType {
3017
  friend class ASTContext; // ASTContext creates these.
3018
3019
  /// An assignment-expression. VLA's are only permitted within
3020
  /// a function block.
3021
  Stmt *SizeExpr;
3022
3023
  /// The range spanned by the left and right array brackets.
3024
  SourceRange Brackets;
3025
3026
  VariableArrayType(QualType et, QualType can, Expr *e,
3027
                    ArraySizeModifier sm, unsigned tq,
3028
                    SourceRange brackets)
3029
      : ArrayType(VariableArray, et, can, sm, tq, e),
3030
9.72k
        SizeExpr((Stmt*) e), Brackets(brackets) {}
3031
3032
public:
3033
  friend class StmtIteratorBase;
3034
3035
63.3k
  Expr *getSizeExpr() const {
3036
    // We use C-style casts instead of cast<> here because we do not wish
3037
    // to have a dependency of Type.h on Stmt.h/Expr.h.
3038
63.3k
    return (Expr*) SizeExpr;
3039
63.3k
  }
3040
3041
621
  SourceRange getBracketsRange() const { return Brackets; }
3042
1.62k
  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3043
1.62k
  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3044
3045
49.6k
  bool isSugared() const { return false; }
3046
33
  QualType desugar() const { return QualType(this, 0); }
3047
3048
33.2M
  static bool classof(const Type *T) {
3049
33.2M
    return T->getTypeClass() == VariableArray;
3050
33.2M
  }
3051
3052
0
  void Profile(llvm::FoldingSetNodeID &ID) {
3053
0
    llvm_unreachable("Cannot unique VariableArrayTypes.");
3054
0
  }
3055
};
3056
3057
/// Represents an array type in C++ whose size is a value-dependent expression.
3058
///
3059
/// For example:
3060
/// \code
3061
/// template<typename T, int Size>
3062
/// class array {
3063
///   T data[Size];
3064
/// };
3065
/// \endcode
3066
///
3067
/// For these types, we won't actually know what the array bound is
3068
/// until template instantiation occurs, at which point this will
3069
/// become either a ConstantArrayType or a VariableArrayType.
3070
class DependentSizedArrayType : public ArrayType {
3071
  friend class ASTContext; // ASTContext creates these.
3072
3073
  const ASTContext &Context;
3074
3075
  /// An assignment expression that will instantiate to the
3076
  /// size of the array.
3077
  ///
3078
  /// The expression itself might be null, in which case the array
3079
  /// type will have its size deduced from an initializer.
3080
  Stmt *SizeExpr;
3081
3082
  /// The range spanned by the left and right array brackets.
3083
  SourceRange Brackets;
3084
3085
  DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
3086
                          Expr *e, ArraySizeModifier sm, unsigned tq,
3087
                          SourceRange brackets);
3088
3089
public:
3090
  friend class StmtIteratorBase;
3091
3092
33.5k
  Expr *getSizeExpr() const {
3093
    // We use C-style casts instead of cast<> here because we do not wish
3094
    // to have a dependency of Type.h on Stmt.h/Expr.h.
3095
33.5k
    return (Expr*) SizeExpr;
3096
33.5k
  }
3097
3098
1.02k
  SourceRange getBracketsRange() const { return Brackets; }
3099
1.23k
  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3100
1.23k
  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3101
3102
38.1k
  bool isSugared() const { return false; }
3103
0
  QualType desugar() const { return QualType(this, 0); }
3104
3105
234k
  static bool classof(const Type *T) {
3106
234k
    return T->getTypeClass() == DependentSizedArray;
3107
234k
  }
3108
3109
8.38k
  void Profile(llvm::FoldingSetNodeID &ID) {
3110
8.38k
    Profile(ID, Context, getElementType(),
3111
8.38k
            getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
3112
8.38k
  }
3113
3114
  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3115
                      QualType ET, ArraySizeModifier SizeMod,
3116
                      unsigned TypeQuals, Expr *E);
3117
};
3118
3119
/// Represents an extended address space qualifier where the input address space
3120
/// value is dependent. Non-dependent address spaces are not represented with a
3121
/// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
3122
///
3123
/// For example:
3124
/// \code
3125
/// template<typename T, int AddrSpace>
3126
/// class AddressSpace {
3127
///   typedef T __attribute__((address_space(AddrSpace))) type;
3128
/// }
3129
/// \endcode
3130
class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
3131
  friend class ASTContext;
3132
3133
  const ASTContext &Context;
3134
  Expr *AddrSpaceExpr;
3135
  QualType PointeeType;
3136
  SourceLocation loc;
3137
3138
  DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType,
3139
                            QualType can, Expr *AddrSpaceExpr,
3140
                            SourceLocation loc);
3141
3142
public:
3143
147
  Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
3144
491
  QualType getPointeeType() const { return PointeeType; }
3145
37
  SourceLocation getAttributeLoc() const { return loc; }
3146
3147
10
  bool isSugared() const { return false; }
3148
0
  QualType desugar() const { return QualType(this, 0); }
3149
3150
37.0M
  static bool classof(const Type *T) {
3151
37.0M
    return T->getTypeClass() == DependentAddressSpace;
3152
37.0M
  }
3153
3154
17
  void Profile(llvm::FoldingSetNodeID &ID) {
3155
17
    Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
3156
17
  }
3157
3158
  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3159
                      QualType PointeeType, Expr *AddrSpaceExpr);
3160
};
3161
3162
/// Represents an extended vector type where either the type or size is
3163
/// dependent.
3164
///
3165
/// For example:
3166
/// \code
3167
/// template<typename T, int Size>
3168
/// class vector {
3169
///   typedef T __attribute__((ext_vector_type(Size))) type;
3170
/// }
3171
/// \endcode
3172
class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
3173
  friend class ASTContext;
3174
3175
  const ASTContext &Context;
3176
  Expr *SizeExpr;
3177
3178
  /// The element type of the array.
3179
  QualType ElementType;
3180
3181
  SourceLocation loc;
3182
3183
  DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
3184
                              QualType can, Expr *SizeExpr, SourceLocation loc);
3185
3186
public:
3187
61
  Expr *getSizeExpr() const { return SizeExpr; }
3188
113
  QualType getElementType() const { return ElementType; }
3189
26
  SourceLocation getAttributeLoc() const { return loc; }
3190
3191
0
  bool isSugared() const { return false; }
3192
0
  QualType desugar() const { return QualType(this, 0); }
3193
3194
436
  static bool classof(const Type *T) {
3195
436
    return T->getTypeClass() == DependentSizedExtVector;
3196
436
  }
3197
3198
12
  void Profile(llvm::FoldingSetNodeID &ID) {
3199
12
    Profile(ID, Context, getElementType(), getSizeExpr());
3200
12
  }
3201
3202
  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3203
                      QualType ElementType, Expr *SizeExpr);
3204
};
3205
3206
3207
/// Represents a GCC generic vector type. This type is created using
3208
/// __attribute__((vector_size(n)), where "n" specifies the vector size in
3209
/// bytes; or from an Altivec __vector or vector declaration.
3210
/// Since the constructor takes the number of vector elements, the
3211
/// client is responsible for converting the size into the number of elements.
3212
class VectorType : public Type, public llvm::FoldingSetNode {
3213
public:
3214
  enum VectorKind {
3215
    /// not a target-specific vector type
3216
    GenericVector,
3217
3218
    /// is AltiVec vector
3219
    AltiVecVector,
3220
3221
    /// is AltiVec 'vector Pixel'
3222
    AltiVecPixel,
3223
3224
    /// is AltiVec 'vector bool ...'
3225
    AltiVecBool,
3226
3227
    /// is ARM Neon vector
3228
    NeonVector,
3229
3230
    /// is ARM Neon polynomial vector
3231
    NeonPolyVector,
3232
3233
    /// is AArch64 SVE fixed-length data vector
3234
    SveFixedLengthDataVector,
3235
3236
    /// is AArch64 SVE fixed-length predicate vector
3237
    SveFixedLengthPredicateVector
3238
  };
3239
3240
protected:
3241
  friend class ASTContext; // ASTContext creates these.
3242
3243
  /// The element type of the vector.
3244
  QualType ElementType;
3245
3246
  VectorType(QualType vecType, unsigned nElements, QualType canonType,
3247
             VectorKind vecKind);
3248
3249
  VectorType(TypeClass tc, QualType vecType, unsigned nElements,
3250
             QualType canonType, VectorKind vecKind);
3251
3252
public:
3253
22.1M
  QualType getElementType() const { return ElementType; }
3254
25.0M
  unsigned getNumElements() const { return VectorTypeBits.NumElements; }
3255
3256
26.0M
  bool isSugared() const { return false; }
3257
0
  QualType desugar() const { return QualType(this, 0); }
3258
3259
17.3M
  VectorKind getVectorKind() const {
3260
17.3M
    return VectorKind(VectorTypeBits.VecKind);
3261
17.3M
  }
3262
3263
6.63M
  void Profile(llvm::FoldingSetNodeID &ID) {
3264
6.63M
    Profile(ID, getElementType(), getNumElements(),
3265
6.63M
            getTypeClass(), getVectorKind());
3266
6.63M
  }
3267
3268
  static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3269
                      unsigned NumElements, TypeClass TypeClass,
3270
11.6M
                      VectorKind VecKind) {
3271
11.6M
    ID.AddPointer(ElementType.getAsOpaquePtr());
3272
11.6M
    ID.AddInteger(NumElements);
3273
11.6M
    ID.AddInteger(TypeClass);
3274
11.6M
    ID.AddInteger(VecKind);
3275
11.6M
  }
3276
3277
251M
  static bool classof(const Type *T) {
3278
251M
    return T->getTypeClass() == Vector || 
T->getTypeClass() == ExtVector130M
;
3279
251M
  }
3280
};
3281
3282
/// Represents a vector type where either the type or size is dependent.
3283
////
3284
/// For example:
3285
/// \code
3286
/// template<typename T, int Size>
3287
/// class vector {
3288
///   typedef T __attribute__((vector_size(Size))) type;
3289
/// }
3290
/// \endcode
3291
class DependentVectorType : public Type, public llvm::FoldingSetNode {
3292
  friend class ASTContext;
3293
3294
  const ASTContext &Context;
3295
  QualType ElementType;
3296
  Expr *SizeExpr;
3297
  SourceLocation Loc;
3298
3299
  DependentVectorType(const ASTContext &Context, QualType ElementType,
3300
                           QualType CanonType, Expr *SizeExpr,
3301
                           SourceLocation Loc, VectorType::VectorKind vecKind);
3302
3303
public:
3304
75
  Expr *getSizeExpr() const { return SizeExpr; }
3305
145
  QualType getElementType() const { return ElementType; }
3306
70
  SourceLocation getAttributeLoc() const { return Loc; }
3307
75
  VectorType::VectorKind getVectorKind() const {
3308
75
    return VectorType::VectorKind(VectorTypeBits.VecKind);
3309
75
  }
3310
3311
0
  bool isSugared() const { return false; }
3312
0
  QualType desugar() const { return QualType(this, 0); }
3313
3314
740
  static bool classof(const Type *T) {
3315
740
    return T->getTypeClass() == DependentVector;
3316
740
  }
3317
3318
5
  void Profile(llvm::FoldingSetNodeID &ID) {
3319
5
    Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind());
3320
5
  }
3321
3322
  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3323
                      QualType ElementType, const Expr *SizeExpr,
3324
                      VectorType::VectorKind VecKind);
3325
};
3326
3327
/// ExtVectorType - Extended vector type. This type is created using
3328
/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
3329
/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
3330
/// class enables syntactic extensions, like Vector Components for accessing
3331
/// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
3332
/// Shading Language).
3333
class ExtVectorType : public VectorType {
3334
  friend class ASTContext; // ASTContext creates these.
3335
3336
  ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
3337
3.87k
      : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
3338
3339
public:
3340
1.57k
  static int getPointAccessorIdx(char c) {
3341
1.57k
    switch (c) {
3342
7
    default: return -1;
3343
722
    case 'x': case 'r': return 0;
3344
577
    case 'y': case 'g': return 1;
3345
159
    case 'z': case 'b': return 2;
3346
114
    case 'w': case 'a': return 3;
3347
1.57k
    }
3348
1.57k
  }
3349
3350
107
  static int getNumericAccessorIdx(char c) {
3351
107
    switch (c) {
3352
25
      default: return -1;
3353
16
      case '0': return 0;
3354
11
      case '1': return 1;
3355
10
      case '2': return 2;
3356
10
      case '3': return 3;
3357
6
      case '4': return 4;
3358
0
      case '5': return 5;
3359
4
      case '6': return 6;
3360
0
      case '7': return 7;
3361
0
      case '8': return 8;
3362
0
      case '9': return 9;
3363
3
      case 'A':
3364
3
      case 'a': return 10;
3365
8
      case 'B':
3366
8
      case 'b': return 11;
3367
3
      case 'C':
3368
3
      case 'c': return 12;
3369
3
      case 'D':
3370
3
      case 'd': return 13;
3371
0
      case 'E':
3372
0
      case 'e': return 14;
3373
8
      case 'F':
3374
8
      case 'f': return 15;
3375
107
    }
3376
107
  }
3377
3378
986
  static int getAccessorIdx(char c, bool isNumericAccessor) {
3379
986
    if (isNumericAccessor)
3380
45
      return getNumericAccessorIdx(c);
3381
941
    else
3382
941
      return getPointAccessorIdx(c);
3383
986
  }
3384
3385
642
  bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
3386
642
    if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
3387
642
      return unsigned(idx-1) < getNumElements();
3388
0
    return false;
3389
0
  }
3390
3391
583k
  bool isSugared() const { return false; }
3392
0
  QualType desugar() const { return QualType(this, 0); }
3393
3394
9.51M
  static bool classof(const Type *T) {
3395
9.51M
    return T->getTypeClass() == ExtVector;
3396
9.51M
  }
3397
};
3398
3399
/// Represents a matrix type, as defined in the Matrix Types clang extensions.
3400
/// __attribute__((matrix_type(rows, columns))), where "rows" specifies
3401
/// number of rows and "columns" specifies the number of columns.
3402
class MatrixType : public Type, public llvm::FoldingSetNode {
3403
protected:
3404
  friend class ASTContext;
3405
3406
  /// The element type of the matrix.
3407
  QualType ElementType;
3408
3409
  MatrixType(QualType ElementTy, QualType CanonElementTy);
3410
3411
  MatrixType(TypeClass TypeClass, QualType ElementTy, QualType CanonElementTy,
3412
             const Expr *RowExpr = nullptr, const Expr *ColumnExpr = nullptr);
3413
3414
public:
3415
  /// Returns type of the elements being stored in the matrix
3416
1.85k
  QualType getElementType() const { return ElementType; }
3417
3418
  /// Valid elements types are the following:
3419
  /// * an integer type (as in C2x 6.2.5p19), but excluding enumerated types
3420
  ///   and _Bool
3421
  /// * the standard floating types float or double
3422
  /// * a half-precision floating point type, if one is supported on the target
3423
702
  static bool isValidElementType(QualType T) {
3424
702
    return T->isDependentType() ||
3425
695
           (T->isRealType() && 
!T->isBooleanType()690
&&
!T->isEnumeralType()688
);
3426
702
  }
3427
3428
2.07k
  bool isSugared() const { return false; }
3429
0
  QualType desugar() const { return QualType(this, 0); }
3430
3431
23.6M
  static bool classof(const Type *T) {
3432
23.6M
    return T->getTypeClass() == ConstantMatrix ||
3433
23.6M
           T->getTypeClass() == DependentSizedMatrix;
3434
23.6M
  }
3435
};
3436
3437
/// Represents a concrete matrix type with constant number of rows and columns
3438
class ConstantMatrixType final : public MatrixType {
3439
protected:
3440
  friend class ASTContext;
3441
3442
  /// The element type of the matrix.
3443
  // FIXME: Appears to be unused? There is also MatrixType::ElementType...
3444
  QualType ElementType;
3445
3446
  /// Number of rows and columns.
3447
  unsigned NumRows;
3448
  unsigned NumColumns;
3449
3450
  static constexpr unsigned MaxElementsPerDimension = (1 << 20) - 1;
3451
3452
  ConstantMatrixType(QualType MatrixElementType, unsigned NRows,
3453
                     unsigned NColumns, QualType CanonElementType);
3454
3455
  ConstantMatrixType(TypeClass typeClass, QualType MatrixType, unsigned NRows,
3456
                     unsigned NColumns, QualType CanonElementType);
3457
3458
public:
3459
  /// Returns the number of rows in the matrix.
3460
1.44k
  unsigned getNumRows() const { return NumRows; }
3461
3462
  /// Returns the number of columns in the matrix.
3463
1.39k
  unsigned getNumColumns() const { return NumColumns; }
3464
3465
  /// Returns the number of elements required to embed the matrix into a vector.
3466
0
  unsigned getNumElementsFlattened() const {
3467
0
    return getNumRows() * getNumColumns();
3468
0
  }
3469
3470
  /// Returns true if \p NumElements is a valid matrix dimension.
3471
1.34k
  static constexpr bool isDimensionValid(size_t NumElements) {
3472
1.34k
    return NumElements > 0 && NumElements <= MaxElementsPerDimension;
3473
1.34k
  }
3474
3475
  /// Returns the maximum number of elements per dimension.
3476
6
  static constexpr unsigned getMaxElementsPerDimension() {
3477
6
    return MaxElementsPerDimension;
3478
6
  }
3479
3480
222
  void Profile(llvm::FoldingSetNodeID &ID) {
3481
222
    Profile(ID, getElementType(), getNumRows(), getNumColumns(),
3482
222
            getTypeClass());
3483
222
  }
3484
3485
  static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3486
                      unsigned NumRows, unsigned NumColumns,
3487
621
                      TypeClass TypeClass) {
3488
621
    ID.AddPointer(ElementType.getAsOpaquePtr());
3489
621
    ID.AddInteger(NumRows);
3490
621
    ID.AddInteger(NumColumns);
3491
621
    ID.AddInteger(TypeClass);
3492
621
  }
3493
3494
8.86M
  static bool classof(const Type *T) {
3495
8.86M
    return T->getTypeClass() == ConstantMatrix;
3496
8.86M
  }
3497
};
3498
3499
/// Represents a matrix type where the type and the number of rows and columns
3500
/// is dependent on a template.
3501
class DependentSizedMatrixType final : public MatrixType {
3502
  friend class ASTContext;
3503
3504
  const ASTContext &Context;
3505
  Expr *RowExpr;
3506
  Expr *ColumnExpr;
3507
3508
  SourceLocation loc;
3509
3510
  DependentSizedMatrixType(const ASTContext &Context, QualType ElementType,
3511
                           QualType CanonicalType, Expr *RowExpr,
3512
                           Expr *ColumnExpr, SourceLocation loc);
3513
3514
public:
3515
592
  QualType getElementType() const { return ElementType; }
3516
373
  Expr *getRowExpr() const { return RowExpr; }
3517
350
  Expr *getColumnExpr() const { return ColumnExpr; }
3518
172
  SourceLocation getAttributeLoc() const { return loc; }
3519
3520
65
  bool isSugared() const { return false; }
3521
0
  QualType desugar() const { return QualType(this, 0); }
3522
3523
2.65k
  static bool classof(const Type *T) {
3524
2.65k
    return T->getTypeClass() == DependentSizedMatrix;
3525
2.65k
  }
3526
3527
17
  void Profile(llvm::FoldingSetNodeID &ID) {
3528
17
    Profile(ID, Context, getElementType(), getRowExpr(), getColumnExpr());
3529
17
  }
3530
3531
  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3532
                      QualType ElementType, Expr *RowExpr, Expr *ColumnExpr);
3533
};
3534
3535
/// FunctionType - C99 6.7.5.3 - Function Declarators.  This is the common base
3536
/// class of FunctionNoProtoType and FunctionProtoType.
3537
class FunctionType : public Type {
3538
  // The type returned by the function.
3539
  QualType ResultType;
3540
3541
public:
3542
  /// Interesting information about a specific parameter that can't simply
3543
  /// be reflected in parameter's type. This is only used by FunctionProtoType
3544
  /// but is in FunctionType to make this class available during the
3545
  /// specification of the bases of FunctionProtoType.
3546
  ///
3547
  /// It makes sense to model language features this way when there's some
3548
  /// sort of parameter-specific override (such as an attribute) that
3549
  /// affects how the function is called.  For example, the ARC ns_consumed
3550
  /// attribute changes whether a parameter is passed at +0 (the default)
3551
  /// or +1 (ns_consumed).  This must be reflected in the function type,
3552
  /// but isn't really a change to the parameter type.
3553
  ///
3554
  /// One serious disadvantage of modelling language features this way is
3555
  /// that they generally do not work with language features that attempt
3556
  /// to destructure types.  For example, template argument deduction will
3557
  /// not be able to match a parameter declared as
3558
  ///   T (*)(U)
3559
  /// against an argument of type
3560
  ///   void (*)(__attribute__((ns_consumed)) id)
3561
  /// because the substitution of T=void, U=id into the former will
3562
  /// not produce the latter.
3563
  class ExtParameterInfo {
3564
    enum {
3565
      ABIMask = 0x0F,
3566
      IsConsumed = 0x10,
3567
      HasPassObjSize = 0x20,
3568
      IsNoEscape = 0x40,
3569
    };
3570
    unsigned char Data = 0;
3571
3572
  public:
3573
22.9M
    ExtParameterInfo() = default;
3574
3575
    /// Return the ABI treatment of this parameter.
3576
2.11M
    ParameterABI getABI() const { return ParameterABI(Data & ABIMask); }
3577
160
    ExtParameterInfo withABI(ParameterABI kind) const {
3578
160
      ExtParameterInfo copy = *this;
3579
160
      copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3580
160
      return copy;
3581
160
    }
3582
3583
    /// Is this parameter considered "consumed" by Objective-C ARC?
3584
    /// Consumed parameters must have retainable object type.
3585
30.3k
    bool isConsumed() const { return (Data & IsConsumed); }
3586
78
    ExtParameterInfo withIsConsumed(bool consumed) const {
3587
78
      ExtParameterInfo copy = *this;
3588
78
      if (consumed)
3589
78
        copy.Data |= IsConsumed;
3590
0
      else
3591
0
        copy.Data &= ~IsConsumed;
3592
78
      return copy;
3593
78
    }
3594
3595
2.33k
    bool hasPassObjectSize() const { return Data & HasPassObjSize; }
3596
126
    ExtParameterInfo withHasPassObjectSize() const {
3597
126
      ExtParameterInfo Copy = *this;
3598
126
      Copy.Data |= HasPassObjSize;
3599
126
      return Copy;
3600
126
    }
3601
3602
6.58M
    bool isNoEscape() const { return Data & IsNoEscape; }
3603
23.9k
    ExtParameterInfo withIsNoEscape(bool NoEscape) const {
3604
23.9k
      ExtParameterInfo Copy = *this;
3605
23.9k
      if (NoEscape)
3606
9.62k
        Copy.Data |= IsNoEscape;
3607
14.3k
      else
3608
14.3k
        Copy.Data &= ~IsNoEscape;
3609
23.9k
      return Copy;
3610
23.9k
    }
3611
3612
519k
    unsigned char getOpaqueValue() const { return Data; }
3613
4
    static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3614
4
      ExtParameterInfo result;
3615
4
      result.Data = data;
3616
4
      return result;
3617
4
    }
3618
3619
80
    friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3620
80
      return lhs.Data == rhs.Data;
3621
80
    }
3622
3623
192
    friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3624
192
      return lhs.Data != rhs.Data;
3625
192
    }
3626
  };
3627
3628
  /// A class which abstracts out some details necessary for
3629
  /// making a call.
3630
  ///
3631
  /// It is not actually used directly for storing this information in
3632
  /// a FunctionType, although FunctionType does currently use the
3633
  /// same bit-pattern.
3634
  ///
3635
  // If you add a field (say Foo), other than the obvious places (both,
3636
  // constructors, compile failures), what you need to update is
3637
  // * Operator==
3638
  // * getFoo
3639
  // * withFoo
3640
  // * functionType. Add Foo, getFoo.
3641
  // * ASTContext::getFooType
3642
  // * ASTContext::mergeFunctionTypes
3643
  // * FunctionNoProtoType::Profile
3644
  // * FunctionProtoType::Profile
3645
  // * TypePrinter::PrintFunctionProto
3646
  // * AST read and write
3647
  // * Codegen
3648
  class ExtInfo {
3649
    friend class FunctionType;
3650
3651
    // Feel free to rearrange or add bits, but if you go over 16, you'll need to
3652
    // adjust the Bits field below, and if you add bits, you'll need to adjust
3653
    // Type::FunctionTypeBitfields::ExtInfo as well.
3654
3655
    // |  CC  |noreturn|produces|nocallersavedregs|regparm|nocfcheck|cmsenscall|
3656
    // |0 .. 4|   5    |    6   |       7         |8 .. 10|    11   |    12    |
3657
    //
3658
    // regparm is either 0 (no regparm attribute) or the regparm value+1.
3659
    enum { CallConvMask = 0x1F };
3660
    enum { NoReturnMask = 0x20 };
3661
    enum { ProducesResultMask = 0x40 };
3662
    enum { NoCallerSavedRegsMask = 0x80 };
3663
    enum {
3664
      RegParmMask =  0x700,
3665
      RegParmOffset = 8
3666
    };
3667
    enum { NoCfCheckMask = 0x800 };
3668
    enum { CmseNSCallMask = 0x1000 };
3669
    uint16_t Bits = CC_C;
3670
3671
108M
    ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
3672
3673
  public:
3674
    // Constructor with no defaults. Use this when you know that you
3675
    // have all the elements (when reading an AST file for example).
3676
    ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
3677
            bool producesResult, bool noCallerSavedRegs, bool NoCfCheck,
3678
776k
            bool cmseNSCall) {
3679
776k
      assert((!hasRegParm || regParm < 7) && "Invalid regparm value");
3680
775k
      Bits = ((unsigned)cc) | (noReturn ? 
NoReturnMask310
: 0) |
3681
776k
             (producesResult ? 
ProducesResultMask0
: 0) |
3682
776k
             (noCallerSavedRegs ? 
NoCallerSavedRegsMask0
: 0) |
3683
776k
             (hasRegParm ? 
((regParm + 1) << RegParmOffset)0
: 0) |
3684
776k
             (NoCfCheck ? 
NoCfCheckMask0
: 0) |
3685
776k
             (cmseNSCall ? 
CmseNSCallMask1
: 0);
3686
776k
    }
3687
3688
    // Constructor with all defaults. Use when for example creating a
3689
    // function known to use defaults.
3690
92.2M
    ExtInfo() = default;
3691
3692
    // Constructor with just the calling convention, which is an important part
3693
    // of the canonical type.
3694
17.0M
    ExtInfo(CallingConv CC) : Bits(CC) {}
3695
3696
8.78M
    bool getNoReturn() const { return Bits & NoReturnMask; }
3697
4.09M
    bool getProducesResult() const { return Bits & ProducesResultMask; }
3698
18.7M
    bool getCmseNSCall() const { return Bits & CmseNSCallMask; }
3699
3.02M
    bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
3700
2.53M
    bool getNoCfCheck() const { return Bits & NoCfCheckMask; }
3701
2.98M
    bool getHasRegParm() const { return ((Bits & RegParmMask) >> RegParmOffset) != 0; }
3702
3703
3.02M
    unsigned getRegParm() const {
3704
3.02M
      unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset;
3705
3.02M
      if (RegParm > 0)
3706
211
        --RegParm;
3707
3.02M
      return RegParm;
3708
3.02M
    }
3709
3710
8.84M
    CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
3711
3712
1.14M
    bool operator==(ExtInfo Other) const {
3713
1.14M
      return Bits == Other.Bits;
3714
1.14M
    }
3715
17
    bool operator!=(ExtInfo Other) const {
3716
17
      return Bits != Other.Bits;
3717
17
    }
3718
3719
    // Note that we don't have setters. That is by design, use
3720
    // the following with methods instead of mutating these objects.
3721
3722
20.1k
    ExtInfo withNoReturn(bool noReturn) const {
3723
20.1k
      if (noReturn)
3724
8.60k
        return ExtInfo(Bits | NoReturnMask);
3725
11.5k
      else
3726
11.5k
        return ExtInfo(Bits & ~NoReturnMask);
3727
20.1k
    }
3728
3729
394
    ExtInfo withProducesResult(bool producesResult) const {
3730
394
      if (producesResult)
3731
394
        return ExtInfo(Bits | ProducesResultMask);
3732
0
      else
3733
0
        return ExtInfo(Bits & ~ProducesResultMask);
3734
394
    }
3735
3736
77
    ExtInfo withCmseNSCall(bool cmseNSCall) const {
3737
77
      if (cmseNSCall)
3738
77
        return ExtInfo(Bits | CmseNSCallMask);
3739
0
      else
3740
0
        return ExtInfo(Bits & ~CmseNSCallMask);
3741
77
    }
3742
3743
19
    ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const {
3744
19
      if (noCallerSavedRegs)
3745
19
        return ExtInfo(Bits | NoCallerSavedRegsMask);
3746
0
      else
3747
0
        return ExtInfo(Bits & ~NoCallerSavedRegsMask);
3748
19
    }
3749
3750
6
    ExtInfo withNoCfCheck(bool noCfCheck) const {
3751
6
      if (noCfCheck)
3752
6
        return ExtInfo(Bits | NoCfCheckMask);
3753
0
      else
3754
0
        return ExtInfo(Bits & ~NoCfCheckMask);
3755
6
    }
3756
3757
84
    ExtInfo withRegParm(unsigned RegParm) const {
3758
84
      assert(RegParm < 7 && "Invalid regparm value");
3759
84
      return ExtInfo((Bits & ~RegParmMask) |
3760
84
                     ((RegParm + 1) << RegParmOffset));
3761
84
    }
3762
3763
430k
    ExtInfo withCallingConv(CallingConv cc) const {
3764
430k
      return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
3765
430k
    }
3766
3767
97.6M
    void Profile(llvm::FoldingSetNodeID &ID) const {
3768
97.6M
      ID.AddInteger(Bits);
3769
97.6M
    }
3770
  };
3771
3772
  /// A simple holder for a QualType representing a type in an
3773
  /// exception specification. Unfortunately needed by FunctionProtoType
3774
  /// because TrailingObjects cannot handle repeated types.
3775
  struct ExceptionType { QualType Type; };
3776
3777
  /// A simple holder for various uncommon bits which do not fit in
3778
  /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the
3779
  /// alignment of subsequent objects in TrailingObjects. You must update
3780
  /// hasExtraBitfields in FunctionProtoType after adding extra data here.
3781
  struct alignas(void *) FunctionTypeExtraBitfields {
3782
    /// The number of types in the exception specification.
3783
    /// A whole unsigned is not needed here and according to
3784
    /// [implimits] 8 bits would be enough here.
3785
    unsigned NumExceptionType;
3786
  };
3787
3788
protected:
3789
  FunctionType(TypeClass tc, QualType res, QualType Canonical,
3790
               TypeDependence Dependence, ExtInfo Info)
3791
13.5M
      : Type(tc, Canonical, Dependence), ResultType(res) {
3792
13.5M
    FunctionTypeBits.ExtInfo = Info.Bits;
3793
13.5M
  }
3794
3795
85.6M
  Qualifiers getFastTypeQuals() const {
3796
85.6M
    return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals);
3797
85.6M
  }
3798
3799
public:
3800
256M
  QualType getReturnType() const { return ResultType; }
3801
3802
152
  bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
3803
10
  unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
3804
3805
  /// Determine whether this function type includes the GNU noreturn
3806
  /// attribute. The C++11 [[noreturn]] attribute does not affect the function
3807
  /// type.
3808
5.63M
  bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
3809
3810
16.8M
  bool getCmseNSCallAttr() const { return getExtInfo().getCmseNSCall(); }
3811
5.09M
  CallingConv getCallConv() const { return getExtInfo().getCC(); }
3812
108M
  ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
3813
3814
  static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0,
3815
                "Const, volatile and restrict are assumed to be a subset of "
3816
                "the fast qualifiers.");
3817
3818
843k
  bool isConst() const { return getFastTypeQuals().hasConst(); }
3819
781k
  bool isVolatile() const { return getFastTypeQuals().hasVolatile(); }
3820
31.4k
  bool isRestrict() const { return getFastTypeQuals().hasRestrict(); }
3821
3822
  /// Determine the type of an expression that calls a function of
3823
  /// this type.
3824
4.49M
  QualType getCallResultType(const ASTContext &Context) const {
3825
4.49M
    return getReturnType().getNonLValueExprType(Context);
3826
4.49M
  }
3827
3828
  static StringRef getNameForCallConv(CallingConv CC);
3829
3830
919M
  static bool classof(const Type *T) {
3831
919M
    return T->getTypeClass() == FunctionNoProto ||
3832
918M
           T->getTypeClass() == FunctionProto;
3833
919M
  }
3834
};
3835
3836
/// Represents a K&R-style 'int foo()' function, which has
3837
/// no information available about its arguments.
3838
class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
3839
  friend class ASTContext; // ASTContext creates these.
3840
3841
  FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
3842
      : FunctionType(FunctionNoProto, Result, Canonical,
3843
                     Result->getDependence() &
3844
                         ~(TypeDependence::DependentInstantiation |
3845
                           TypeDependence::UnexpandedPack),
3846
14.0k
                     Info) {}
3847
3848
public:
3849
  // No additional state past what FunctionType provides.
3850
3851
10.9k
  bool isSugared() const { return false; }
3852
0
  QualType desugar() const { return QualType(this, 0); }
3853
3854
147k
  void Profile(llvm::FoldingSetNodeID &ID) {
3855
147k
    Profile(ID, getReturnType(), getExtInfo());
3856
147k
  }
3857
3858
  static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3859
308k
                      ExtInfo Info) {
3860
308k
    Info.Profile(ID);
3861
308k
    ID.AddPointer(ResultType.getAsOpaquePtr());
3862
308k
  }
3863
3864
191M
  static bool classof(const Type *T) {
3865
191M
    return T->getTypeClass() == FunctionNoProto;
3866
191M
  }
3867
};
3868
3869
/// Represents a prototype with parameter type info, e.g.
3870
/// 'int foo(int)' or 'int foo(void)'.  'void' is represented as having no
3871
/// parameters, not as having a single void parameter. Such a type can have
3872
/// an exception specification, but this specification is not part of the
3873
/// canonical type. FunctionProtoType has several trailing objects, some of
3874
/// which optional. For more information about the trailing objects see
3875
/// the first comment inside FunctionProtoType.
3876
class FunctionProtoType final
3877
    : public FunctionType,
3878
      public llvm::FoldingSetNode,
3879
      private llvm::TrailingObjects<
3880
          FunctionProtoType, QualType, SourceLocation,
3881
          FunctionType::FunctionTypeExtraBitfields, FunctionType::ExceptionType,
3882
          Expr *, FunctionDecl *, FunctionType::ExtParameterInfo, Qualifiers> {
3883
  friend class ASTContext; // ASTContext creates these.
3884
  friend TrailingObjects;
3885
3886
  // FunctionProtoType is followed by several trailing objects, some of
3887
  // which optional. They are in order:
3888
  //
3889
  // * An array of getNumParams() QualType holding the parameter types.
3890
  //   Always present. Note that for the vast majority of FunctionProtoType,
3891
  //   these will be the only trailing objects.
3892
  //
3893
  // * Optionally if the function is variadic, the SourceLocation of the
3894
  //   ellipsis.
3895
  //
3896
  // * Optionally if some extra data is stored in FunctionTypeExtraBitfields
3897
  //   (see FunctionTypeExtraBitfields and FunctionTypeBitfields):
3898
  //   a single FunctionTypeExtraBitfields. Present if and only if
3899
  //   hasExtraBitfields() is true.
3900
  //
3901
  // * Optionally exactly one of:
3902
  //   * an array of getNumExceptions() ExceptionType,
3903
  //   * a single Expr *,
3904
  //   * a pair of FunctionDecl *,
3905
  //   * a single FunctionDecl *
3906
  //   used to store information about the various types of exception
3907
  //   specification. See getExceptionSpecSize for the details.
3908
  //
3909
  // * Optionally an array of getNumParams() ExtParameterInfo holding
3910
  //   an ExtParameterInfo for each of the parameters. Present if and
3911
  //   only if hasExtParameterInfos() is true.
3912
  //
3913
  // * Optionally a Qualifiers object to represent extra qualifiers that can't
3914
  //   be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only
3915
  //   if hasExtQualifiers() is true.
3916
  //
3917
  // The optional FunctionTypeExtraBitfields has to be before the data
3918
  // related to the exception specification since it contains the number
3919
  // of exception types.
3920
  //
3921
  // We put the ExtParameterInfos last.  If all were equal, it would make
3922
  // more sense to put these before the exception specification, because
3923
  // it's much easier to skip past them compared to the elaborate switch
3924
  // required to skip the exception specification.  However, all is not
3925
  // equal; ExtParameterInfos are used to model very uncommon features,
3926
  // and it's better not to burden the more common paths.
3927
3928
public:
3929
  /// Holds information about the various types of exception specification.
3930
  /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is
3931
  /// used to group together the various bits of information about the
3932
  /// exception specification.
3933
  struct ExceptionSpecInfo {
3934
    /// The kind of exception specification this is.
3935
    ExceptionSpecificationType Type = EST_None;
3936
3937
    /// Explicitly-specified list of exception types.
3938
    ArrayRef<QualType> Exceptions;
3939
3940
    /// Noexcept expression, if this is a computed noexcept specification.
3941
    Expr *NoexceptExpr = nullptr;
3942
3943
    /// The function whose exception specification this is, for
3944
    /// EST_Unevaluated and EST_Uninstantiated.
3945
    FunctionDecl *SourceDecl = nullptr;
3946
3947
    /// The function template whose exception specification this is instantiated
3948
    /// from, for EST_Uninstantiated.
3949
    FunctionDecl *SourceTemplate = nullptr;
3950
3951
168M
    ExceptionSpecInfo() = default;
3952
3953
107k
    ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {}
3954
  };
3955
3956
  /// Extra information about a function prototype. ExtProtoInfo is not
3957
  /// stored as such in FunctionProtoType but is used to group together
3958
  /// the various bits of extra information about a function prototype.
3959
  struct ExtProtoInfo {
3960
    FunctionType::ExtInfo ExtInfo;
3961
    bool Variadic : 1;
3962
    bool HasTrailingReturn : 1;
3963
    Qualifiers TypeQuals;
3964
    RefQualifierKind RefQualifier = RQ_None;
3965
    ExceptionSpecInfo ExceptionSpec;
3966
    const ExtParameterInfo *ExtParameterInfos = nullptr;
3967
    SourceLocation EllipsisLoc;
3968
3969
92.0M
    ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {}
3970
3971
    ExtProtoInfo(CallingConv CC)
3972
190k
        : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {}
3973
3974
647k
    ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) {
3975
647k
      ExtProtoInfo Result(*this);
3976
647k
      Result.ExceptionSpec = ESI;
3977
647k
      return Result;
3978
647k
    }
3979
  };
3980
3981
private:
3982
7.35M
  unsigned numTrailingObjects(OverloadToken<QualType>) const {
3983
7.35M
    return getNumParams();
3984
7.35M
  }
3985
3986
6.40M
  unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
3987
6.40M
    return isVariadic();
3988
6.40M
  }
3989
3990
6.39M
  unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const {
3991
6.39M
    return hasExtraBitfields();
3992
6.39M
  }
3993
3994
4.37M
  unsigned numTrailingObjects(OverloadToken<ExceptionType>) const {
3995
4.37M
    return getExceptionSpecSize().NumExceptionType;
3996
4.37M
  }
3997
3998
2.88M
  unsigned numTrailingObjects(OverloadToken<Expr *>) const {
3999
2.88M
    return getExceptionSpecSize().NumExprPtr;
4000
2.88M
  }
4001
4002
130k
  unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const {
4003
130k
    return getExceptionSpecSize().NumFunctionDeclPtr;
4004
130k
  }
4005
4006
2.53k
  unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const {
4007
2.53k
    return hasExtParameterInfos() ? 
getNumParams()0
: 0;
4008
2.53k
  }
4009
4010
  /// Determine whether there are any argument types that
4011
  /// contain an unexpanded parameter pack.
4012
  static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
4013
0
                                                 unsigned numArgs) {
4014
0
    for (unsigned Idx = 0; Idx < numArgs; ++Idx)
4015
0
      if (ArgArray[Idx]->containsUnexpandedParameterPack())
4016
0
        return true;
4017
0
4018
0
    return false;
4019
0
  }
4020
4021
  FunctionProtoType(QualType result, ArrayRef<QualType> params,
4022
                    QualType canonical, const ExtProtoInfo &epi);
4023
4024
  /// This struct is returned by getExceptionSpecSize and is used to
4025
  /// translate an ExceptionSpecificationType to the number and kind
4026
  /// of trailing objects related to the exception specification.
4027
  struct ExceptionSpecSizeHolder {
4028
    unsigned NumExceptionType;
4029
    unsigned NumExprPtr;
4030
    unsigned NumFunctionDeclPtr;
4031
  };
4032
4033
  /// Return the number and kind of trailing objects
4034
  /// related to the exception specification.
4035
  static ExceptionSpecSizeHolder
4036
20.9M
  getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) {
4037
20.9M
    switch (EST) {
4038
13.1M
    case EST_None:
4039
13.1M
    case EST_DynamicNone:
4040
13.1M
    case EST_MSAny:
4041
13.1M
    case EST_BasicNoexcept:
4042
13.1M
    case EST_Unparsed:
4043
13.1M
    case EST_NoThrow:
4044
13.1M
      return {0, 0, 0};
4045
4046
676
    case EST_Dynamic:
4047
676
      return {NumExceptions, 0, 0};
4048
4049
1.69M
    case EST_DependentNoexcept:
4050
1.69M
    case EST_NoexceptFalse:
4051
1.69M
    case EST_NoexceptTrue:
4052
1.69M
      return {0, 1, 0};
4053
4054
1.11M
    case EST_Uninstantiated:
4055
1.11M
      return {0, 0, 2};
4056
4057
4.96M
    case EST_Unevaluated:
4058
4.96M
      return {0, 0, 1};
4059
0
    }
4060
0
    llvm_unreachable("bad exception specification kind");
4061
0
  }
4062
4063
  /// Return the number and kind of trailing objects
4064
  /// related to the exception specification.
4065
7.38M
  ExceptionSpecSizeHolder getExceptionSpecSize() const {
4066
7.38M
    return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions());
4067
7.38M
  }
4068
4069
  /// Whether the trailing FunctionTypeExtraBitfields is present.
4070
33.5M
  static bool hasExtraBitfields(ExceptionSpecificationType EST) {
4071
    // If the exception spec type is EST_Dynamic then we have > 0 exception
4072
    // types and the exact number is stored in FunctionTypeExtraBitfields.
4073
33.5M
    return EST == EST_Dynamic;
4074
33.5M
  }
4075
4076
  /// Whether the trailing FunctionTypeExtraBitfields is present.
4077
6.39M
  bool hasExtraBitfields() const {
4078
6.39M
    return hasExtraBitfields(getExceptionSpecType());
4079
6.39M
  }
4080
4081
84.0M
  bool hasExtQualifiers() const {
4082
84.0M
    return FunctionTypeBits.HasExtQuals;
4083
84.0M
  }
4084
4085
public:
4086
545M
  unsigned getNumParams() const { return FunctionTypeBits.NumParams; }
4087
4088
15.3M
  QualType getParamType(unsigned i) const {
4089
15.3M
    assert(i < getNumParams() && "invalid parameter index");
4090
15.3M
    return param_type_begin()[i];
4091
15.3M
  }
4092
4093
1.99M
  ArrayRef<QualType> getParamTypes() const {
4094
1.99M
    return llvm::makeArrayRef(param_type_begin(), param_type_end());
4095
1.99M
  }
4096
4097
73.3M
  ExtProtoInfo getExtProtoInfo() const {
4098
73.3M
    ExtProtoInfo EPI;
4099
73.3M
    EPI.ExtInfo = getExtInfo();
4100
73.3M
    EPI.Variadic = isVariadic();
4101
73.3M
    EPI.EllipsisLoc = getEllipsisLoc();
4102
73.3M
    EPI.HasTrailingReturn = hasTrailingReturn();
4103
73.3M
    EPI.ExceptionSpec = getExceptionSpecInfo();
4104
73.3M
    EPI.TypeQuals = getMethodQuals();
4105
73.3M
    EPI.RefQualifier = getRefQualifier();
4106
73.3M
    EPI.ExtParameterInfos = getExtParameterInfosOrNull();
4107
73.3M
    return EPI;
4108
73.3M
  }
4109
4110
  /// Get the kind of exception specification on this function.
4111
270M
  ExceptionSpecificationType getExceptionSpecType() const {
4112
270M
    return static_cast<ExceptionSpecificationType>(
4113
270M
        FunctionTypeBits.ExceptionSpecType);
4114
270M
  }
4115
4116
  /// Return whether this function has any kind of exception spec.
4117
83.2M
  bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; }
4118
4119
  /// Return whether this function has a dynamic (throw) exception spec.
4120
46.2k
  bool hasDynamicExceptionSpec() const {
4121
46.2k
    return isDynamicExceptionSpec(getExceptionSpecType());
4122
46.2k
  }
4123
4124
  /// Return whether this function has a noexcept exception spec.
4125
0
  bool hasNoexceptExceptionSpec() const {
4126
0
    return isNoexceptExceptionSpec(getExceptionSpecType());
4127
0
  }
4128
4129
  /// Return whether this function has a dependent exception spec.
4130
  bool hasDependentExceptionSpec() const;
4131
4132
  /// Return whether this function has an instantiation-dependent exception
4133
  /// spec.
4134
  bool hasInstantiationDependentExceptionSpec() const;
4135
4136
  /// Return all the available information about this type's exception spec.
4137
73.6M
  ExceptionSpecInfo getExceptionSpecInfo() const {
4138
73.6M
    ExceptionSpecInfo Result;
4139
73.6M
    Result.Type = getExceptionSpecType();
4140
73.6M
    if (Result.Type == EST_Dynamic) {
4141
2.45k
      Result.Exceptions = exceptions();
4142
73.6M
    } else if (isComputedNoexcept(Result.Type)) {
4143
1.24M
      Result.NoexceptExpr = getNoexceptExpr();
4144
72.3M
    } else if (Result.Type == EST_Uninstantiated) {
4145
214k
      Result.SourceDecl = getExceptionSpecDecl();
4146
214k
      Result.SourceTemplate = getExceptionSpecTemplate();
4147
72.1M
    } else if (Result.Type == EST_Unevaluated) {
4148
1.56M
      Result.SourceDecl = getExceptionSpecDecl();
4149
1.56M
    }
4150
73.6M
    return Result;
4151
73.6M
  }
4152
4153
  /// Return the number of types in the exception specification.
4154
8.40M
  unsigned getNumExceptions() const {
4155
8.40M
    return getExceptionSpecType() == EST_Dynamic
4156
4.82k
               ? getTrailingObjects<FunctionTypeExtraBitfields>()
4157
4.82k
                     ->NumExceptionType
4158
8.39M
               : 0;
4159
8.40M
  }
4160
4161
  /// Return the ith exception type, where 0 <= i < getNumExceptions().
4162
853
  QualType getExceptionType(unsigned i) const {
4163
853
    assert(i < getNumExceptions() && "Invalid exception number!");
4164
853
    return exception_begin()[i];
4165
853
  }
4166
4167
  /// Return the expression inside noexcept(expression), or a null pointer
4168
  /// if there is none (because the exception spec is not of this form).
4169
1.93M
  Expr *getNoexceptExpr() const {
4170
1.93M
    if (!isComputedNoexcept(getExceptionSpecType()))
4171
658k
      return nullptr;
4172
1.27M
    return *getTrailingObjects<Expr *>();
4173
1.27M
  }
4174
4175
  /// If this function type has an exception specification which hasn't
4176
  /// been determined yet (either because it has not been evaluated or because
4177
  /// it has not been instantiated), this is the function whose exception
4178
  /// specification is represented by this type.
4179
1.96M
  FunctionDecl *getExceptionSpecDecl() const {
4180
1.96M
    if (getExceptionSpecType() != EST_Uninstantiated &&
4181
1.74M
        getExceptionSpecType() != EST_Unevaluated)
4182
0
      return nullptr;
4183
1.96M
    return getTrailingObjects<FunctionDecl *>()[0];
4184
1.96M
  }
4185
4186
  /// If this function type has an uninstantiated exception
4187
  /// specification, this is the function whose exception specification
4188
  /// should be instantiated to find the exception specification for
4189
  /// this type.
4190
220k
  FunctionDecl *getExceptionSpecTemplate() const {
4191
220k
    if (getExceptionSpecType() != EST_Uninstantiated)
4192
0
      return nullptr;
4193
220k
    return getTrailingObjects<FunctionDecl *>()[1];
4194
220k
  }
4195
4196
  /// Determine whether this function type has a non-throwing exception
4197
  /// specification.
4198
  CanThrowResult canThrow() const;
4199
4200
  /// Determine whether this function type has a non-throwing exception
4201
  /// specification. If this depends on template arguments, returns
4202
  /// \c ResultIfDependent.
4203
1.00M
  bool isNothrow(bool ResultIfDependent = false) const {
4204
1.00M
    return ResultIfDependent ? 
canThrow() != CT_Can1.63k
: canThrow() == CT_Cannot;
4205
1.00M
  }
4206
4207
  /// Whether this function prototype is variadic.
4208
260M
  bool isVariadic() const { return FunctionTypeBits.Variadic; }
4209
4210
73.3M
  SourceLocation getEllipsisLoc() const {
4211
840k
    return isVariadic() ? *getTrailingObjects<SourceLocation>()
4212
72.4M
                        : SourceLocation();
4213
73.3M
  }
4214
4215
  /// Determines whether this function prototype contains a
4216
  /// parameter pack at the end.
4217
  ///
4218
  /// A function template whose last parameter is a parameter pack can be
4219
  /// called with an arbitrary number of arguments, much like a variadic
4220
  /// function.
4221
  bool isTemplateVariadic() const;
4222
4223
  /// Whether this function prototype has a trailing return type.
4224
79.3M
  bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; }
4225
4226
84.0M
  Qualifiers getMethodQuals() const {
4227
84.0M
    if (hasExtQualifiers())
4228
2.12k
      return *getTrailingObjects<Qualifiers>();
4229
84.0M
    else
4230
84.0M
      return getFastTypeQuals();
4231
84.0M
  }
4232
4233
  /// Retrieve the ref-qualifier associated with this function type.
4234
79.9M
  RefQualifierKind getRefQualifier() const {
4235
79.9M
    return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
4236
79.9M
  }
4237
4238
  using param_type_iterator = const QualType *;
4239
  using param_type_range = llvm::iterator_range<param_type_iterator>;
4240
4241
5.79M
  param_type_range param_types() const {
4242
5.79M
    return param_type_range(param_type_begin(), param_type_end());
4243
5.79M
  }
4244
4245
243M
  param_type_iterator param_type_begin() const {
4246
243M
    return getTrailingObjects<QualType>();
4247
243M
  }
4248
4249
55.7M
  param_type_iterator param_type_end() const {
4250
55.7M
    return param_type_begin() + getNumParams();
4251
55.7M
  }
4252
4253
  using exception_iterator = const QualType *;
4254
4255
1.01M
  ArrayRef<QualType> exceptions() const {
4256
1.01M
    return llvm::makeArrayRef(exception_begin(), exception_end());
4257
1.01M
  }
4258
4259
2.02M
  exception_iterator exception_begin() const {
4260
2.02M
    return reinterpret_cast<exception_iterator>(
4261
2.02M
        getTrailingObjects<ExceptionType>());
4262
2.02M
  }
4263
4264
1.01M
  exception_iterator exception_end() const {
4265
1.01M
    return exception_begin() + getNumExceptions();
4266
1.01M
  }
4267
4268
  /// Is there any interesting extra information for any of the parameters
4269
  /// of this function type?
4270
83.2M
  bool hasExtParameterInfos() const {
4271
83.2M
    return FunctionTypeBits.HasExtParameterInfos;
4272
83.2M
  }
4273
4274
1.53k
  ArrayRef<ExtParameterInfo> getExtParameterInfos() const {
4275
1.53k
    assert(hasExtParameterInfos());
4276
1.53k
    return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(),
4277
1.53k
                                      getNumParams());
4278
1.53k
  }
4279
4280
  /// Return a pointer to the beginning of the array of extra parameter
4281
  /// information, if present, or else null if none of the parameters
4282
  /// carry it.  This is equivalent to getExtProtoInfo().ExtParameterInfos.
4283
74.5M
  const ExtParameterInfo *getExtParameterInfosOrNull() const {
4284
74.5M
    if (!hasExtParameterInfos())
4285
74.4M
      return nullptr;
4286
110k
    return getTrailingObjects<ExtParameterInfo>();
4287
110k
  }
4288
4289
5.52M
  ExtParameterInfo getExtParameterInfo(unsigned I) const {
4290
5.52M
    assert(I < getNumParams() && "parameter index out of range");
4291
5.52M
    if (hasExtParameterInfos())
4292
1.37k
      return getTrailingObjects<ExtParameterInfo>()[I];
4293
5.52M
    return ExtParameterInfo();
4294
5.52M
  }
4295
4296
0
  ParameterABI getParameterABI(unsigned I) const {
4297
0
    assert(I < getNumParams() && "parameter index out of range");
4298
0
    if (hasExtParameterInfos())
4299
0
      return getTrailingObjects<ExtParameterInfo>()[I].getABI();
4300
0
    return ParameterABI::Ordinary;
4301
0
  }
4302
4303
19.6k
  bool isParamConsumed(unsigned I) const {
4304
19.6k
    assert(I < getNumParams() && "parameter index out of range");
4305
19.6k
    if (hasExtParameterInfos())
4306
14
      return getTrailingObjects<ExtParameterInfo>()[I].isConsumed();
4307
19.6k
    return false;
4308
19.6k
  }
4309
4310
3.18M
  bool isSugared() const { return false; }
4311
153
  QualType desugar() const { return QualType(this, 0); }
4312
4313
  void printExceptionSpecification(raw_ostream &OS,
4314
                                   const PrintingPolicy &Policy) const;
4315
4316
1.11G
  static bool classof(const Type *T) {
4317
1.11G
    return T->getTypeClass() == FunctionProto;
4318
1.11G
  }
4319
4320
  void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
4321
  static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
4322
                      param_type_iterator ArgTys, unsigned NumArgs,
4323
                      const ExtProtoInfo &EPI, const ASTContext &Context,
4324
                      bool Canonical);
4325
};
4326
4327
/// Represents the dependent type named by a dependently-scoped
4328
/// typename using declaration, e.g.
4329
///   using typename Base<T>::foo;
4330
///
4331
/// Template instantiation turns these into the underlying type.
4332
class UnresolvedUsingType : public Type {
4333
  friend class ASTContext; // ASTContext creates these.
4334
4335
  UnresolvedUsingTypenameDecl *Decl;
4336
4337
  UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
4338
      : Type(UnresolvedUsing, QualType(),
4339
             TypeDependence::DependentInstantiation),
4340
1.11k
        Decl(const_cast<UnresolvedUsingTypenameDecl *>(D)) {}
4341
4342
public:
4343
1.21k
  UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
4344
4345
286
  bool isSugared() const { return false; }
4346
0
  QualType desugar() const { return QualType(this, 0); }
4347
4348
19.7k
  static bool classof(const Type *T) {
4349
19.7k
    return T->getTypeClass() == UnresolvedUsing;
4350
19.7k
  }
4351
4352
0
  void Profile(llvm::FoldingSetNodeID &ID) {
4353
0
    return Profile(ID, Decl);
4354
0
  }
4355
4356
  static void Profile(llvm::FoldingSetNodeID &ID,
4357
0
                      UnresolvedUsingTypenameDecl *D) {
4358
0
    ID.AddPointer(D);
4359
0
  }
4360
};
4361
4362
class TypedefType : public Type {
4363
  TypedefNameDecl *Decl;
4364
4365
protected:
4366
  friend class ASTContext; // ASTContext creates these.
4367
4368
  TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can);
4369
4370
public:
4371
72.0M
  TypedefNameDecl *getDecl() const { return Decl; }
4372
4373
50.1M
  bool isSugared() const { return true; }
4374
  QualType desugar() const;
4375
4376
420M
  static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
4377
};
4378
4379
/// Sugar type that represents a type that was qualified by a qualifier written
4380
/// as a macro invocation.
4381
class MacroQualifiedType : public Type {
4382
  friend class ASTContext; // ASTContext creates these.
4383
4384
  QualType UnderlyingTy;
4385
  const IdentifierInfo *MacroII;
4386
4387
  MacroQualifiedType(QualType UnderlyingTy, QualType CanonTy,
4388
                     const IdentifierInfo *MacroII)
4389
      : Type(MacroQualified, CanonTy, UnderlyingTy->getDependence()),
4390
318k
        UnderlyingTy(UnderlyingTy), MacroII(MacroII) {
4391
318k
    assert(isa<AttributedType>(UnderlyingTy) &&
4392
318k
           "Expected a macro qualified type to only wrap attributed types.");
4393
318k
  }
4394
4395
public:
4396
9.99k
  const IdentifierInfo *getMacroIdentifier() const { return MacroII; }
4397
2.44M
  QualType getUnderlyingType() const { return UnderlyingTy; }
4398
4399
  /// Return this attributed type's modified type with no qualifiers attached to
4400
  /// it.
4401
  QualType getModifiedType() const;
4402
4403
355k
  bool isSugared() const { return true; }
4404
  QualType desugar() const;
4405
4406
42.5M
  static bool classof(const Type *T) {
4407
42.5M
    return T->getTypeClass() == MacroQualified;
4408
42.5M
  }
4409
};
4410
4411
/// Represents a `typeof` (or __typeof__) expression (a GCC extension).
4412
class TypeOfExprType : public Type {
4413
  Expr *TOExpr;
4414
4415
protected:
4416
  friend class ASTContext; // ASTContext creates these.
4417
4418
  TypeOfExprType(Expr *E, QualType can = QualType());
4419
4420
public:
4421
18.5k
  Expr *getUnderlyingExpr() const { return TOExpr; }
4422
4423
  /// Remove a single level of sugar.
4424
  QualType desugar() const;
4425
4426
  /// Returns whether this type directly provides sugar.
4427
  bool isSugared() const;
4428
4429
111k
  static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
4430
};
4431
4432
/// Internal representation of canonical, dependent
4433
/// `typeof(expr)` types.
4434
///
4435
/// This class is used internally by the ASTContext to manage
4436
/// canonical, dependent types, only. Clients will only see instances
4437
/// of this class via TypeOfExprType nodes.
4438
class DependentTypeOfExprType
4439
  : public TypeOfExprType, public llvm::FoldingSetNode {
4440
  const ASTContext &Context;
4441
4442
public:
4443
  DependentTypeOfExprType(const ASTContext &Context, Expr *E)
4444
244
      : TypeOfExprType(E), Context(Context) {}
4445
4446
868
  void Profile(llvm::FoldingSetNodeID &ID) {
4447
868
    Profile(ID, Context, getUnderlyingExpr());
4448
868
  }
4449
4450
  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4451
                      Expr *E);
4452
};
4453
4454
/// Represents `typeof(type)`, a GCC extension.
4455
class TypeOfType : public Type {
4456
  friend class ASTContext; // ASTContext creates these.
4457
4458
  QualType TOType;
4459
4460
  TypeOfType(QualType T, QualType can)
4461
110
      : Type(TypeOf, can, T->getDependence()), TOType(T) {
4462
110
    assert(!isa<TypedefType>(can) && "Invalid canonical type");
4463
110
  }
4464
4465
public:
4466
560
  QualType getUnderlyingType() const { return TOType; }
4467
4468
  /// Remove a single level of sugar.
4469
515
  QualType desugar() const { return getUnderlyingType(); }
4470
4471
  /// Returns whether this type directly provides sugar.
4472
492
  bool isSugared() const { return true; }
4473
4474
1.19k
  static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
4475
};
4476
4477
/// Represents the type `decltype(expr)` (C++11).
4478
class DecltypeType : public Type {
4479
  Expr *E;
4480
  QualType UnderlyingType;
4481
4482
protected:
4483
  friend class ASTContext; // ASTContext creates these.
4484
4485
  DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
4486
4487
public:
4488
208k
  Expr *getUnderlyingExpr() const { return E; }
4489
122k
  QualType getUnderlyingType() const { return UnderlyingType; }
4490
4491
  /// Remove a single level of sugar.
4492
  QualType desugar() const;
4493
4494
  /// Returns whether this type directly provides sugar.
4495
  bool isSugared() const;
4496
4497
3.95M
  static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
4498
};
4499
4500
/// Internal representation of canonical, dependent
4501
/// decltype(expr) types.
4502
///
4503
/// This class is used internally by the ASTContext to manage
4504
/// canonical, dependent types, only. Clients will only see instances
4505
/// of this class via DecltypeType nodes.
4506
class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
4507
  const ASTContext &Context;
4508
4509
public:
4510
  DependentDecltypeType(const ASTContext &Context, Expr *E);
4511
4512
33.4k
  void Profile(llvm::FoldingSetNodeID &ID) {
4513
33.4k
    Profile(ID, Context, getUnderlyingExpr());
4514
33.4k
  }
4515
4516
  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4517
                      Expr *E);
4518
};
4519
4520
/// A unary type transform, which is a type constructed from another.
4521
class UnaryTransformType : public Type {
4522
public:
4523
  enum UTTKind {
4524
    EnumUnderlyingType
4525
  };
4526
4527
private:
4528
  /// The untransformed type.
4529
  QualType BaseType;
4530
4531
  /// The transformed type if not dependent, otherwise the same as BaseType.
4532
  QualType UnderlyingType;
4533
4534
  UTTKind UKind;
4535
4536
protected:
4537
  friend class ASTContext;
4538
4539
  UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
4540
                     QualType CanonicalTy);
4541
4542
public:
4543
7.10k
  bool isSugared() const { return !isDependentType(); }
4544
7.51k
  QualType desugar() const { return UnderlyingType; }
4545
4546
746
  QualType getUnderlyingType() const { return UnderlyingType; }
4547
673
  QualType getBaseType() const { return BaseType; }
4548
4549
1.05k
  UTTKind getUTTKind() const { return UKind; }
4550
4551
26.1k
  static bool classof(const Type *T) {
4552
26.1k
    return T->getTypeClass() == UnaryTransform;
4553
26.1k
  }
4554
};
4555
4556
/// Internal representation of canonical, dependent
4557
/// __underlying_type(type) types.
4558
///
4559
/// This class is used internally by the ASTContext to manage
4560
/// canonical, dependent types, only. Clients will only see instances
4561
/// of this class via UnaryTransformType nodes.
4562
class DependentUnaryTransformType : public UnaryTransformType,
4563
                                    public llvm::FoldingSetNode {
4564
public:
4565
  DependentUnaryTransformType(const ASTContext &C, QualType BaseType,
4566
                              UTTKind UKind);
4567
4568
6
  void Profile(llvm::FoldingSetNodeID &ID) {
4569
6
    Profile(ID, getBaseType(), getUTTKind());
4570
6
  }
4571
4572
  static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
4573
467
                      UTTKind UKind) {
4574
467
    ID.AddPointer(BaseType.getAsOpaquePtr());
4575
467
    ID.AddInteger((unsigned)UKind);
4576
467
  }
4577
};
4578
4579
class TagType : public Type {
4580
  friend class ASTReader;
4581
  template <class T> friend class serialization::AbstractTypeReader;
4582
4583
  /// Stores the TagDecl associated with this type. The decl may point to any
4584
  /// TagDecl that declares the entity.
4585
  TagDecl *decl;
4586
4587
protected:
4588
  TagType(TypeClass TC, const TagDecl *D, QualType can);
4589
4590
public:
4591
  TagDecl *getDecl() const;
4592
4593
  /// Determines whether this type is in the process of being defined.
4594
  bool isBeingDefined() const;
4595
4596
586M
  static bool classof(const Type *T) {
4597
586M
    return T->getTypeClass() == Enum || 
T->getTypeClass() == Record556M
;
4598
586M
  }
4599
};
4600
4601
/// A helper class that allows the use of isa/cast/dyncast
4602
/// to detect TagType objects of structs/unions/classes.
4603
class RecordType : public TagType {
4604
protected:
4605
  friend class ASTContext; // ASTContext creates these.
4606
4607
  explicit RecordType(const RecordDecl *D)
4608
3.75M
      : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4609
  explicit RecordType(TypeClass TC, RecordDecl *D)
4610
0
      : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4611
4612
public:
4613
61.0M
  RecordDecl *getDecl() const {
4614
61.0M
    return reinterpret_cast<RecordDecl*>(TagType::getDecl());
4615
61.0M
  }
4616
4617
  /// Recursively check all fields in the record for const-ness. If any field
4618
  /// is declared const, return true. Otherwise, return false.
4619
  bool hasConstFields() const;
4620
4621
24.2M
  bool isSugared() const { return false; }
4622
0
  QualType desugar() const { return QualType(this, 0); }
4623
4624
347M
  static bool classof(const Type *T) { return T->getTypeClass() == Record; }
4625
};
4626
4627
/// A helper class that allows the use of isa/cast/dyncast
4628
/// to detect TagType objects of enums.
4629
class EnumType : public TagType {
4630
  friend class ASTContext; // ASTContext creates these.
4631
4632
  explicit EnumType(const EnumDecl *D)
4633
611k
      : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4634
4635
public:
4636
53.0M
  EnumDecl *getDecl() const {
4637
53.0M
    return reinterpret_cast<EnumDecl*>(TagType::getDecl());
4638
53.0M
  }
4639
4640
2.72M
  bool isSugared() const { return false; }
4641
0
  QualType desugar() const { return QualType(this, 0); }
4642
4643
221M
  static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
4644
};
4645
4646
/// An attributed type is a type to which a type attribute has been applied.
4647
///
4648
/// The "modified type" is the fully-sugared type to which the attributed
4649
/// type was applied; generally it is not canonically equivalent to the
4650
/// attributed type. The "equivalent type" is the minimally-desugared type
4651
/// which the type is canonically equivalent to.
4652
///
4653
/// For example, in the following attributed type:
4654
///     int32_t __attribute__((vector_size(16)))
4655
///   - the modified type is the TypedefType for int32_t
4656
///   - the equivalent type is VectorType(16, int32_t)
4657
///   - the canonical type is VectorType(16, int)
4658
class AttributedType : public Type, public llvm::FoldingSetNode {
4659
public:
4660
  using Kind = attr::Kind;
4661
4662
private:
4663
  friend class ASTContext; // ASTContext creates these
4664
4665
  QualType ModifiedType;
4666
  QualType EquivalentType;
4667
4668
  AttributedType(QualType canon, attr::Kind attrKind, QualType modified,
4669
                 QualType equivalent)
4670
      : Type(Attributed, canon, equivalent->getDependence()),
4671
510k
        ModifiedType(modified), EquivalentType(equivalent) {
4672
510k
    AttributedTypeBits.AttrKind = attrKind;
4673
510k
  }
4674
4675
public:
4676
9.32M
  Kind getAttrKind() const {
4677
9.32M
    return static_cast<Kind>(AttributedTypeBits.AttrKind);
4678
9.32M
  }
4679
4680
23.3M
  QualType getModifiedType() const { return ModifiedType; }
4681
2.72M
  QualType getEquivalentType() const { return EquivalentType; }
4682
4683
2.53M
  bool isSugared() const { return true; }
4684
2.53M
  QualType desugar() const { return getEquivalentType(); }
4685
4686
  /// Does this attribute behave like a type qualifier?
4687
  ///
4688
  /// A type qualifier adjusts a type to provide specialized rules for
4689
  /// a specific object, like the standard const and volatile qualifiers.
4690
  /// This includes attributes controlling things like nullability,
4691
  /// address spaces, and ARC ownership.  The value of the object is still
4692
  /// largely described by the modified type.
4693
  ///
4694
  /// In contrast, many type attributes "rewrite" their modified type to
4695
  /// produce a fundamentally different type, not necessarily related in any
4696
  /// formalizable way to the original type.  For example, calling convention
4697
  /// and vector attributes are not simple type qualifiers.
4698
  ///
4699
  /// Type qualifiers are often, but not always, reflected in the canonical
4700
  /// type.
4701
  bool isQualifier() const;
4702
4703
  bool isMSTypeSpec() const;
4704
4705
  bool isCallingConv() const;
4706
4707
  llvm::Optional<NullabilityKind> getImmediateNullability() const;
4708
4709
  /// Retrieve the attribute kind corresponding to the given
4710
  /// nullability kind.
4711
21.5k
  static Kind getNullabilityAttrKind(NullabilityKind kind) {
4712
21.5k
    switch (kind) {
4713
11.3k
    case NullabilityKind::NonNull:
4714
11.3k
      return attr::TypeNonNull;
4715
4716
10.1k
    case NullabilityKind::Nullable:
4717
10.1k
      return attr::TypeNullable;
4718
4719
7
    case NullabilityKind::Unspecified:
4720
7
      return attr::TypeNullUnspecified;
4721
0
    }
4722
0
    llvm_unreachable("Unknown nullability kind.");
4723
0
  }
4724
4725
  /// Strip off the top-level nullability annotation on the given
4726
  /// type, if it's there.
4727
  ///
4728
  /// \param T The type to strip. If the type is exactly an
4729
  /// AttributedType specifying nullability (without looking through
4730
  /// type sugar), the nullability is returned and this type changed
4731
  /// to the underlying modified type.
4732
  ///
4733
  /// \returns the top-level nullability, if present.
4734
  static Optional<NullabilityKind> stripOuterNullability(QualType &T);
4735
4736
6.91M
  void Profile(llvm::FoldingSetNodeID &ID) {
4737
6.91M
    Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
4738
6.91M
  }
4739
4740
  static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
4741
11.2M
                      QualType modified, QualType equivalent) {
4742
11.2M
    ID.AddInteger(attrKind);
4743
11.2M
    ID.AddPointer(modified.getAsOpaquePtr());
4744
11.2M
    ID.AddPointer(equivalent.getAsOpaquePtr());
4745
11.2M
  }
4746
4747
222M
  static bool classof(const Type *T) {
4748
222M
    return T->getTypeClass() == Attributed;
4749
222M
  }
4750
};
4751
4752
class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4753
  friend class ASTContext; // ASTContext creates these
4754
4755
  // Helper data collector for canonical types.
4756
  struct CanonicalTTPTInfo {
4757
    unsigned Depth : 15;
4758
    unsigned ParameterPack : 1;
4759
    unsigned Index : 16;
4760
  };
4761
4762
  union {
4763
    // Info for the canonical type.
4764
    CanonicalTTPTInfo CanTTPTInfo;
4765
4766
    // Info for the non-canonical type.
4767
    TemplateTypeParmDecl *TTPDecl;
4768
  };
4769
4770
  /// Build a non-canonical type.
4771
  TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
4772
      : Type(TemplateTypeParm, Canon,
4773
             TypeDependence::DependentInstantiation |
4774
                 (Canon->getDependence() & TypeDependence::UnexpandedPack)),
4775
3.64M
        TTPDecl(TTPDecl) {}
4776
4777
  /// Build the canonical type.
4778
  TemplateTypeParmType(unsigned D, unsigned I, bool PP)
4779
      : Type(TemplateTypeParm, QualType(this, 0),
4780
             TypeDependence::DependentInstantiation |
4781
51.3k
                 (PP ? TypeDependence::UnexpandedPack : TypeDependence::None)) {
4782
51.3k
    CanTTPTInfo.Depth = D;
4783
51.3k
    CanTTPTInfo.Index = I;
4784
51.3k
    CanTTPTInfo.ParameterPack = PP;
4785
51.3k
  }
4786
4787
161M
  const CanonicalTTPTInfo& getCanTTPTInfo() const {
4788
161M
    QualType Can = getCanonicalTypeInternal();
4789
161M
    return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
4790
161M
  }
4791
4792
public:
4793
52.1M
  unsigned getDepth() const { return getCanTTPTInfo().Depth; }
4794
42.7M
  unsigned getIndex() const { return getCanTTPTInfo().Index; }
4795
66.0M
  bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
4796
4797
25.8M
  TemplateTypeParmDecl *getDecl() const {
4798
22.0M
    return isCanonicalUnqualified() ? 
nullptr3.85M
: TTPDecl;
4799
25.8M
  }
4800
4801
  IdentifierInfo *getIdentifier() const;
4802
4803
1.14M
  bool isSugared() const { return false; }
4804
0
  QualType desugar() const { return QualType(this, 0); }
4805
4806
23.1M
  void Profile(llvm::FoldingSetNodeID &ID) {
4807
23.1M
    Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
4808
23.1M
  }
4809
4810
  static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
4811
                      unsigned Index, bool ParameterPack,
4812
31.9M
                      TemplateTypeParmDecl *TTPDecl) {
4813
31.9M
    ID.AddInteger(Depth);
4814
31.9M
    ID.AddInteger(Index);
4815
31.9M
    ID.AddBoolean(ParameterPack);
4816
31.9M
    ID.AddPointer(TTPDecl);
4817
31.9M
  }
4818
4819
342M
  static bool classof(const Type *T) {
4820
342M
    return T->getTypeClass() == TemplateTypeParm;
4821
342M
  }
4822
};
4823
4824
/// Represents the result of substituting a type for a template
4825
/// type parameter.
4826
///
4827
/// Within an instantiated template, all template type parameters have
4828
/// been replaced with these.  They are used solely to record that a
4829
/// type was originally written as a template type parameter;
4830
/// therefore they are never canonical.
4831
class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4832
  friend class ASTContext;
4833
4834
  // The original type parameter.
4835
  const TemplateTypeParmType *Replaced;
4836
4837
  SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
4838
      : Type(SubstTemplateTypeParm, Canon, Canon->getDependence()),
4839
1.73M
        Replaced(Param) {}
4840
4841
public:
4842
  /// Gets the template parameter that was substituted for.
4843
8.24M
  const TemplateTypeParmType *getReplacedParameter() const {
4844
8.24M
    return Replaced;
4845
8.24M
  }
4846
4847
  /// Gets the type that was substituted for the template
4848
  /// parameter.
4849
12.4M
  QualType getReplacementType() const {
4850
12.4M
    return getCanonicalTypeInternal();
4851
12.4M
  }
4852
4853
3.90M
  bool isSugared() const { return true; }
4854
3.91M
  QualType desugar() const { return getReplacementType(); }
4855
4856
8.10M
  void Profile(llvm::FoldingSetNodeID &ID) {
4857
8.10M
    Profile(ID, getReplacedParameter(), getReplacementType());
4858
8.10M
  }
4859
4860
  static void Profile(llvm::FoldingSetNodeID &ID,
4861
                      const TemplateTypeParmType *Replaced,
4862
12.7M
                      QualType Replacement) {
4863
12.7M
    ID.AddPointer(Replaced);
4864
12.7M
    ID.AddPointer(Replacement.getAsOpaquePtr());
4865
12.7M
  }
4866
4867
74.9M
  static bool classof(const Type *T) {
4868
74.9M
    return T->getTypeClass() == SubstTemplateTypeParm;
4869
74.9M
  }
4870
};
4871
4872
/// Represents the result of substituting a set of types for a template
4873
/// type parameter pack.
4874
///
4875
/// When a pack expansion in the source code contains multiple parameter packs
4876
/// and those parameter packs correspond to different levels of template
4877
/// parameter lists, this type node is used to represent a template type
4878
/// parameter pack from an outer level, which has already had its argument pack
4879
/// substituted but that still lives within a pack expansion that itself
4880
/// could not be instantiated. When actually performing a substitution into
4881
/// that pack expansion (e.g., when all template parameters have corresponding
4882
/// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
4883
/// at the current pack substitution index.
4884
class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
4885
  friend class ASTContext;
4886
4887
  /// The original type parameter.
4888
  const TemplateTypeParmType *Replaced;
4889
4890
  /// A pointer to the set of template arguments that this
4891
  /// parameter pack is instantiated with.
4892
  const TemplateArgument *Arguments;
4893
4894
  SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
4895
                                QualType Canon,
4896
                                const TemplateArgument &ArgPack);
4897
4898
public:
4899
0
  IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
4900
4901
  /// Gets the template parameter that was substituted for.
4902
115k
  const TemplateTypeParmType *getReplacedParameter() const {
4903
115k
    return Replaced;
4904
115k
  }
4905
4906
175k
  unsigned getNumArgs() const {
4907
175k
    return SubstTemplateTypeParmPackTypeBits.NumArgs;
4908
175k
  }
4909
4910
14
  bool isSugared() const { return false; }
4911
0
  QualType desugar() const { return QualType(this, 0); }
4912
4913
  TemplateArgument getArgumentPack() const;
4914
4915
  void Profile(llvm::FoldingSetNodeID &ID);
4916
  static void Profile(llvm::FoldingSetNodeID &ID,
4917
                      const TemplateTypeParmType *Replaced,
4918
                      const TemplateArgument &ArgPack);
4919
4920
2.35M
  static bool classof(const Type *T) {
4921
2.35M
    return T->getTypeClass() == SubstTemplateTypeParmPack;
4922
2.35M
  }
4923
};
4924
4925
/// Common base class for placeholders for types that get replaced by
4926
/// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced
4927
/// class template types, and constrained type names.
4928
///
4929
/// These types are usually a placeholder for a deduced type. However, before
4930
/// the initializer is attached, or (usually) if the initializer is
4931
/// type-dependent, there is no deduced type and the type is canonical. In
4932
/// the latter case, it is also a dependent type.
4933
class DeducedType : public Type {
4934
protected:
4935
  DeducedType(TypeClass TC, QualType DeducedAsType,
4936
              TypeDependence ExtraDependence)
4937
      : Type(TC,
4938
             // FIXME: Retain the sugared deduced type?
4939
             DeducedAsType.isNull() ? QualType(this, 0)
4940
                                    : DeducedAsType.getCanonicalType(),
4941
             ExtraDependence | (DeducedAsType.isNull()
4942
                                    ? TypeDependence::None
4943
                                    : DeducedAsType->getDependence() &
4944
14.0k
                                          ~TypeDependence::VariablyModified)) {}
4945
4946
public:
4947
173k
  bool isSugared() const { return !isCanonicalUnqualified(); }
4948
170k
  QualType desugar() const { return getCanonicalTypeInternal(); }
4949
4950
  /// Get the type deduced for this placeholder type, or null if it's
4951
  /// either not been deduced or was deduced to a dependent type.
4952
67.3k
  QualType getDeducedType() const {
4953
39.1k
    return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : 
QualType()28.1k
;
4954
67.3k
  }
4955
85.1k
  bool isDeduced() const {
4956
85.1k
    return !isCanonicalUnqualified() || 
isDependentType()60.4k
;
4957
85.1k
  }
4958
4959
139M
  static bool classof(const Type *T) {
4960
139M
    return T->getTypeClass() == Auto ||
4961
139M
           T->getTypeClass() == DeducedTemplateSpecialization;
4962
139M
  }
4963
};
4964
4965
/// Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained
4966
/// by a type-constraint.
4967
class alignas(8) AutoType : public DeducedType, public llvm::FoldingSetNode {
4968
  friend class ASTContext; // ASTContext creates these
4969
4970
  ConceptDecl *TypeConstraintConcept;
4971
4972
  AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
4973
           TypeDependence ExtraDependence, ConceptDecl *CD,
4974
           ArrayRef<TemplateArgument> TypeConstraintArgs);
4975
4976
84.7k
  const TemplateArgument *getArgBuffer() const {
4977
84.7k
    return reinterpret_cast<const TemplateArgument*>(this+1);
4978
84.7k
  }
4979
4980
46
  TemplateArgument *getArgBuffer() {
4981
46
    return reinterpret_cast<TemplateArgument*>(this+1);
4982
46
  }
4983
4984
public:
4985
  /// Retrieve the template arguments.
4986
84.7k
  const TemplateArgument *getArgs() const {
4987
84.7k
    return getArgBuffer();
4988
84.7k
  }
4989
4990
  /// Retrieve the number of template arguments.
4991
340k
  unsigned getNumArgs() const {
4992
340k
    return AutoTypeBits.NumArgs;
4993
340k
  }
4994
4995
  const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4996
4997
59.7k
  ArrayRef<TemplateArgument> getTypeConstraintArguments() const {
4998
59.7k
    return {getArgs(), getNumArgs()};
4999
59.7k
  }
5000
5001
59.7k
  ConceptDecl *getTypeConstraintConcept() const {
5002
59.7k
    return TypeConstraintConcept;
5003
59.7k
  }
5004
5005
115k
  bool isConstrained() const {
5006
115k
    return TypeConstraintConcept != nullptr;
5007
115k
  }
5008
5009
52.1k
  bool isDecltypeAuto() const {
5010
52.1k
    return getKeyword() == AutoTypeKeyword::DecltypeAuto;
5011
52.1k
  }
5012
5013
155k
  AutoTypeKeyword getKeyword() const {
5014
155k
    return (AutoTypeKeyword)AutoTypeBits.Keyword;
5015
155k
  }
5016
5017
30.2k
  void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5018
30.2k
    Profile(ID, Context, getDeducedType(), getKeyword(), isDependentType(),
5019
30.2k
            getTypeConstraintConcept(), getTypeConstraintArguments());
5020
30.2k
  }
5021
5022
  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
5023
                      QualType Deduced, AutoTypeKeyword Keyword,
5024
                      bool IsDependent, ConceptDecl *CD,
5025
                      ArrayRef<TemplateArgument> Arguments);
5026
5027
8.83M
  static bool classof(const Type *T) {
5028
8.83M
    return T->getTypeClass() == Auto;
5029
8.83M
  }
5030
};
5031
5032
/// Represents a C++17 deduced template specialization type.
5033
class DeducedTemplateSpecializationType : public DeducedType,
5034
                                          public llvm::FoldingSetNode {
5035
  friend class ASTContext; // ASTContext creates these
5036
5037
  /// The name of the template whose arguments will be deduced.
5038
  TemplateName Template;
5039
5040
  DeducedTemplateSpecializationType(TemplateName Template,
5041
                                    QualType DeducedAsType,
5042
                                    bool IsDeducedAsDependent)
5043
      : DeducedType(DeducedTemplateSpecialization, DeducedAsType,
5044
                    toTypeDependence(Template.getDependence()) |
5045
                        (IsDeducedAsDependent
5046
                             ? TypeDependence::DependentInstantiation
5047
                             : TypeDependence::None)),
5048
761
        Template(Template) {}
5049
5050
public:
5051
  /// Retrieve the name of the template that we are deducing.
5052
3.08k
  TemplateName getTemplateName() const { return Template;}
5053
5054
1.69k
  void Profile(llvm::FoldingSetNodeID &ID) {
5055
1.69k
    Profile(ID, getTemplateName(), getDeducedType(), isDependentType());
5056
1.69k
  }
5057
5058
  static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template,
5059
3.28k
                      QualType Deduced, bool IsDependent) {
5060
3.28k
    Template.Profile(ID);
5061
3.28k
    ID.AddPointer(Deduced.getAsOpaquePtr());
5062
3.28k
    ID.AddBoolean(IsDependent);
5063
3.28k
  }
5064
5065
179k
  static bool classof(const Type *T) {
5066
179k
    return T->getTypeClass() == DeducedTemplateSpecialization;
5067
179k
  }
5068
};
5069
5070
/// Represents a type template specialization; the template
5071
/// must be a class template, a type alias template, or a template
5072
/// template parameter.  A template which cannot be resolved to one of
5073
/// these, e.g. because it is written with a dependent scope
5074
/// specifier, is instead represented as a
5075
/// @c DependentTemplateSpecializationType.
5076
///
5077
/// A non-dependent template specialization type is always "sugar",
5078
/// typically for a \c RecordType.  For example, a class template
5079
/// specialization type of \c vector<int> will refer to a tag type for
5080
/// the instantiation \c std::vector<int, std::allocator<int>>
5081
///
5082
/// Template specializations are dependent if either the template or
5083
/// any of the template arguments are dependent, in which case the
5084
/// type may also be canonical.
5085
///
5086
/// Instances of this type are allocated with a trailing array of
5087
/// TemplateArguments, followed by a QualType representing the
5088
/// non-canonical aliased type when the template is a type alias
5089
/// template.
5090
class alignas(8) TemplateSpecializationType
5091
    : public Type,
5092
      public llvm::FoldingSetNode {
5093
  friend class ASTContext; // ASTContext creates these
5094
5095
  /// The name of the template being specialized.  This is
5096
  /// either a TemplateName::Template (in which case it is a
5097
  /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
5098
  /// TypeAliasTemplateDecl*), a
5099
  /// TemplateName::SubstTemplateTemplateParmPack, or a
5100
  /// TemplateName::SubstTemplateTemplateParm (in which case the
5101
  /// replacement must, recursively, be one of these).
5102
  TemplateName Template;
5103
5104
  TemplateSpecializationType(TemplateName T,
5105
                             ArrayRef<TemplateArgument> Args,
5106
                             QualType Canon,
5107
                             QualType Aliased);
5108
5109
public:
5110
  /// Determine whether any of the given template arguments are dependent.
5111
  static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
5112
                                            bool &InstantiationDependent);
5113
5114
  static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
5115
                                            bool &InstantiationDependent);
5116
5117
  /// True if this template specialization type matches a current
5118
  /// instantiation in the context in which it is found.
5119
778k
  bool isCurrentInstantiation() const {
5120
778k
    return isa<InjectedClassNameType>(getCanonicalTypeInternal());
5121
778k
  }
5122
5123
  /// Determine if this template specialization type is for a type alias
5124
  /// template that has been substituted.
5125
  ///
5126
  /// Nearly every template specialization type whose template is an alias
5127
  /// template will be substituted. However, this is not the case when
5128
  /// the specialization contains a pack expansion but the template alias
5129
  /// does not have a corresponding parameter pack, e.g.,
5130
  ///
5131
  /// \code
5132
  /// template<typename T, typename U, typename V> struct S;
5133
  /// template<typename T, typename U> using A = S<T, int, U>;
5134
  /// template<typename... Ts> struct X {
5135
  ///   typedef A<Ts...> type; // not a type alias
5136
  /// };
5137
  /// \endcode
5138
25.6M
  bool isTypeAlias() const { return TemplateSpecializationTypeBits.TypeAlias; }
5139
5140
  /// Get the aliased type, if this is a specialization of a type alias
5141
  /// template.
5142
390k
  QualType getAliasedType() const {
5143
390k
    assert(isTypeAlias() && "not a type alias template specialization");
5144
390k
    return *reinterpret_cast<const QualType*>(end());
5145
390k
  }
5146
5147
  using iterator = const TemplateArgument *;
5148
5149
54
  iterator begin() const { return getArgs(); }
5150
  iterator end() const; // defined inline in TemplateBase.h
5151
5152
  /// Retrieve the name of the template that we are specializing.
5153
11.2M
  TemplateName getTemplateName() const { return Template; }
5154
5155
  /// Retrieve the template arguments.
5156
27.7M
  const TemplateArgument *getArgs() const {
5157
27.7M
    return reinterpret_cast<const TemplateArgument *>(this + 1);
5158
27.7M
  }
5159
5160
  /// Retrieve the number of template arguments.
5161
63.9M
  unsigned getNumArgs() const {
5162
63.9M
    return TemplateSpecializationTypeBits.NumArgs;
5163
63.9M
  }
5164
5165
  /// Retrieve a specific template argument as a type.
5166
  /// \pre \c isArgType(Arg)
5167
  const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5168
5169
9.92M
  ArrayRef<TemplateArgument> template_arguments() const {
5170
9.92M
    return {getArgs(), getNumArgs()};
5171
9.92M
  }
5172
5173
6.99M
  bool isSugared() const {
5174
6.99M
    return !isDependentType() || 
isCurrentInstantiation()778k
||
isTypeAlias()778k
;
5175
6.99M
  }
5176
5177
6.30M
  QualType desugar() const {
5178
5.94M
    return isTypeAlias() ? 
getAliasedType()359k
: getCanonicalTypeInternal();
5179
6.30M
  }
5180
5181
7.54M
  void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
5182
7.54M
    Profile(ID, Template, template_arguments(), Ctx);
5183
7.54M
    if (isTypeAlias())
5184
0
      getAliasedType().Profile(ID);
5185
7.54M
  }
5186
5187
  static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
5188
                      ArrayRef<TemplateArgument> Args,
5189
                      const ASTContext &Context);
5190
5191
306M
  static bool classof(const Type *T) {
5192
306M
    return T->getTypeClass() == TemplateSpecialization;
5193
306M
  }
5194
};
5195
5196
/// Print a template argument list, including the '<' and '>'
5197
/// enclosing the template arguments.
5198
void printTemplateArgumentList(raw_ostream &OS,
5199
                               ArrayRef<TemplateArgument> Args,
5200
                               const PrintingPolicy &Policy,
5201
                               const TemplateParameterList *TPL = nullptr);
5202
5203
void printTemplateArgumentList(raw_ostream &OS,
5204
                               ArrayRef<TemplateArgumentLoc> Args,
5205
                               const PrintingPolicy &Policy,
5206
                               const TemplateParameterList *TPL = nullptr);
5207
5208
void printTemplateArgumentList(raw_ostream &OS,
5209
                               const TemplateArgumentListInfo &Args,
5210
                               const PrintingPolicy &Policy,
5211
                               const TemplateParameterList *TPL = nullptr);
5212
5213
/// The injected class name of a C++ class template or class
5214
/// template partial specialization.  Used to record that a type was
5215
/// spelled with a bare identifier rather than as a template-id; the
5216
/// equivalent for non-templated classes is just RecordType.
5217
///
5218
/// Injected class name types are always dependent.  Template
5219
/// instantiation turns these into RecordTypes.
5220
///
5221
/// Injected class name types are always canonical.  This works
5222
/// because it is impossible to compare an injected class name type
5223
/// with the corresponding non-injected template type, for the same
5224
/// reason that it is impossible to directly compare template
5225
/// parameters from different dependent contexts: injected class name
5226
/// types can only occur within the scope of a particular templated
5227
/// declaration, and within that scope every template specialization
5228
/// will canonicalize to the injected class name (when appropriate
5229
/// according to the rules of the language).
5230
class InjectedClassNameType : public Type {
5231
  friend class ASTContext; // ASTContext creates these.
5232
  friend class ASTNodeImporter;
5233
  friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
5234
                          // currently suitable for AST reading, too much
5235
                          // interdependencies.
5236
  template <class T> friend class serialization::AbstractTypeReader;
5237
5238
  CXXRecordDecl *Decl;
5239
5240
  /// The template specialization which this type represents.
5241
  /// For example, in
5242
  ///   template <class T> class A { ... };
5243
  /// this is A<T>, whereas in
5244
  ///   template <class X, class Y> class A<B<X,Y> > { ... };
5245
  /// this is A<B<X,Y> >.
5246
  ///
5247
  /// It is always unqualified, always a template specialization type,
5248
  /// and always dependent.
5249
  QualType InjectedType;
5250
5251
  InjectedClassNameType(CXXRecordDecl *D, QualType TST)
5252
      : Type(InjectedClassName, QualType(),
5253
             TypeDependence::DependentInstantiation),
5254
566k
        Decl(D), InjectedType(TST) {
5255
566k
    assert(isa<TemplateSpecializationType>(TST));
5256
566k
    assert(!TST.hasQualifiers());
5257
566k
    assert(TST->isDependentType());
5258
566k
  }
5259
5260
public:
5261
1.70M
  QualType getInjectedSpecializationType() const { return InjectedType; }
5262
5263
100k
  const TemplateSpecializationType *getInjectedTST() const {
5264
100k
    return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
5265
100k
  }
5266
5267
1
  TemplateName getTemplateName() const {
5268
1
    return getInjectedTST()->getTemplateName();
5269
1
  }
5270
5271
  CXXRecordDecl *getDecl() const;
5272
5273
43.1k
  bool isSugared() const { return false; }
5274
0
  QualType desugar() const { return QualType(this, 0); }
5275
5276
181M
  static bool classof(const Type *T) {
5277
181M
    return T->getTypeClass() == InjectedClassName;
5278
181M
  }
5279
};
5280
5281
/// The kind of a tag type.
5282
enum TagTypeKind {
5283
  /// The "struct" keyword.
5284
  TTK_Struct,
5285
5286
  /// The "__interface" keyword.
5287
  TTK_Interface,
5288
5289
  /// The "union" keyword.
5290
  TTK_Union,
5291
5292
  /// The "class" keyword.
5293
  TTK_Class,
5294
5295
  /// The "enum" keyword.
5296
  TTK_Enum
5297
};
5298
5299
/// The elaboration keyword that precedes a qualified type name or
5300
/// introduces an elaborated-type-specifier.
5301
enum ElaboratedTypeKeyword {
5302
  /// The "struct" keyword introduces the elaborated-type-specifier.
5303
  ETK_Struct,
5304
5305
  /// The "__interface" keyword introduces the elaborated-type-specifier.
5306
  ETK_Interface,
5307
5308
  /// The "union" keyword introduces the elaborated-type-specifier.
5309
  ETK_Union,
5310
5311
  /// The "class" keyword introduces the elaborated-type-specifier.
5312
  ETK_Class,
5313
5314
  /// The "enum" keyword introduces the elaborated-type-specifier.
5315
  ETK_Enum,
5316
5317
  /// The "typename" keyword precedes the qualified type name, e.g.,
5318
  /// \c typename T::type.
5319
  ETK_Typename,
5320
5321
  /// No keyword precedes the qualified type name.
5322
  ETK_None
5323
};
5324
5325
/// A helper class for Type nodes having an ElaboratedTypeKeyword.
5326
/// The keyword in stored in the free bits of the base class.
5327
/// Also provides a few static helpers for converting and printing
5328
/// elaborated type keyword and tag type kind enumerations.
5329
class TypeWithKeyword : public Type {
5330
protected:
5331
  TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
5332
                  QualType Canonical, TypeDependence Dependence)
5333
3.63M
      : Type(tc, Canonical, Dependence) {
5334
3.63M
    TypeWithKeywordBits.Keyword = Keyword;
5335
3.63M
  }
5336
5337
public:
5338
15.1M
  ElaboratedTypeKeyword getKeyword() const {
5339
15.1M
    return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
5340
15.1M
  }
5341
5342
  /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
5343
  static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
5344
5345
  /// Converts a type specifier (DeclSpec::TST) into a tag type kind.
5346
  /// It is an error to provide a type specifier which *isn't* a tag kind here.
5347
  static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
5348
5349
  /// Converts a TagTypeKind into an elaborated type keyword.
5350
  static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
5351
5352
  /// Converts an elaborated type keyword into a TagTypeKind.
5353
  /// It is an error to provide an elaborated type keyword
5354
  /// which *isn't* a tag kind here.
5355
  static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
5356
5357
  static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
5358
5359
  static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
5360
5361
140k
  static StringRef getTagTypeKindName(TagTypeKind Kind) {
5362
140k
    return getKeywordName(getKeywordForTagTypeKind(Kind));
5363
140k
  }
5364
5365
  class CannotCastToThisType {};
5366
  static CannotCastToThisType classof(const Type *);
5367
};
5368
5369
/// Represents a type that was referred to using an elaborated type
5370
/// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
5371
/// or both.
5372
///
5373
/// This type is used to keep track of a type name as written in the
5374
/// source code, including tag keywords and any nested-name-specifiers.
5375
/// The type itself is always "sugar", used to express what was written
5376
/// in the source code but containing no additional semantic information.
5377
class ElaboratedType final
5378
    : public TypeWithKeyword,
5379
      public llvm::FoldingSetNode,
5380
      private llvm::TrailingObjects<ElaboratedType, TagDecl *> {
5381
  friend class ASTContext; // ASTContext creates these
5382
  friend TrailingObjects;
5383
5384
  /// The nested name specifier containing the qualifier.
5385
  NestedNameSpecifier *NNS;
5386
5387
  /// The type that this qualified name refers to.
5388
  QualType NamedType;
5389
5390
  /// The (re)declaration of this tag type owned by this occurrence is stored
5391
  /// as a trailing object if there is one. Use getOwnedTagDecl to obtain
5392
  /// it, or obtain a null pointer if there is none.
5393
5394
  ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5395
                 QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl)
5396
      : TypeWithKeyword(Keyword, Elaborated, CanonType,
5397
                        NamedType->getDependence()),
5398
1.86M
        NNS(NNS), NamedType(NamedType) {
5399
1.86M
    ElaboratedTypeBits.HasOwnedTagDecl = false;
5400
1.86M
    if (OwnedTagDecl) {
5401
534k
      ElaboratedTypeBits.HasOwnedTagDecl = true;
5402
534k
      *getTrailingObjects<TagDecl *>() = OwnedTagDecl;
5403
534k
    }
5404
1.86M
    assert(!(Keyword == ETK_None && NNS == nullptr) &&
5405
1.86M
           "ElaboratedType cannot have elaborated type keyword "