Coverage Report

Created: 2020-09-15 12:33

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