1 //===- TypePrinter.cpp - Pretty-Print Clang Types -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This contains code to print types from Clang's type system.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/Attr.h"
15 #include "clang/AST/Decl.h"
16 #include "clang/AST/DeclBase.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/NestedNameSpecifier.h"
22 #include "clang/AST/PrettyPrinter.h"
23 #include "clang/AST/TemplateBase.h"
24 #include "clang/AST/TemplateName.h"
25 #include "clang/AST/Type.h"
26 #include "clang/Basic/AddressSpaces.h"
27 #include "clang/Basic/ExceptionSpecificationType.h"
28 #include "clang/Basic/IdentifierTable.h"
29 #include "clang/Basic/LLVM.h"
30 #include "clang/Basic/LangOptions.h"
31 #include "clang/Basic/SourceLocation.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Basic/Specifiers.h"
34 #include "llvm/ADT/ArrayRef.h"
35 #include "llvm/ADT/SmallString.h"
36 #include "llvm/ADT/StringRef.h"
37 #include "llvm/ADT/Twine.h"
38 #include "llvm/Support/Casting.h"
39 #include "llvm/Support/Compiler.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/SaveAndRestore.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include <cassert>
44 #include <string>
45 
46 using namespace clang;
47 
48 namespace {
49 
50   /// RAII object that enables printing of the ARC __strong lifetime
51   /// qualifier.
52   class IncludeStrongLifetimeRAII {
53     PrintingPolicy &Policy;
54     bool Old;
55 
56   public:
57     explicit IncludeStrongLifetimeRAII(PrintingPolicy &Policy)
58         : Policy(Policy), Old(Policy.SuppressStrongLifetime) {
59         if (!Policy.SuppressLifetimeQualifiers)
60           Policy.SuppressStrongLifetime = false;
61     }
62 
63     ~IncludeStrongLifetimeRAII() {
64       Policy.SuppressStrongLifetime = Old;
65     }
66   };
67 
68   class ParamPolicyRAII {
69     PrintingPolicy &Policy;
70     bool Old;
71 
72   public:
73     explicit ParamPolicyRAII(PrintingPolicy &Policy)
74         : Policy(Policy), Old(Policy.SuppressSpecifiers) {
75       Policy.SuppressSpecifiers = false;
76     }
77 
78     ~ParamPolicyRAII() {
79       Policy.SuppressSpecifiers = Old;
80     }
81   };
82 
83   class ElaboratedTypePolicyRAII {
84     PrintingPolicy &Policy;
85     bool SuppressTagKeyword;
86     bool SuppressScope;
87 
88   public:
89     explicit ElaboratedTypePolicyRAII(PrintingPolicy &Policy) : Policy(Policy) {
90       SuppressTagKeyword = Policy.SuppressTagKeyword;
91       SuppressScope = Policy.SuppressScope;
92       Policy.SuppressTagKeyword = true;
93       Policy.SuppressScope = true;
94     }
95 
96     ~ElaboratedTypePolicyRAII() {
97       Policy.SuppressTagKeyword = SuppressTagKeyword;
98       Policy.SuppressScope = SuppressScope;
99     }
100   };
101 
102   class TypePrinter {
103     PrintingPolicy Policy;
104     unsigned Indentation;
105     bool HasEmptyPlaceHolder = false;
106     bool InsideCCAttribute = false;
107 
108   public:
109     explicit TypePrinter(const PrintingPolicy &Policy, unsigned Indentation = 0)
110         : Policy(Policy), Indentation(Indentation) {}
111 
112     void print(const Type *ty, Qualifiers qs, raw_ostream &OS,
113                StringRef PlaceHolder);
114     void print(QualType T, raw_ostream &OS, StringRef PlaceHolder);
115 
116     static bool canPrefixQualifiers(const Type *T, bool &NeedARCStrongQualifier);
117     void spaceBeforePlaceHolder(raw_ostream &OS);
118     void printTypeSpec(NamedDecl *D, raw_ostream &OS);
119     void printTemplateId(const TemplateSpecializationType *T, raw_ostream &OS,
120                          bool FullyQualify);
121 
122     void printBefore(QualType T, raw_ostream &OS);
123     void printAfter(QualType T, raw_ostream &OS);
124     void AppendScope(DeclContext *DC, raw_ostream &OS,
125                      DeclarationName NameInScope);
126     void printTag(TagDecl *T, raw_ostream &OS);
127     void printFunctionAfter(const FunctionType::ExtInfo &Info, raw_ostream &OS);
128 #define ABSTRACT_TYPE(CLASS, PARENT)
129 #define TYPE(CLASS, PARENT) \
130     void print##CLASS##Before(const CLASS##Type *T, raw_ostream &OS); \
131     void print##CLASS##After(const CLASS##Type *T, raw_ostream &OS);
132 #include "clang/AST/TypeNodes.inc"
133 
134   private:
135     void printBefore(const Type *ty, Qualifiers qs, raw_ostream &OS);
136     void printAfter(const Type *ty, Qualifiers qs, raw_ostream &OS);
137   };
138 
139 } // namespace
140 
141 static void AppendTypeQualList(raw_ostream &OS, unsigned TypeQuals,
142                                bool HasRestrictKeyword) {
143   bool appendSpace = false;
144   if (TypeQuals & Qualifiers::Const) {
145     OS << "const";
146     appendSpace = true;
147   }
148   if (TypeQuals & Qualifiers::Volatile) {
149     if (appendSpace) OS << ' ';
150     OS << "volatile";
151     appendSpace = true;
152   }
153   if (TypeQuals & Qualifiers::Restrict) {
154     if (appendSpace) OS << ' ';
155     if (HasRestrictKeyword) {
156       OS << "restrict";
157     } else {
158       OS << "__restrict";
159     }
160   }
161 }
162 
163 void TypePrinter::spaceBeforePlaceHolder(raw_ostream &OS) {
164   if (!HasEmptyPlaceHolder)
165     OS << ' ';
166 }
167 
168 static SplitQualType splitAccordingToPolicy(QualType QT,
169                                             const PrintingPolicy &Policy) {
170   if (Policy.PrintCanonicalTypes)
171     QT = QT.getCanonicalType();
172   return QT.split();
173 }
174 
175 void TypePrinter::print(QualType t, raw_ostream &OS, StringRef PlaceHolder) {
176   SplitQualType split = splitAccordingToPolicy(t, Policy);
177   print(split.Ty, split.Quals, OS, PlaceHolder);
178 }
179 
180 void TypePrinter::print(const Type *T, Qualifiers Quals, raw_ostream &OS,
181                         StringRef PlaceHolder) {
182   if (!T) {
183     OS << "NULL TYPE";
184     return;
185   }
186 
187   SaveAndRestore<bool> PHVal(HasEmptyPlaceHolder, PlaceHolder.empty());
188 
189   printBefore(T, Quals, OS);
190   OS << PlaceHolder;
191   printAfter(T, Quals, OS);
192 }
193 
194 bool TypePrinter::canPrefixQualifiers(const Type *T,
195                                       bool &NeedARCStrongQualifier) {
196   // CanPrefixQualifiers - We prefer to print type qualifiers before the type,
197   // so that we get "const int" instead of "int const", but we can't do this if
198   // the type is complex.  For example if the type is "int*", we *must* print
199   // "int * const", printing "const int *" is different.  Only do this when the
200   // type expands to a simple string.
201   bool CanPrefixQualifiers = false;
202   NeedARCStrongQualifier = false;
203   const Type *UnderlyingType = T;
204   if (const auto *AT = dyn_cast<AutoType>(T))
205     UnderlyingType = AT->desugar().getTypePtr();
206   if (const auto *Subst = dyn_cast<SubstTemplateTypeParmType>(T))
207     UnderlyingType = Subst->getReplacementType().getTypePtr();
208   Type::TypeClass TC = UnderlyingType->getTypeClass();
209 
210   switch (TC) {
211     case Type::Auto:
212     case Type::Builtin:
213     case Type::Complex:
214     case Type::UnresolvedUsing:
215     case Type::Using:
216     case Type::Typedef:
217     case Type::TypeOfExpr:
218     case Type::TypeOf:
219     case Type::Decltype:
220     case Type::UnaryTransform:
221     case Type::Record:
222     case Type::Enum:
223     case Type::Elaborated:
224     case Type::TemplateTypeParm:
225     case Type::SubstTemplateTypeParmPack:
226     case Type::DeducedTemplateSpecialization:
227     case Type::TemplateSpecialization:
228     case Type::InjectedClassName:
229     case Type::DependentName:
230     case Type::DependentTemplateSpecialization:
231     case Type::ObjCObject:
232     case Type::ObjCTypeParam:
233     case Type::ObjCInterface:
234     case Type::Atomic:
235     case Type::Pipe:
236     case Type::BitInt:
237     case Type::DependentBitInt:
238     case Type::BTFTagAttributed:
239       CanPrefixQualifiers = true;
240       break;
241 
242     case Type::ObjCObjectPointer:
243       CanPrefixQualifiers = T->isObjCIdType() || T->isObjCClassType() ||
244         T->isObjCQualifiedIdType() || T->isObjCQualifiedClassType();
245       break;
246 
247     case Type::VariableArray:
248     case Type::DependentSizedArray:
249       NeedARCStrongQualifier = true;
250       LLVM_FALLTHROUGH;
251 
252     case Type::ConstantArray:
253     case Type::IncompleteArray:
254       return canPrefixQualifiers(
255           cast<ArrayType>(UnderlyingType)->getElementType().getTypePtr(),
256           NeedARCStrongQualifier);
257 
258     case Type::Adjusted:
259     case Type::Decayed:
260     case Type::Pointer:
261     case Type::BlockPointer:
262     case Type::LValueReference:
263     case Type::RValueReference:
264     case Type::MemberPointer:
265     case Type::DependentAddressSpace:
266     case Type::DependentVector:
267     case Type::DependentSizedExtVector:
268     case Type::Vector:
269     case Type::ExtVector:
270     case Type::ConstantMatrix:
271     case Type::DependentSizedMatrix:
272     case Type::FunctionProto:
273     case Type::FunctionNoProto:
274     case Type::Paren:
275     case Type::PackExpansion:
276     case Type::SubstTemplateTypeParm:
277     case Type::MacroQualified:
278       CanPrefixQualifiers = false;
279       break;
280 
281     case Type::Attributed: {
282       // We still want to print the address_space before the type if it is an
283       // address_space attribute.
284       const auto *AttrTy = cast<AttributedType>(UnderlyingType);
285       CanPrefixQualifiers = AttrTy->getAttrKind() == attr::AddressSpace;
286       break;
287     }
288   }
289 
290   return CanPrefixQualifiers;
291 }
292 
293 void TypePrinter::printBefore(QualType T, raw_ostream &OS) {
294   SplitQualType Split = splitAccordingToPolicy(T, Policy);
295 
296   // If we have cv1 T, where T is substituted for cv2 U, only print cv1 - cv2
297   // at this level.
298   Qualifiers Quals = Split.Quals;
299   if (const auto *Subst = dyn_cast<SubstTemplateTypeParmType>(Split.Ty))
300     Quals -= QualType(Subst, 0).getQualifiers();
301 
302   printBefore(Split.Ty, Quals, OS);
303 }
304 
305 /// Prints the part of the type string before an identifier, e.g. for
306 /// "int foo[10]" it prints "int ".
307 void TypePrinter::printBefore(const Type *T,Qualifiers Quals, raw_ostream &OS) {
308   if (Policy.SuppressSpecifiers && T->isSpecifierType())
309     return;
310 
311   SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder);
312 
313   // Print qualifiers as appropriate.
314 
315   bool CanPrefixQualifiers = false;
316   bool NeedARCStrongQualifier = false;
317   CanPrefixQualifiers = canPrefixQualifiers(T, NeedARCStrongQualifier);
318 
319   if (CanPrefixQualifiers && !Quals.empty()) {
320     if (NeedARCStrongQualifier) {
321       IncludeStrongLifetimeRAII Strong(Policy);
322       Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/true);
323     } else {
324       Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/true);
325     }
326   }
327 
328   bool hasAfterQuals = false;
329   if (!CanPrefixQualifiers && !Quals.empty()) {
330     hasAfterQuals = !Quals.isEmptyWhenPrinted(Policy);
331     if (hasAfterQuals)
332       HasEmptyPlaceHolder = false;
333   }
334 
335   switch (T->getTypeClass()) {
336 #define ABSTRACT_TYPE(CLASS, PARENT)
337 #define TYPE(CLASS, PARENT) case Type::CLASS: \
338     print##CLASS##Before(cast<CLASS##Type>(T), OS); \
339     break;
340 #include "clang/AST/TypeNodes.inc"
341   }
342 
343   if (hasAfterQuals) {
344     if (NeedARCStrongQualifier) {
345       IncludeStrongLifetimeRAII Strong(Policy);
346       Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/!PrevPHIsEmpty.get());
347     } else {
348       Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/!PrevPHIsEmpty.get());
349     }
350   }
351 }
352 
353 void TypePrinter::printAfter(QualType t, raw_ostream &OS) {
354   SplitQualType split = splitAccordingToPolicy(t, Policy);
355   printAfter(split.Ty, split.Quals, OS);
356 }
357 
358 /// Prints the part of the type string after an identifier, e.g. for
359 /// "int foo[10]" it prints "[10]".
360 void TypePrinter::printAfter(const Type *T, Qualifiers Quals, raw_ostream &OS) {
361   switch (T->getTypeClass()) {
362 #define ABSTRACT_TYPE(CLASS, PARENT)
363 #define TYPE(CLASS, PARENT) case Type::CLASS: \
364     print##CLASS##After(cast<CLASS##Type>(T), OS); \
365     break;
366 #include "clang/AST/TypeNodes.inc"
367   }
368 }
369 
370 void TypePrinter::printBuiltinBefore(const BuiltinType *T, raw_ostream &OS) {
371   OS << T->getName(Policy);
372   spaceBeforePlaceHolder(OS);
373 }
374 
375 void TypePrinter::printBuiltinAfter(const BuiltinType *T, raw_ostream &OS) {}
376 
377 void TypePrinter::printComplexBefore(const ComplexType *T, raw_ostream &OS) {
378   OS << "_Complex ";
379   printBefore(T->getElementType(), OS);
380 }
381 
382 void TypePrinter::printComplexAfter(const ComplexType *T, raw_ostream &OS) {
383   printAfter(T->getElementType(), OS);
384 }
385 
386 void TypePrinter::printPointerBefore(const PointerType *T, raw_ostream &OS) {
387   IncludeStrongLifetimeRAII Strong(Policy);
388   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
389   printBefore(T->getPointeeType(), OS);
390   // Handle things like 'int (*A)[4];' correctly.
391   // FIXME: this should include vectors, but vectors use attributes I guess.
392   if (isa<ArrayType>(T->getPointeeType()))
393     OS << '(';
394   OS << '*';
395 }
396 
397 void TypePrinter::printPointerAfter(const PointerType *T, raw_ostream &OS) {
398   IncludeStrongLifetimeRAII Strong(Policy);
399   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
400   // Handle things like 'int (*A)[4];' correctly.
401   // FIXME: this should include vectors, but vectors use attributes I guess.
402   if (isa<ArrayType>(T->getPointeeType()))
403     OS << ')';
404   printAfter(T->getPointeeType(), OS);
405 }
406 
407 void TypePrinter::printBlockPointerBefore(const BlockPointerType *T,
408                                           raw_ostream &OS) {
409   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
410   printBefore(T->getPointeeType(), OS);
411   OS << '^';
412 }
413 
414 void TypePrinter::printBlockPointerAfter(const BlockPointerType *T,
415                                           raw_ostream &OS) {
416   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
417   printAfter(T->getPointeeType(), OS);
418 }
419 
420 // When printing a reference, the referenced type might also be a reference.
421 // If so, we want to skip that before printing the inner type.
422 static QualType skipTopLevelReferences(QualType T) {
423   if (auto *Ref = T->getAs<ReferenceType>())
424     return skipTopLevelReferences(Ref->getPointeeTypeAsWritten());
425   return T;
426 }
427 
428 void TypePrinter::printLValueReferenceBefore(const LValueReferenceType *T,
429                                              raw_ostream &OS) {
430   IncludeStrongLifetimeRAII Strong(Policy);
431   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
432   QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten());
433   printBefore(Inner, OS);
434   // Handle things like 'int (&A)[4];' correctly.
435   // FIXME: this should include vectors, but vectors use attributes I guess.
436   if (isa<ArrayType>(Inner))
437     OS << '(';
438   OS << '&';
439 }
440 
441 void TypePrinter::printLValueReferenceAfter(const LValueReferenceType *T,
442                                             raw_ostream &OS) {
443   IncludeStrongLifetimeRAII Strong(Policy);
444   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
445   QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten());
446   // Handle things like 'int (&A)[4];' correctly.
447   // FIXME: this should include vectors, but vectors use attributes I guess.
448   if (isa<ArrayType>(Inner))
449     OS << ')';
450   printAfter(Inner, OS);
451 }
452 
453 void TypePrinter::printRValueReferenceBefore(const RValueReferenceType *T,
454                                              raw_ostream &OS) {
455   IncludeStrongLifetimeRAII Strong(Policy);
456   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
457   QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten());
458   printBefore(Inner, OS);
459   // Handle things like 'int (&&A)[4];' correctly.
460   // FIXME: this should include vectors, but vectors use attributes I guess.
461   if (isa<ArrayType>(Inner))
462     OS << '(';
463   OS << "&&";
464 }
465 
466 void TypePrinter::printRValueReferenceAfter(const RValueReferenceType *T,
467                                             raw_ostream &OS) {
468   IncludeStrongLifetimeRAII Strong(Policy);
469   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
470   QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten());
471   // Handle things like 'int (&&A)[4];' correctly.
472   // FIXME: this should include vectors, but vectors use attributes I guess.
473   if (isa<ArrayType>(Inner))
474     OS << ')';
475   printAfter(Inner, OS);
476 }
477 
478 void TypePrinter::printMemberPointerBefore(const MemberPointerType *T,
479                                            raw_ostream &OS) {
480   IncludeStrongLifetimeRAII Strong(Policy);
481   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
482   printBefore(T->getPointeeType(), OS);
483   // Handle things like 'int (Cls::*A)[4];' correctly.
484   // FIXME: this should include vectors, but vectors use attributes I guess.
485   if (isa<ArrayType>(T->getPointeeType()))
486     OS << '(';
487 
488   PrintingPolicy InnerPolicy(Policy);
489   InnerPolicy.IncludeTagDefinition = false;
490   TypePrinter(InnerPolicy).print(QualType(T->getClass(), 0), OS, StringRef());
491 
492   OS << "::*";
493 }
494 
495 void TypePrinter::printMemberPointerAfter(const MemberPointerType *T,
496                                           raw_ostream &OS) {
497   IncludeStrongLifetimeRAII Strong(Policy);
498   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
499   // Handle things like 'int (Cls::*A)[4];' correctly.
500   // FIXME: this should include vectors, but vectors use attributes I guess.
501   if (isa<ArrayType>(T->getPointeeType()))
502     OS << ')';
503   printAfter(T->getPointeeType(), OS);
504 }
505 
506 void TypePrinter::printConstantArrayBefore(const ConstantArrayType *T,
507                                            raw_ostream &OS) {
508   IncludeStrongLifetimeRAII Strong(Policy);
509   printBefore(T->getElementType(), OS);
510 }
511 
512 void TypePrinter::printConstantArrayAfter(const ConstantArrayType *T,
513                                           raw_ostream &OS) {
514   OS << '[';
515   if (T->getIndexTypeQualifiers().hasQualifiers()) {
516     AppendTypeQualList(OS, T->getIndexTypeCVRQualifiers(),
517                        Policy.Restrict);
518     OS << ' ';
519   }
520 
521   if (T->getSizeModifier() == ArrayType::Static)
522     OS << "static ";
523 
524   OS << T->getSize().getZExtValue() << ']';
525   printAfter(T->getElementType(), OS);
526 }
527 
528 void TypePrinter::printIncompleteArrayBefore(const IncompleteArrayType *T,
529                                              raw_ostream &OS) {
530   IncludeStrongLifetimeRAII Strong(Policy);
531   printBefore(T->getElementType(), OS);
532 }
533 
534 void TypePrinter::printIncompleteArrayAfter(const IncompleteArrayType *T,
535                                             raw_ostream &OS) {
536   OS << "[]";
537   printAfter(T->getElementType(), OS);
538 }
539 
540 void TypePrinter::printVariableArrayBefore(const VariableArrayType *T,
541                                            raw_ostream &OS) {
542   IncludeStrongLifetimeRAII Strong(Policy);
543   printBefore(T->getElementType(), OS);
544 }
545 
546 void TypePrinter::printVariableArrayAfter(const VariableArrayType *T,
547                                           raw_ostream &OS) {
548   OS << '[';
549   if (T->getIndexTypeQualifiers().hasQualifiers()) {
550     AppendTypeQualList(OS, T->getIndexTypeCVRQualifiers(), Policy.Restrict);
551     OS << ' ';
552   }
553 
554   if (T->getSizeModifier() == VariableArrayType::Static)
555     OS << "static ";
556   else if (T->getSizeModifier() == VariableArrayType::Star)
557     OS << '*';
558 
559   if (T->getSizeExpr())
560     T->getSizeExpr()->printPretty(OS, nullptr, Policy);
561   OS << ']';
562 
563   printAfter(T->getElementType(), OS);
564 }
565 
566 void TypePrinter::printAdjustedBefore(const AdjustedType *T, raw_ostream &OS) {
567   // Print the adjusted representation, otherwise the adjustment will be
568   // invisible.
569   printBefore(T->getAdjustedType(), OS);
570 }
571 
572 void TypePrinter::printAdjustedAfter(const AdjustedType *T, raw_ostream &OS) {
573   printAfter(T->getAdjustedType(), OS);
574 }
575 
576 void TypePrinter::printDecayedBefore(const DecayedType *T, raw_ostream &OS) {
577   // Print as though it's a pointer.
578   printAdjustedBefore(T, OS);
579 }
580 
581 void TypePrinter::printDecayedAfter(const DecayedType *T, raw_ostream &OS) {
582   printAdjustedAfter(T, OS);
583 }
584 
585 void TypePrinter::printDependentSizedArrayBefore(
586                                                const DependentSizedArrayType *T,
587                                                raw_ostream &OS) {
588   IncludeStrongLifetimeRAII Strong(Policy);
589   printBefore(T->getElementType(), OS);
590 }
591 
592 void TypePrinter::printDependentSizedArrayAfter(
593                                                const DependentSizedArrayType *T,
594                                                raw_ostream &OS) {
595   OS << '[';
596   if (T->getSizeExpr())
597     T->getSizeExpr()->printPretty(OS, nullptr, Policy);
598   OS << ']';
599   printAfter(T->getElementType(), OS);
600 }
601 
602 void TypePrinter::printDependentAddressSpaceBefore(
603     const DependentAddressSpaceType *T, raw_ostream &OS) {
604   printBefore(T->getPointeeType(), OS);
605 }
606 
607 void TypePrinter::printDependentAddressSpaceAfter(
608     const DependentAddressSpaceType *T, raw_ostream &OS) {
609   OS << " __attribute__((address_space(";
610   if (T->getAddrSpaceExpr())
611     T->getAddrSpaceExpr()->printPretty(OS, nullptr, Policy);
612   OS << ")))";
613   printAfter(T->getPointeeType(), OS);
614 }
615 
616 void TypePrinter::printDependentSizedExtVectorBefore(
617                                           const DependentSizedExtVectorType *T,
618                                           raw_ostream &OS) {
619   printBefore(T->getElementType(), OS);
620 }
621 
622 void TypePrinter::printDependentSizedExtVectorAfter(
623                                           const DependentSizedExtVectorType *T,
624                                           raw_ostream &OS) {
625   OS << " __attribute__((ext_vector_type(";
626   if (T->getSizeExpr())
627     T->getSizeExpr()->printPretty(OS, nullptr, Policy);
628   OS << ")))";
629   printAfter(T->getElementType(), OS);
630 }
631 
632 void TypePrinter::printVectorBefore(const VectorType *T, raw_ostream &OS) {
633   switch (T->getVectorKind()) {
634   case VectorType::AltiVecPixel:
635     OS << "__vector __pixel ";
636     break;
637   case VectorType::AltiVecBool:
638     OS << "__vector __bool ";
639     printBefore(T->getElementType(), OS);
640     break;
641   case VectorType::AltiVecVector:
642     OS << "__vector ";
643     printBefore(T->getElementType(), OS);
644     break;
645   case VectorType::NeonVector:
646     OS << "__attribute__((neon_vector_type("
647        << T->getNumElements() << "))) ";
648     printBefore(T->getElementType(), OS);
649     break;
650   case VectorType::NeonPolyVector:
651     OS << "__attribute__((neon_polyvector_type(" <<
652           T->getNumElements() << "))) ";
653     printBefore(T->getElementType(), OS);
654     break;
655   case VectorType::GenericVector: {
656     // FIXME: We prefer to print the size directly here, but have no way
657     // to get the size of the type.
658     OS << "__attribute__((__vector_size__("
659        << T->getNumElements()
660        << " * sizeof(";
661     print(T->getElementType(), OS, StringRef());
662     OS << ")))) ";
663     printBefore(T->getElementType(), OS);
664     break;
665   }
666   case VectorType::SveFixedLengthDataVector:
667   case VectorType::SveFixedLengthPredicateVector:
668     // FIXME: We prefer to print the size directly here, but have no way
669     // to get the size of the type.
670     OS << "__attribute__((__arm_sve_vector_bits__(";
671 
672     if (T->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
673       // Predicates take a bit per byte of the vector size, multiply by 8 to
674       // get the number of bits passed to the attribute.
675       OS << T->getNumElements() * 8;
676     else
677       OS << T->getNumElements();
678 
679     OS << " * sizeof(";
680     print(T->getElementType(), OS, StringRef());
681     // Multiply by 8 for the number of bits.
682     OS << ") * 8))) ";
683     printBefore(T->getElementType(), OS);
684   }
685 }
686 
687 void TypePrinter::printVectorAfter(const VectorType *T, raw_ostream &OS) {
688   printAfter(T->getElementType(), OS);
689 }
690 
691 void TypePrinter::printDependentVectorBefore(
692     const DependentVectorType *T, raw_ostream &OS) {
693   switch (T->getVectorKind()) {
694   case VectorType::AltiVecPixel:
695     OS << "__vector __pixel ";
696     break;
697   case VectorType::AltiVecBool:
698     OS << "__vector __bool ";
699     printBefore(T->getElementType(), OS);
700     break;
701   case VectorType::AltiVecVector:
702     OS << "__vector ";
703     printBefore(T->getElementType(), OS);
704     break;
705   case VectorType::NeonVector:
706     OS << "__attribute__((neon_vector_type(";
707     if (T->getSizeExpr())
708       T->getSizeExpr()->printPretty(OS, nullptr, Policy);
709     OS << "))) ";
710     printBefore(T->getElementType(), OS);
711     break;
712   case VectorType::NeonPolyVector:
713     OS << "__attribute__((neon_polyvector_type(";
714     if (T->getSizeExpr())
715       T->getSizeExpr()->printPretty(OS, nullptr, Policy);
716     OS << "))) ";
717     printBefore(T->getElementType(), OS);
718     break;
719   case VectorType::GenericVector: {
720     // FIXME: We prefer to print the size directly here, but have no way
721     // to get the size of the type.
722     OS << "__attribute__((__vector_size__(";
723     if (T->getSizeExpr())
724       T->getSizeExpr()->printPretty(OS, nullptr, Policy);
725     OS << " * sizeof(";
726     print(T->getElementType(), OS, StringRef());
727     OS << ")))) ";
728     printBefore(T->getElementType(), OS);
729     break;
730   }
731   case VectorType::SveFixedLengthDataVector:
732   case VectorType::SveFixedLengthPredicateVector:
733     // FIXME: We prefer to print the size directly here, but have no way
734     // to get the size of the type.
735     OS << "__attribute__((__arm_sve_vector_bits__(";
736     if (T->getSizeExpr()) {
737       T->getSizeExpr()->printPretty(OS, nullptr, Policy);
738       if (T->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
739         // Predicates take a bit per byte of the vector size, multiply by 8 to
740         // get the number of bits passed to the attribute.
741         OS << " * 8";
742       OS << " * sizeof(";
743       print(T->getElementType(), OS, StringRef());
744       // Multiply by 8 for the number of bits.
745       OS << ") * 8";
746     }
747     OS << "))) ";
748     printBefore(T->getElementType(), OS);
749   }
750 }
751 
752 void TypePrinter::printDependentVectorAfter(
753     const DependentVectorType *T, raw_ostream &OS) {
754   printAfter(T->getElementType(), OS);
755 }
756 
757 void TypePrinter::printExtVectorBefore(const ExtVectorType *T,
758                                        raw_ostream &OS) {
759   printBefore(T->getElementType(), OS);
760 }
761 
762 void TypePrinter::printExtVectorAfter(const ExtVectorType *T, raw_ostream &OS) {
763   printAfter(T->getElementType(), OS);
764   OS << " __attribute__((ext_vector_type(";
765   OS << T->getNumElements();
766   OS << ")))";
767 }
768 
769 void TypePrinter::printConstantMatrixBefore(const ConstantMatrixType *T,
770                                             raw_ostream &OS) {
771   printBefore(T->getElementType(), OS);
772   OS << " __attribute__((matrix_type(";
773   OS << T->getNumRows() << ", " << T->getNumColumns();
774   OS << ")))";
775 }
776 
777 void TypePrinter::printConstantMatrixAfter(const ConstantMatrixType *T,
778                                            raw_ostream &OS) {
779   printAfter(T->getElementType(), OS);
780 }
781 
782 void TypePrinter::printDependentSizedMatrixBefore(
783     const DependentSizedMatrixType *T, raw_ostream &OS) {
784   printBefore(T->getElementType(), OS);
785   OS << " __attribute__((matrix_type(";
786   if (T->getRowExpr()) {
787     T->getRowExpr()->printPretty(OS, nullptr, Policy);
788   }
789   OS << ", ";
790   if (T->getColumnExpr()) {
791     T->getColumnExpr()->printPretty(OS, nullptr, Policy);
792   }
793   OS << ")))";
794 }
795 
796 void TypePrinter::printDependentSizedMatrixAfter(
797     const DependentSizedMatrixType *T, raw_ostream &OS) {
798   printAfter(T->getElementType(), OS);
799 }
800 
801 void
802 FunctionProtoType::printExceptionSpecification(raw_ostream &OS,
803                                                const PrintingPolicy &Policy)
804                                                                          const {
805   if (hasDynamicExceptionSpec()) {
806     OS << " throw(";
807     if (getExceptionSpecType() == EST_MSAny)
808       OS << "...";
809     else
810       for (unsigned I = 0, N = getNumExceptions(); I != N; ++I) {
811         if (I)
812           OS << ", ";
813 
814         OS << getExceptionType(I).stream(Policy);
815       }
816     OS << ')';
817   } else if (EST_NoThrow == getExceptionSpecType()) {
818     OS << " __attribute__((nothrow))";
819   } else if (isNoexceptExceptionSpec(getExceptionSpecType())) {
820     OS << " noexcept";
821     // FIXME:Is it useful to print out the expression for a non-dependent
822     // noexcept specification?
823     if (isComputedNoexcept(getExceptionSpecType())) {
824       OS << '(';
825       if (getNoexceptExpr())
826         getNoexceptExpr()->printPretty(OS, nullptr, Policy);
827       OS << ')';
828     }
829   }
830 }
831 
832 void TypePrinter::printFunctionProtoBefore(const FunctionProtoType *T,
833                                            raw_ostream &OS) {
834   if (T->hasTrailingReturn()) {
835     OS << "auto ";
836     if (!HasEmptyPlaceHolder)
837       OS << '(';
838   } else {
839     // If needed for precedence reasons, wrap the inner part in grouping parens.
840     SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder, false);
841     printBefore(T->getReturnType(), OS);
842     if (!PrevPHIsEmpty.get())
843       OS << '(';
844   }
845 }
846 
847 StringRef clang::getParameterABISpelling(ParameterABI ABI) {
848   switch (ABI) {
849   case ParameterABI::Ordinary:
850     llvm_unreachable("asking for spelling of ordinary parameter ABI");
851   case ParameterABI::SwiftContext:
852     return "swift_context";
853   case ParameterABI::SwiftAsyncContext:
854     return "swift_async_context";
855   case ParameterABI::SwiftErrorResult:
856     return "swift_error_result";
857   case ParameterABI::SwiftIndirectResult:
858     return "swift_indirect_result";
859   }
860   llvm_unreachable("bad parameter ABI kind");
861 }
862 
863 void TypePrinter::printFunctionProtoAfter(const FunctionProtoType *T,
864                                           raw_ostream &OS) {
865   // If needed for precedence reasons, wrap the inner part in grouping parens.
866   if (!HasEmptyPlaceHolder)
867     OS << ')';
868   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
869 
870   OS << '(';
871   {
872     ParamPolicyRAII ParamPolicy(Policy);
873     for (unsigned i = 0, e = T->getNumParams(); i != e; ++i) {
874       if (i) OS << ", ";
875 
876       auto EPI = T->getExtParameterInfo(i);
877       if (EPI.isConsumed()) OS << "__attribute__((ns_consumed)) ";
878       if (EPI.isNoEscape())
879         OS << "__attribute__((noescape)) ";
880       auto ABI = EPI.getABI();
881       if (ABI != ParameterABI::Ordinary)
882         OS << "__attribute__((" << getParameterABISpelling(ABI) << ")) ";
883 
884       print(T->getParamType(i), OS, StringRef());
885     }
886   }
887 
888   if (T->isVariadic()) {
889     if (T->getNumParams())
890       OS << ", ";
891     OS << "...";
892   } else if (T->getNumParams() == 0 && Policy.UseVoidForZeroParams) {
893     // Do not emit int() if we have a proto, emit 'int(void)'.
894     OS << "void";
895   }
896 
897   OS << ')';
898 
899   FunctionType::ExtInfo Info = T->getExtInfo();
900 
901   printFunctionAfter(Info, OS);
902 
903   if (!T->getMethodQuals().empty())
904     OS << " " << T->getMethodQuals().getAsString();
905 
906   switch (T->getRefQualifier()) {
907   case RQ_None:
908     break;
909 
910   case RQ_LValue:
911     OS << " &";
912     break;
913 
914   case RQ_RValue:
915     OS << " &&";
916     break;
917   }
918   T->printExceptionSpecification(OS, Policy);
919 
920   if (T->hasTrailingReturn()) {
921     OS << " -> ";
922     print(T->getReturnType(), OS, StringRef());
923   } else
924     printAfter(T->getReturnType(), OS);
925 }
926 
927 void TypePrinter::printFunctionAfter(const FunctionType::ExtInfo &Info,
928                                      raw_ostream &OS) {
929   if (!InsideCCAttribute) {
930     switch (Info.getCC()) {
931     case CC_C:
932       // The C calling convention is the default on the vast majority of platforms
933       // we support.  If the user wrote it explicitly, it will usually be printed
934       // while traversing the AttributedType.  If the type has been desugared, let
935       // the canonical spelling be the implicit calling convention.
936       // FIXME: It would be better to be explicit in certain contexts, such as a
937       // cdecl function typedef used to declare a member function with the
938       // Microsoft C++ ABI.
939       break;
940     case CC_X86StdCall:
941       OS << " __attribute__((stdcall))";
942       break;
943     case CC_X86FastCall:
944       OS << " __attribute__((fastcall))";
945       break;
946     case CC_X86ThisCall:
947       OS << " __attribute__((thiscall))";
948       break;
949     case CC_X86VectorCall:
950       OS << " __attribute__((vectorcall))";
951       break;
952     case CC_X86Pascal:
953       OS << " __attribute__((pascal))";
954       break;
955     case CC_AAPCS:
956       OS << " __attribute__((pcs(\"aapcs\")))";
957       break;
958     case CC_AAPCS_VFP:
959       OS << " __attribute__((pcs(\"aapcs-vfp\")))";
960       break;
961     case CC_AArch64VectorCall:
962       OS << "__attribute__((aarch64_vector_pcs))";
963       break;
964     case CC_AArch64SVEPCS:
965       OS << "__attribute__((aarch64_sve_pcs))";
966       break;
967     case CC_IntelOclBicc:
968       OS << " __attribute__((intel_ocl_bicc))";
969       break;
970     case CC_Win64:
971       OS << " __attribute__((ms_abi))";
972       break;
973     case CC_X86_64SysV:
974       OS << " __attribute__((sysv_abi))";
975       break;
976     case CC_X86RegCall:
977       OS << " __attribute__((regcall))";
978       break;
979     case CC_SpirFunction:
980     case CC_OpenCLKernel:
981       // Do nothing. These CCs are not available as attributes.
982       break;
983     case CC_Swift:
984       OS << " __attribute__((swiftcall))";
985       break;
986     case CC_SwiftAsync:
987       OS << "__attribute__((swiftasynccall))";
988       break;
989     case CC_PreserveMost:
990       OS << " __attribute__((preserve_most))";
991       break;
992     case CC_PreserveAll:
993       OS << " __attribute__((preserve_all))";
994       break;
995     }
996   }
997 
998   if (Info.getNoReturn())
999     OS << " __attribute__((noreturn))";
1000   if (Info.getCmseNSCall())
1001     OS << " __attribute__((cmse_nonsecure_call))";
1002   if (Info.getProducesResult())
1003     OS << " __attribute__((ns_returns_retained))";
1004   if (Info.getRegParm())
1005     OS << " __attribute__((regparm ("
1006        << Info.getRegParm() << ")))";
1007   if (Info.getNoCallerSavedRegs())
1008     OS << " __attribute__((no_caller_saved_registers))";
1009   if (Info.getNoCfCheck())
1010     OS << " __attribute__((nocf_check))";
1011 }
1012 
1013 void TypePrinter::printFunctionNoProtoBefore(const FunctionNoProtoType *T,
1014                                              raw_ostream &OS) {
1015   // If needed for precedence reasons, wrap the inner part in grouping parens.
1016   SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder, false);
1017   printBefore(T->getReturnType(), OS);
1018   if (!PrevPHIsEmpty.get())
1019     OS << '(';
1020 }
1021 
1022 void TypePrinter::printFunctionNoProtoAfter(const FunctionNoProtoType *T,
1023                                             raw_ostream &OS) {
1024   // If needed for precedence reasons, wrap the inner part in grouping parens.
1025   if (!HasEmptyPlaceHolder)
1026     OS << ')';
1027   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
1028 
1029   OS << "()";
1030   printFunctionAfter(T->getExtInfo(), OS);
1031   printAfter(T->getReturnType(), OS);
1032 }
1033 
1034 void TypePrinter::printTypeSpec(NamedDecl *D, raw_ostream &OS) {
1035 
1036   // Compute the full nested-name-specifier for this type.
1037   // In C, this will always be empty except when the type
1038   // being printed is anonymous within other Record.
1039   if (!Policy.SuppressScope)
1040     AppendScope(D->getDeclContext(), OS, D->getDeclName());
1041 
1042   IdentifierInfo *II = D->getIdentifier();
1043   OS << II->getName();
1044   spaceBeforePlaceHolder(OS);
1045 }
1046 
1047 void TypePrinter::printUnresolvedUsingBefore(const UnresolvedUsingType *T,
1048                                              raw_ostream &OS) {
1049   printTypeSpec(T->getDecl(), OS);
1050 }
1051 
1052 void TypePrinter::printUnresolvedUsingAfter(const UnresolvedUsingType *T,
1053                                             raw_ostream &OS) {}
1054 
1055 void TypePrinter::printUsingBefore(const UsingType *T, raw_ostream &OS) {
1056   // After `namespace b { using a::X }`, is the type X within B a::X or b::X?
1057   //
1058   // - b::X is more formally correct given the UsingType model
1059   // - b::X makes sense if "re-exporting" a symbol in a new namespace
1060   // - a::X makes sense if "importing" a symbol for convenience
1061   //
1062   // The "importing" use seems much more common, so we print a::X.
1063   // This could be a policy option, but the right choice seems to rest more
1064   // with the intent of the code than the caller.
1065   printTypeSpec(T->getFoundDecl()->getUnderlyingDecl(), OS);
1066 }
1067 
1068 void TypePrinter::printUsingAfter(const UsingType *T, raw_ostream &OS) {}
1069 
1070 void TypePrinter::printTypedefBefore(const TypedefType *T, raw_ostream &OS) {
1071   printTypeSpec(T->getDecl(), OS);
1072 }
1073 
1074 void TypePrinter::printMacroQualifiedBefore(const MacroQualifiedType *T,
1075                                             raw_ostream &OS) {
1076   StringRef MacroName = T->getMacroIdentifier()->getName();
1077   OS << MacroName << " ";
1078 
1079   // Since this type is meant to print the macro instead of the whole attribute,
1080   // we trim any attributes and go directly to the original modified type.
1081   printBefore(T->getModifiedType(), OS);
1082 }
1083 
1084 void TypePrinter::printMacroQualifiedAfter(const MacroQualifiedType *T,
1085                                            raw_ostream &OS) {
1086   printAfter(T->getModifiedType(), OS);
1087 }
1088 
1089 void TypePrinter::printTypedefAfter(const TypedefType *T, raw_ostream &OS) {}
1090 
1091 void TypePrinter::printTypeOfExprBefore(const TypeOfExprType *T,
1092                                         raw_ostream &OS) {
1093   OS << "typeof ";
1094   if (T->getUnderlyingExpr())
1095     T->getUnderlyingExpr()->printPretty(OS, nullptr, Policy);
1096   spaceBeforePlaceHolder(OS);
1097 }
1098 
1099 void TypePrinter::printTypeOfExprAfter(const TypeOfExprType *T,
1100                                        raw_ostream &OS) {}
1101 
1102 void TypePrinter::printTypeOfBefore(const TypeOfType *T, raw_ostream &OS) {
1103   OS << "typeof(";
1104   print(T->getUnderlyingType(), OS, StringRef());
1105   OS << ')';
1106   spaceBeforePlaceHolder(OS);
1107 }
1108 
1109 void TypePrinter::printTypeOfAfter(const TypeOfType *T, raw_ostream &OS) {}
1110 
1111 void TypePrinter::printDecltypeBefore(const DecltypeType *T, raw_ostream &OS) {
1112   OS << "decltype(";
1113   if (T->getUnderlyingExpr())
1114     T->getUnderlyingExpr()->printPretty(OS, nullptr, Policy);
1115   OS << ')';
1116   spaceBeforePlaceHolder(OS);
1117 }
1118 
1119 void TypePrinter::printDecltypeAfter(const DecltypeType *T, raw_ostream &OS) {}
1120 
1121 void TypePrinter::printUnaryTransformBefore(const UnaryTransformType *T,
1122                                             raw_ostream &OS) {
1123   IncludeStrongLifetimeRAII Strong(Policy);
1124 
1125   switch (T->getUTTKind()) {
1126     case UnaryTransformType::EnumUnderlyingType:
1127       OS << "__underlying_type(";
1128       print(T->getBaseType(), OS, StringRef());
1129       OS << ')';
1130       spaceBeforePlaceHolder(OS);
1131       return;
1132   }
1133 
1134   printBefore(T->getBaseType(), OS);
1135 }
1136 
1137 void TypePrinter::printUnaryTransformAfter(const UnaryTransformType *T,
1138                                            raw_ostream &OS) {
1139   IncludeStrongLifetimeRAII Strong(Policy);
1140 
1141   switch (T->getUTTKind()) {
1142     case UnaryTransformType::EnumUnderlyingType:
1143       return;
1144   }
1145 
1146   printAfter(T->getBaseType(), OS);
1147 }
1148 
1149 void TypePrinter::printAutoBefore(const AutoType *T, raw_ostream &OS) {
1150   // If the type has been deduced, do not print 'auto'.
1151   if (!T->getDeducedType().isNull()) {
1152     printBefore(T->getDeducedType(), OS);
1153   } else {
1154     if (T->isConstrained()) {
1155       // FIXME: Track a TypeConstraint as type sugar, so that we can print the
1156       // type as it was written.
1157       T->getTypeConstraintConcept()->getDeclName().print(OS, Policy);
1158       auto Args = T->getTypeConstraintArguments();
1159       if (!Args.empty())
1160         printTemplateArgumentList(
1161             OS, Args, Policy,
1162             T->getTypeConstraintConcept()->getTemplateParameters());
1163       OS << ' ';
1164     }
1165     switch (T->getKeyword()) {
1166     case AutoTypeKeyword::Auto: OS << "auto"; break;
1167     case AutoTypeKeyword::DecltypeAuto: OS << "decltype(auto)"; break;
1168     case AutoTypeKeyword::GNUAutoType: OS << "__auto_type"; break;
1169     }
1170     spaceBeforePlaceHolder(OS);
1171   }
1172 }
1173 
1174 void TypePrinter::printAutoAfter(const AutoType *T, raw_ostream &OS) {
1175   // If the type has been deduced, do not print 'auto'.
1176   if (!T->getDeducedType().isNull())
1177     printAfter(T->getDeducedType(), OS);
1178 }
1179 
1180 void TypePrinter::printDeducedTemplateSpecializationBefore(
1181     const DeducedTemplateSpecializationType *T, raw_ostream &OS) {
1182   // If the type has been deduced, print the deduced type.
1183   if (!T->getDeducedType().isNull()) {
1184     printBefore(T->getDeducedType(), OS);
1185   } else {
1186     IncludeStrongLifetimeRAII Strong(Policy);
1187     T->getTemplateName().print(OS, Policy);
1188     spaceBeforePlaceHolder(OS);
1189   }
1190 }
1191 
1192 void TypePrinter::printDeducedTemplateSpecializationAfter(
1193     const DeducedTemplateSpecializationType *T, raw_ostream &OS) {
1194   // If the type has been deduced, print the deduced type.
1195   if (!T->getDeducedType().isNull())
1196     printAfter(T->getDeducedType(), OS);
1197 }
1198 
1199 void TypePrinter::printAtomicBefore(const AtomicType *T, raw_ostream &OS) {
1200   IncludeStrongLifetimeRAII Strong(Policy);
1201 
1202   OS << "_Atomic(";
1203   print(T->getValueType(), OS, StringRef());
1204   OS << ')';
1205   spaceBeforePlaceHolder(OS);
1206 }
1207 
1208 void TypePrinter::printAtomicAfter(const AtomicType *T, raw_ostream &OS) {}
1209 
1210 void TypePrinter::printPipeBefore(const PipeType *T, raw_ostream &OS) {
1211   IncludeStrongLifetimeRAII Strong(Policy);
1212 
1213   if (T->isReadOnly())
1214     OS << "read_only ";
1215   else
1216     OS << "write_only ";
1217   OS << "pipe ";
1218   print(T->getElementType(), OS, StringRef());
1219   spaceBeforePlaceHolder(OS);
1220 }
1221 
1222 void TypePrinter::printPipeAfter(const PipeType *T, raw_ostream &OS) {}
1223 
1224 void TypePrinter::printBitIntBefore(const BitIntType *T, raw_ostream &OS) {
1225   if (T->isUnsigned())
1226     OS << "unsigned ";
1227   OS << "_BitInt(" << T->getNumBits() << ")";
1228   spaceBeforePlaceHolder(OS);
1229 }
1230 
1231 void TypePrinter::printBitIntAfter(const BitIntType *T, raw_ostream &OS) {}
1232 
1233 void TypePrinter::printDependentBitIntBefore(const DependentBitIntType *T,
1234                                              raw_ostream &OS) {
1235   if (T->isUnsigned())
1236     OS << "unsigned ";
1237   OS << "_BitInt(";
1238   T->getNumBitsExpr()->printPretty(OS, nullptr, Policy);
1239   OS << ")";
1240   spaceBeforePlaceHolder(OS);
1241 }
1242 
1243 void TypePrinter::printDependentBitIntAfter(const DependentBitIntType *T,
1244                                             raw_ostream &OS) {}
1245 
1246 /// Appends the given scope to the end of a string.
1247 void TypePrinter::AppendScope(DeclContext *DC, raw_ostream &OS,
1248                               DeclarationName NameInScope) {
1249   if (DC->isTranslationUnit())
1250     return;
1251 
1252   // FIXME: Consider replacing this with NamedDecl::printNestedNameSpecifier,
1253   // which can also print names for function and method scopes.
1254   if (DC->isFunctionOrMethod())
1255     return;
1256 
1257   if (Policy.Callbacks && Policy.Callbacks->isScopeVisible(DC))
1258     return;
1259 
1260   if (const auto *NS = dyn_cast<NamespaceDecl>(DC)) {
1261     if (Policy.SuppressUnwrittenScope && NS->isAnonymousNamespace())
1262       return AppendScope(DC->getParent(), OS, NameInScope);
1263 
1264     // Only suppress an inline namespace if the name has the same lookup
1265     // results in the enclosing namespace.
1266     if (Policy.SuppressInlineNamespace && NS->isInline() && NameInScope &&
1267         NS->isRedundantInlineQualifierFor(NameInScope))
1268       return AppendScope(DC->getParent(), OS, NameInScope);
1269 
1270     AppendScope(DC->getParent(), OS, NS->getDeclName());
1271     if (NS->getIdentifier())
1272       OS << NS->getName() << "::";
1273     else
1274       OS << "(anonymous namespace)::";
1275   } else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
1276     AppendScope(DC->getParent(), OS, Spec->getDeclName());
1277     IncludeStrongLifetimeRAII Strong(Policy);
1278     OS << Spec->getIdentifier()->getName();
1279     const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1280     printTemplateArgumentList(
1281         OS, TemplateArgs.asArray(), Policy,
1282         Spec->getSpecializedTemplate()->getTemplateParameters());
1283     OS << "::";
1284   } else if (const auto *Tag = dyn_cast<TagDecl>(DC)) {
1285     AppendScope(DC->getParent(), OS, Tag->getDeclName());
1286     if (TypedefNameDecl *Typedef = Tag->getTypedefNameForAnonDecl())
1287       OS << Typedef->getIdentifier()->getName() << "::";
1288     else if (Tag->getIdentifier())
1289       OS << Tag->getIdentifier()->getName() << "::";
1290     else
1291       return;
1292   } else {
1293     AppendScope(DC->getParent(), OS, NameInScope);
1294   }
1295 }
1296 
1297 void TypePrinter::printTag(TagDecl *D, raw_ostream &OS) {
1298   if (Policy.IncludeTagDefinition) {
1299     PrintingPolicy SubPolicy = Policy;
1300     SubPolicy.IncludeTagDefinition = false;
1301     D->print(OS, SubPolicy, Indentation);
1302     spaceBeforePlaceHolder(OS);
1303     return;
1304   }
1305 
1306   bool HasKindDecoration = false;
1307 
1308   // We don't print tags unless this is an elaborated type.
1309   // In C, we just assume every RecordType is an elaborated type.
1310   if (!Policy.SuppressTagKeyword && !D->getTypedefNameForAnonDecl()) {
1311     HasKindDecoration = true;
1312     OS << D->getKindName();
1313     OS << ' ';
1314   }
1315 
1316   // Compute the full nested-name-specifier for this type.
1317   // In C, this will always be empty except when the type
1318   // being printed is anonymous within other Record.
1319   if (!Policy.SuppressScope)
1320     AppendScope(D->getDeclContext(), OS, D->getDeclName());
1321 
1322   if (const IdentifierInfo *II = D->getIdentifier())
1323     OS << II->getName();
1324   else if (TypedefNameDecl *Typedef = D->getTypedefNameForAnonDecl()) {
1325     assert(Typedef->getIdentifier() && "Typedef without identifier?");
1326     OS << Typedef->getIdentifier()->getName();
1327   } else {
1328     // Make an unambiguous representation for anonymous types, e.g.
1329     //   (anonymous enum at /usr/include/string.h:120:9)
1330     OS << (Policy.MSVCFormatting ? '`' : '(');
1331 
1332     if (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda()) {
1333       OS << "lambda";
1334       HasKindDecoration = true;
1335     } else if ((isa<RecordDecl>(D) && cast<RecordDecl>(D)->isAnonymousStructOrUnion())) {
1336       OS << "anonymous";
1337     } else {
1338       OS << "unnamed";
1339     }
1340 
1341     if (Policy.AnonymousTagLocations) {
1342       // Suppress the redundant tag keyword if we just printed one.
1343       // We don't have to worry about ElaboratedTypes here because you can't
1344       // refer to an anonymous type with one.
1345       if (!HasKindDecoration)
1346         OS << " " << D->getKindName();
1347 
1348       PresumedLoc PLoc = D->getASTContext().getSourceManager().getPresumedLoc(
1349           D->getLocation());
1350       if (PLoc.isValid()) {
1351         OS << " at ";
1352         StringRef File = PLoc.getFilename();
1353         if (auto *Callbacks = Policy.Callbacks)
1354           OS << Callbacks->remapPath(File);
1355         else
1356           OS << File;
1357         OS << ':' << PLoc.getLine() << ':' << PLoc.getColumn();
1358       }
1359     }
1360 
1361     OS << (Policy.MSVCFormatting ? '\'' : ')');
1362   }
1363 
1364   // If this is a class template specialization, print the template
1365   // arguments.
1366   if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
1367     ArrayRef<TemplateArgument> Args;
1368     TypeSourceInfo *TAW = Spec->getTypeAsWritten();
1369     if (!Policy.PrintCanonicalTypes && TAW) {
1370       const TemplateSpecializationType *TST =
1371         cast<TemplateSpecializationType>(TAW->getType());
1372       Args = TST->template_arguments();
1373     } else {
1374       const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1375       Args = TemplateArgs.asArray();
1376     }
1377     IncludeStrongLifetimeRAII Strong(Policy);
1378     printTemplateArgumentList(
1379         OS, Args, Policy,
1380         Spec->getSpecializedTemplate()->getTemplateParameters());
1381   }
1382 
1383   spaceBeforePlaceHolder(OS);
1384 }
1385 
1386 void TypePrinter::printRecordBefore(const RecordType *T, raw_ostream &OS) {
1387   // Print the preferred name if we have one for this type.
1388   if (Policy.UsePreferredNames) {
1389     for (const auto *PNA : T->getDecl()->specific_attrs<PreferredNameAttr>()) {
1390       if (!declaresSameEntity(PNA->getTypedefType()->getAsCXXRecordDecl(),
1391                               T->getDecl()))
1392         continue;
1393       // Find the outermost typedef or alias template.
1394       QualType T = PNA->getTypedefType();
1395       while (true) {
1396         if (auto *TT = dyn_cast<TypedefType>(T))
1397           return printTypeSpec(TT->getDecl(), OS);
1398         if (auto *TST = dyn_cast<TemplateSpecializationType>(T))
1399           return printTemplateId(TST, OS, /*FullyQualify=*/true);
1400         T = T->getLocallyUnqualifiedSingleStepDesugaredType();
1401       }
1402     }
1403   }
1404 
1405   printTag(T->getDecl(), OS);
1406 }
1407 
1408 void TypePrinter::printRecordAfter(const RecordType *T, raw_ostream &OS) {}
1409 
1410 void TypePrinter::printEnumBefore(const EnumType *T, raw_ostream &OS) {
1411   printTag(T->getDecl(), OS);
1412 }
1413 
1414 void TypePrinter::printEnumAfter(const EnumType *T, raw_ostream &OS) {}
1415 
1416 void TypePrinter::printTemplateTypeParmBefore(const TemplateTypeParmType *T,
1417                                               raw_ostream &OS) {
1418   TemplateTypeParmDecl *D = T->getDecl();
1419   if (D && D->isImplicit()) {
1420     if (auto *TC = D->getTypeConstraint()) {
1421       TC->print(OS, Policy);
1422       OS << ' ';
1423     }
1424     OS << "auto";
1425   } else if (IdentifierInfo *Id = T->getIdentifier())
1426     OS << (Policy.CleanUglifiedParameters ? Id->deuglifiedName()
1427                                           : Id->getName());
1428   else
1429     OS << "type-parameter-" << T->getDepth() << '-' << T->getIndex();
1430 
1431   spaceBeforePlaceHolder(OS);
1432 }
1433 
1434 void TypePrinter::printTemplateTypeParmAfter(const TemplateTypeParmType *T,
1435                                              raw_ostream &OS) {}
1436 
1437 void TypePrinter::printSubstTemplateTypeParmBefore(
1438                                              const SubstTemplateTypeParmType *T,
1439                                              raw_ostream &OS) {
1440   IncludeStrongLifetimeRAII Strong(Policy);
1441   printBefore(T->getReplacementType(), OS);
1442 }
1443 
1444 void TypePrinter::printSubstTemplateTypeParmAfter(
1445                                              const SubstTemplateTypeParmType *T,
1446                                              raw_ostream &OS) {
1447   IncludeStrongLifetimeRAII Strong(Policy);
1448   printAfter(T->getReplacementType(), OS);
1449 }
1450 
1451 void TypePrinter::printSubstTemplateTypeParmPackBefore(
1452                                         const SubstTemplateTypeParmPackType *T,
1453                                         raw_ostream &OS) {
1454   IncludeStrongLifetimeRAII Strong(Policy);
1455   printTemplateTypeParmBefore(T->getReplacedParameter(), OS);
1456 }
1457 
1458 void TypePrinter::printSubstTemplateTypeParmPackAfter(
1459                                         const SubstTemplateTypeParmPackType *T,
1460                                         raw_ostream &OS) {
1461   IncludeStrongLifetimeRAII Strong(Policy);
1462   printTemplateTypeParmAfter(T->getReplacedParameter(), OS);
1463 }
1464 
1465 void TypePrinter::printTemplateId(const TemplateSpecializationType *T,
1466                                   raw_ostream &OS, bool FullyQualify) {
1467   IncludeStrongLifetimeRAII Strong(Policy);
1468 
1469   TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl();
1470   if (FullyQualify && TD) {
1471     if (!Policy.SuppressScope)
1472       AppendScope(TD->getDeclContext(), OS, TD->getDeclName());
1473 
1474     OS << TD->getName();
1475   } else {
1476     T->getTemplateName().print(OS, Policy);
1477   }
1478 
1479   printTemplateArgumentList(OS, T->template_arguments(), Policy);
1480   spaceBeforePlaceHolder(OS);
1481 }
1482 
1483 void TypePrinter::printTemplateSpecializationBefore(
1484                                             const TemplateSpecializationType *T,
1485                                             raw_ostream &OS) {
1486   printTemplateId(T, OS, Policy.FullyQualifiedName);
1487 }
1488 
1489 void TypePrinter::printTemplateSpecializationAfter(
1490                                             const TemplateSpecializationType *T,
1491                                             raw_ostream &OS) {}
1492 
1493 void TypePrinter::printInjectedClassNameBefore(const InjectedClassNameType *T,
1494                                                raw_ostream &OS) {
1495   if (Policy.PrintInjectedClassNameWithArguments)
1496     return printTemplateSpecializationBefore(T->getInjectedTST(), OS);
1497 
1498   IncludeStrongLifetimeRAII Strong(Policy);
1499   T->getTemplateName().print(OS, Policy);
1500   spaceBeforePlaceHolder(OS);
1501 }
1502 
1503 void TypePrinter::printInjectedClassNameAfter(const InjectedClassNameType *T,
1504                                                raw_ostream &OS) {}
1505 
1506 void TypePrinter::printElaboratedBefore(const ElaboratedType *T,
1507                                         raw_ostream &OS) {
1508   if (Policy.IncludeTagDefinition && T->getOwnedTagDecl()) {
1509     TagDecl *OwnedTagDecl = T->getOwnedTagDecl();
1510     assert(OwnedTagDecl->getTypeForDecl() == T->getNamedType().getTypePtr() &&
1511            "OwnedTagDecl expected to be a declaration for the type");
1512     PrintingPolicy SubPolicy = Policy;
1513     SubPolicy.IncludeTagDefinition = false;
1514     OwnedTagDecl->print(OS, SubPolicy, Indentation);
1515     spaceBeforePlaceHolder(OS);
1516     return;
1517   }
1518 
1519   // The tag definition will take care of these.
1520   if (!Policy.IncludeTagDefinition)
1521   {
1522     OS << TypeWithKeyword::getKeywordName(T->getKeyword());
1523     if (T->getKeyword() != ETK_None)
1524       OS << " ";
1525     NestedNameSpecifier *Qualifier = T->getQualifier();
1526     if (Qualifier)
1527       Qualifier->print(OS, Policy);
1528   }
1529 
1530   ElaboratedTypePolicyRAII PolicyRAII(Policy);
1531   printBefore(T->getNamedType(), OS);
1532 }
1533 
1534 void TypePrinter::printElaboratedAfter(const ElaboratedType *T,
1535                                         raw_ostream &OS) {
1536   if (Policy.IncludeTagDefinition && T->getOwnedTagDecl())
1537     return;
1538   ElaboratedTypePolicyRAII PolicyRAII(Policy);
1539   printAfter(T->getNamedType(), OS);
1540 }
1541 
1542 void TypePrinter::printParenBefore(const ParenType *T, raw_ostream &OS) {
1543   if (!HasEmptyPlaceHolder && !isa<FunctionType>(T->getInnerType())) {
1544     printBefore(T->getInnerType(), OS);
1545     OS << '(';
1546   } else
1547     printBefore(T->getInnerType(), OS);
1548 }
1549 
1550 void TypePrinter::printParenAfter(const ParenType *T, raw_ostream &OS) {
1551   if (!HasEmptyPlaceHolder && !isa<FunctionType>(T->getInnerType())) {
1552     OS << ')';
1553     printAfter(T->getInnerType(), OS);
1554   } else
1555     printAfter(T->getInnerType(), OS);
1556 }
1557 
1558 void TypePrinter::printDependentNameBefore(const DependentNameType *T,
1559                                            raw_ostream &OS) {
1560   OS << TypeWithKeyword::getKeywordName(T->getKeyword());
1561   if (T->getKeyword() != ETK_None)
1562     OS << " ";
1563 
1564   T->getQualifier()->print(OS, Policy);
1565 
1566   OS << T->getIdentifier()->getName();
1567   spaceBeforePlaceHolder(OS);
1568 }
1569 
1570 void TypePrinter::printDependentNameAfter(const DependentNameType *T,
1571                                           raw_ostream &OS) {}
1572 
1573 void TypePrinter::printDependentTemplateSpecializationBefore(
1574         const DependentTemplateSpecializationType *T, raw_ostream &OS) {
1575   IncludeStrongLifetimeRAII Strong(Policy);
1576 
1577   OS << TypeWithKeyword::getKeywordName(T->getKeyword());
1578   if (T->getKeyword() != ETK_None)
1579     OS << " ";
1580 
1581   if (T->getQualifier())
1582     T->getQualifier()->print(OS, Policy);
1583   OS << "template " << T->getIdentifier()->getName();
1584   printTemplateArgumentList(OS, T->template_arguments(), Policy);
1585   spaceBeforePlaceHolder(OS);
1586 }
1587 
1588 void TypePrinter::printDependentTemplateSpecializationAfter(
1589         const DependentTemplateSpecializationType *T, raw_ostream &OS) {}
1590 
1591 void TypePrinter::printPackExpansionBefore(const PackExpansionType *T,
1592                                            raw_ostream &OS) {
1593   printBefore(T->getPattern(), OS);
1594 }
1595 
1596 void TypePrinter::printPackExpansionAfter(const PackExpansionType *T,
1597                                           raw_ostream &OS) {
1598   printAfter(T->getPattern(), OS);
1599   OS << "...";
1600 }
1601 
1602 void TypePrinter::printAttributedBefore(const AttributedType *T,
1603                                         raw_ostream &OS) {
1604   // FIXME: Generate this with TableGen.
1605 
1606   // Prefer the macro forms of the GC and ownership qualifiers.
1607   if (T->getAttrKind() == attr::ObjCGC ||
1608       T->getAttrKind() == attr::ObjCOwnership)
1609     return printBefore(T->getEquivalentType(), OS);
1610 
1611   if (T->getAttrKind() == attr::ObjCKindOf)
1612     OS << "__kindof ";
1613 
1614   if (T->getAttrKind() == attr::AddressSpace)
1615     printBefore(T->getEquivalentType(), OS);
1616   else
1617     printBefore(T->getModifiedType(), OS);
1618 
1619   if (T->isMSTypeSpec()) {
1620     switch (T->getAttrKind()) {
1621     default: return;
1622     case attr::Ptr32: OS << " __ptr32"; break;
1623     case attr::Ptr64: OS << " __ptr64"; break;
1624     case attr::SPtr: OS << " __sptr"; break;
1625     case attr::UPtr: OS << " __uptr"; break;
1626     }
1627     spaceBeforePlaceHolder(OS);
1628   }
1629 
1630   // Print nullability type specifiers.
1631   if (T->getImmediateNullability()) {
1632     if (T->getAttrKind() == attr::TypeNonNull)
1633       OS << " _Nonnull";
1634     else if (T->getAttrKind() == attr::TypeNullable)
1635       OS << " _Nullable";
1636     else if (T->getAttrKind() == attr::TypeNullUnspecified)
1637       OS << " _Null_unspecified";
1638     else if (T->getAttrKind() == attr::TypeNullableResult)
1639       OS << " _Nullable_result";
1640     else
1641       llvm_unreachable("unhandled nullability");
1642     spaceBeforePlaceHolder(OS);
1643   }
1644 }
1645 
1646 void TypePrinter::printAttributedAfter(const AttributedType *T,
1647                                        raw_ostream &OS) {
1648   // FIXME: Generate this with TableGen.
1649 
1650   // Prefer the macro forms of the GC and ownership qualifiers.
1651   if (T->getAttrKind() == attr::ObjCGC ||
1652       T->getAttrKind() == attr::ObjCOwnership)
1653     return printAfter(T->getEquivalentType(), OS);
1654 
1655   // If this is a calling convention attribute, don't print the implicit CC from
1656   // the modified type.
1657   SaveAndRestore<bool> MaybeSuppressCC(InsideCCAttribute, T->isCallingConv());
1658 
1659   printAfter(T->getModifiedType(), OS);
1660 
1661   // Some attributes are printed as qualifiers before the type, so we have
1662   // nothing left to do.
1663   if (T->getAttrKind() == attr::ObjCKindOf ||
1664       T->isMSTypeSpec() || T->getImmediateNullability())
1665     return;
1666 
1667   // Don't print the inert __unsafe_unretained attribute at all.
1668   if (T->getAttrKind() == attr::ObjCInertUnsafeUnretained)
1669     return;
1670 
1671   // Don't print ns_returns_retained unless it had an effect.
1672   if (T->getAttrKind() == attr::NSReturnsRetained &&
1673       !T->getEquivalentType()->castAs<FunctionType>()
1674                              ->getExtInfo().getProducesResult())
1675     return;
1676 
1677   if (T->getAttrKind() == attr::LifetimeBound) {
1678     OS << " [[clang::lifetimebound]]";
1679     return;
1680   }
1681 
1682   // The printing of the address_space attribute is handled by the qualifier
1683   // since it is still stored in the qualifier. Return early to prevent printing
1684   // this twice.
1685   if (T->getAttrKind() == attr::AddressSpace)
1686     return;
1687 
1688   OS << " __attribute__((";
1689   switch (T->getAttrKind()) {
1690 #define TYPE_ATTR(NAME)
1691 #define DECL_OR_TYPE_ATTR(NAME)
1692 #define ATTR(NAME) case attr::NAME:
1693 #include "clang/Basic/AttrList.inc"
1694     llvm_unreachable("non-type attribute attached to type");
1695 
1696   case attr::BTFTypeTag:
1697     llvm_unreachable("BTFTypeTag attribute handled separately");
1698 
1699   case attr::OpenCLPrivateAddressSpace:
1700   case attr::OpenCLGlobalAddressSpace:
1701   case attr::OpenCLGlobalDeviceAddressSpace:
1702   case attr::OpenCLGlobalHostAddressSpace:
1703   case attr::OpenCLLocalAddressSpace:
1704   case attr::OpenCLConstantAddressSpace:
1705   case attr::OpenCLGenericAddressSpace:
1706     // FIXME: Update printAttributedBefore to print these once we generate
1707     // AttributedType nodes for them.
1708     break;
1709 
1710   case attr::LifetimeBound:
1711   case attr::TypeNonNull:
1712   case attr::TypeNullable:
1713   case attr::TypeNullableResult:
1714   case attr::TypeNullUnspecified:
1715   case attr::ObjCGC:
1716   case attr::ObjCInertUnsafeUnretained:
1717   case attr::ObjCKindOf:
1718   case attr::ObjCOwnership:
1719   case attr::Ptr32:
1720   case attr::Ptr64:
1721   case attr::SPtr:
1722   case attr::UPtr:
1723   case attr::AddressSpace:
1724   case attr::CmseNSCall:
1725     llvm_unreachable("This attribute should have been handled already");
1726 
1727   case attr::NSReturnsRetained:
1728     OS << "ns_returns_retained";
1729     break;
1730 
1731   // FIXME: When Sema learns to form this AttributedType, avoid printing the
1732   // attribute again in printFunctionProtoAfter.
1733   case attr::AnyX86NoCfCheck: OS << "nocf_check"; break;
1734   case attr::CDecl: OS << "cdecl"; break;
1735   case attr::FastCall: OS << "fastcall"; break;
1736   case attr::StdCall: OS << "stdcall"; break;
1737   case attr::ThisCall: OS << "thiscall"; break;
1738   case attr::SwiftCall: OS << "swiftcall"; break;
1739   case attr::SwiftAsyncCall: OS << "swiftasynccall"; break;
1740   case attr::VectorCall: OS << "vectorcall"; break;
1741   case attr::Pascal: OS << "pascal"; break;
1742   case attr::MSABI: OS << "ms_abi"; break;
1743   case attr::SysVABI: OS << "sysv_abi"; break;
1744   case attr::RegCall: OS << "regcall"; break;
1745   case attr::Pcs: {
1746     OS << "pcs(";
1747    QualType t = T->getEquivalentType();
1748    while (!t->isFunctionType())
1749      t = t->getPointeeType();
1750    OS << (t->castAs<FunctionType>()->getCallConv() == CC_AAPCS ?
1751          "\"aapcs\"" : "\"aapcs-vfp\"");
1752    OS << ')';
1753    break;
1754   }
1755   case attr::AArch64VectorPcs: OS << "aarch64_vector_pcs"; break;
1756   case attr::AArch64SVEPcs: OS << "aarch64_sve_pcs"; break;
1757   case attr::IntelOclBicc: OS << "inteloclbicc"; break;
1758   case attr::PreserveMost:
1759     OS << "preserve_most";
1760     break;
1761 
1762   case attr::PreserveAll:
1763     OS << "preserve_all";
1764     break;
1765   case attr::NoDeref:
1766     OS << "noderef";
1767     break;
1768   case attr::AcquireHandle:
1769     OS << "acquire_handle";
1770     break;
1771   case attr::ArmMveStrictPolymorphism:
1772     OS << "__clang_arm_mve_strict_polymorphism";
1773     break;
1774   }
1775   OS << "))";
1776 }
1777 
1778 void TypePrinter::printBTFTagAttributedBefore(const BTFTagAttributedType *T,
1779                                               raw_ostream &OS) {
1780   printBefore(T->getWrappedType(), OS);
1781   OS << " btf_type_tag(" << T->getAttr()->getBTFTypeTag() << ")";
1782 }
1783 
1784 void TypePrinter::printBTFTagAttributedAfter(const BTFTagAttributedType *T,
1785                                              raw_ostream &OS) {
1786   printAfter(T->getWrappedType(), OS);
1787 }
1788 
1789 void TypePrinter::printObjCInterfaceBefore(const ObjCInterfaceType *T,
1790                                            raw_ostream &OS) {
1791   OS << T->getDecl()->getName();
1792   spaceBeforePlaceHolder(OS);
1793 }
1794 
1795 void TypePrinter::printObjCInterfaceAfter(const ObjCInterfaceType *T,
1796                                           raw_ostream &OS) {}
1797 
1798 void TypePrinter::printObjCTypeParamBefore(const ObjCTypeParamType *T,
1799                                           raw_ostream &OS) {
1800   OS << T->getDecl()->getName();
1801   if (!T->qual_empty()) {
1802     bool isFirst = true;
1803     OS << '<';
1804     for (const auto *I : T->quals()) {
1805       if (isFirst)
1806         isFirst = false;
1807       else
1808         OS << ',';
1809       OS << I->getName();
1810     }
1811     OS << '>';
1812   }
1813 
1814   spaceBeforePlaceHolder(OS);
1815 }
1816 
1817 void TypePrinter::printObjCTypeParamAfter(const ObjCTypeParamType *T,
1818                                           raw_ostream &OS) {}
1819 
1820 void TypePrinter::printObjCObjectBefore(const ObjCObjectType *T,
1821                                         raw_ostream &OS) {
1822   if (T->qual_empty() && T->isUnspecializedAsWritten() &&
1823       !T->isKindOfTypeAsWritten())
1824     return printBefore(T->getBaseType(), OS);
1825 
1826   if (T->isKindOfTypeAsWritten())
1827     OS << "__kindof ";
1828 
1829   print(T->getBaseType(), OS, StringRef());
1830 
1831   if (T->isSpecializedAsWritten()) {
1832     bool isFirst = true;
1833     OS << '<';
1834     for (auto typeArg : T->getTypeArgsAsWritten()) {
1835       if (isFirst)
1836         isFirst = false;
1837       else
1838         OS << ",";
1839 
1840       print(typeArg, OS, StringRef());
1841     }
1842     OS << '>';
1843   }
1844 
1845   if (!T->qual_empty()) {
1846     bool isFirst = true;
1847     OS << '<';
1848     for (const auto *I : T->quals()) {
1849       if (isFirst)
1850         isFirst = false;
1851       else
1852         OS << ',';
1853       OS << I->getName();
1854     }
1855     OS << '>';
1856   }
1857 
1858   spaceBeforePlaceHolder(OS);
1859 }
1860 
1861 void TypePrinter::printObjCObjectAfter(const ObjCObjectType *T,
1862                                         raw_ostream &OS) {
1863   if (T->qual_empty() && T->isUnspecializedAsWritten() &&
1864       !T->isKindOfTypeAsWritten())
1865     return printAfter(T->getBaseType(), OS);
1866 }
1867 
1868 void TypePrinter::printObjCObjectPointerBefore(const ObjCObjectPointerType *T,
1869                                                raw_ostream &OS) {
1870   printBefore(T->getPointeeType(), OS);
1871 
1872   // If we need to print the pointer, print it now.
1873   if (!T->isObjCIdType() && !T->isObjCQualifiedIdType() &&
1874       !T->isObjCClassType() && !T->isObjCQualifiedClassType()) {
1875     if (HasEmptyPlaceHolder)
1876       OS << ' ';
1877     OS << '*';
1878   }
1879 }
1880 
1881 void TypePrinter::printObjCObjectPointerAfter(const ObjCObjectPointerType *T,
1882                                               raw_ostream &OS) {}
1883 
1884 static
1885 const TemplateArgument &getArgument(const TemplateArgument &A) { return A; }
1886 
1887 static const TemplateArgument &getArgument(const TemplateArgumentLoc &A) {
1888   return A.getArgument();
1889 }
1890 
1891 static void printArgument(const TemplateArgument &A, const PrintingPolicy &PP,
1892                           llvm::raw_ostream &OS, bool IncludeType) {
1893   A.print(PP, OS, IncludeType);
1894 }
1895 
1896 static void printArgument(const TemplateArgumentLoc &A,
1897                           const PrintingPolicy &PP, llvm::raw_ostream &OS,
1898                           bool IncludeType) {
1899   const TemplateArgument::ArgKind &Kind = A.getArgument().getKind();
1900   if (Kind == TemplateArgument::ArgKind::Type)
1901     return A.getTypeSourceInfo()->getType().print(OS, PP);
1902   return A.getArgument().print(PP, OS, IncludeType);
1903 }
1904 
1905 static bool isSubstitutedTemplateArgument(ASTContext &Ctx, TemplateArgument Arg,
1906                                           TemplateArgument Pattern,
1907                                           ArrayRef<TemplateArgument> Args,
1908                                           unsigned Depth);
1909 
1910 static bool isSubstitutedType(ASTContext &Ctx, QualType T, QualType Pattern,
1911                               ArrayRef<TemplateArgument> Args, unsigned Depth) {
1912   if (Ctx.hasSameType(T, Pattern))
1913     return true;
1914 
1915   // A type parameter matches its argument.
1916   if (auto *TTPT = Pattern->getAs<TemplateTypeParmType>()) {
1917     if (TTPT->getDepth() == Depth && TTPT->getIndex() < Args.size() &&
1918         Args[TTPT->getIndex()].getKind() == TemplateArgument::Type) {
1919       QualType SubstArg = Ctx.getQualifiedType(
1920           Args[TTPT->getIndex()].getAsType(), Pattern.getQualifiers());
1921       return Ctx.hasSameType(SubstArg, T);
1922     }
1923     return false;
1924   }
1925 
1926   // FIXME: Recurse into array types.
1927 
1928   // All other cases will need the types to be identically qualified.
1929   Qualifiers TQual, PatQual;
1930   T = Ctx.getUnqualifiedArrayType(T, TQual);
1931   Pattern = Ctx.getUnqualifiedArrayType(Pattern, PatQual);
1932   if (TQual != PatQual)
1933     return false;
1934 
1935   // Recurse into pointer-like types.
1936   {
1937     QualType TPointee = T->getPointeeType();
1938     QualType PPointee = Pattern->getPointeeType();
1939     if (!TPointee.isNull() && !PPointee.isNull())
1940       return T->getTypeClass() == Pattern->getTypeClass() &&
1941              isSubstitutedType(Ctx, TPointee, PPointee, Args, Depth);
1942   }
1943 
1944   // Recurse into template specialization types.
1945   if (auto *PTST =
1946           Pattern.getCanonicalType()->getAs<TemplateSpecializationType>()) {
1947     TemplateName Template;
1948     ArrayRef<TemplateArgument> TemplateArgs;
1949     if (auto *TTST = T->getAs<TemplateSpecializationType>()) {
1950       Template = TTST->getTemplateName();
1951       TemplateArgs = TTST->template_arguments();
1952     } else if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1953                    T->getAsCXXRecordDecl())) {
1954       Template = TemplateName(CTSD->getSpecializedTemplate());
1955       TemplateArgs = CTSD->getTemplateArgs().asArray();
1956     } else {
1957       return false;
1958     }
1959 
1960     if (!isSubstitutedTemplateArgument(Ctx, Template, PTST->getTemplateName(),
1961                                        Args, Depth))
1962       return false;
1963     if (TemplateArgs.size() != PTST->getNumArgs())
1964       return false;
1965     for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1966       if (!isSubstitutedTemplateArgument(Ctx, TemplateArgs[I], PTST->getArg(I),
1967                                          Args, Depth))
1968         return false;
1969     return true;
1970   }
1971 
1972   // FIXME: Handle more cases.
1973   return false;
1974 }
1975 
1976 static bool isSubstitutedTemplateArgument(ASTContext &Ctx, TemplateArgument Arg,
1977                                           TemplateArgument Pattern,
1978                                           ArrayRef<TemplateArgument> Args,
1979                                           unsigned Depth) {
1980   Arg = Ctx.getCanonicalTemplateArgument(Arg);
1981   Pattern = Ctx.getCanonicalTemplateArgument(Pattern);
1982   if (Arg.structurallyEquals(Pattern))
1983     return true;
1984 
1985   if (Pattern.getKind() == TemplateArgument::Expression) {
1986     if (auto *DRE =
1987             dyn_cast<DeclRefExpr>(Pattern.getAsExpr()->IgnoreParenImpCasts())) {
1988       if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
1989         return NTTP->getDepth() == Depth && Args.size() > NTTP->getIndex() &&
1990                Args[NTTP->getIndex()].structurallyEquals(Arg);
1991     }
1992   }
1993 
1994   if (Arg.getKind() != Pattern.getKind())
1995     return false;
1996 
1997   if (Arg.getKind() == TemplateArgument::Type)
1998     return isSubstitutedType(Ctx, Arg.getAsType(), Pattern.getAsType(), Args,
1999                              Depth);
2000 
2001   if (Arg.getKind() == TemplateArgument::Template) {
2002     TemplateDecl *PatTD = Pattern.getAsTemplate().getAsTemplateDecl();
2003     if (auto *TTPD = dyn_cast_or_null<TemplateTemplateParmDecl>(PatTD))
2004       return TTPD->getDepth() == Depth && Args.size() > TTPD->getIndex() &&
2005              Ctx.getCanonicalTemplateArgument(Args[TTPD->getIndex()])
2006                  .structurallyEquals(Arg);
2007   }
2008 
2009   // FIXME: Handle more cases.
2010   return false;
2011 }
2012 
2013 /// Make a best-effort determination of whether the type T can be produced by
2014 /// substituting Args into the default argument of Param.
2015 static bool isSubstitutedDefaultArgument(ASTContext &Ctx, TemplateArgument Arg,
2016                                          const NamedDecl *Param,
2017                                          ArrayRef<TemplateArgument> Args,
2018                                          unsigned Depth) {
2019   // An empty pack is equivalent to not providing a pack argument.
2020   if (Arg.getKind() == TemplateArgument::Pack && Arg.pack_size() == 0)
2021     return true;
2022 
2023   if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Param)) {
2024     return TTPD->hasDefaultArgument() &&
2025            isSubstitutedTemplateArgument(Ctx, Arg, TTPD->getDefaultArgument(),
2026                                          Args, Depth);
2027   } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2028     return TTPD->hasDefaultArgument() &&
2029            isSubstitutedTemplateArgument(
2030                Ctx, Arg, TTPD->getDefaultArgument().getArgument(), Args, Depth);
2031   } else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2032     return NTTPD->hasDefaultArgument() &&
2033            isSubstitutedTemplateArgument(Ctx, Arg, NTTPD->getDefaultArgument(),
2034                                          Args, Depth);
2035   }
2036   return false;
2037 }
2038 
2039 template <typename TA>
2040 static void
2041 printTo(raw_ostream &OS, ArrayRef<TA> Args, const PrintingPolicy &Policy,
2042         const TemplateParameterList *TPL, bool IsPack, unsigned ParmIndex) {
2043   // Drop trailing template arguments that match default arguments.
2044   if (TPL && Policy.SuppressDefaultTemplateArgs &&
2045       !Policy.PrintCanonicalTypes && !Args.empty() && !IsPack &&
2046       Args.size() <= TPL->size()) {
2047     ASTContext &Ctx = TPL->getParam(0)->getASTContext();
2048     llvm::SmallVector<TemplateArgument, 8> OrigArgs;
2049     for (const TA &A : Args)
2050       OrigArgs.push_back(getArgument(A));
2051     while (!Args.empty() &&
2052            isSubstitutedDefaultArgument(Ctx, getArgument(Args.back()),
2053                                         TPL->getParam(Args.size() - 1),
2054                                         OrigArgs, TPL->getDepth()))
2055       Args = Args.drop_back();
2056   }
2057 
2058   const char *Comma = Policy.MSVCFormatting ? "," : ", ";
2059   if (!IsPack)
2060     OS << '<';
2061 
2062   bool NeedSpace = false;
2063   bool FirstArg = true;
2064   for (const auto &Arg : Args) {
2065     // Print the argument into a string.
2066     SmallString<128> Buf;
2067     llvm::raw_svector_ostream ArgOS(Buf);
2068     const TemplateArgument &Argument = getArgument(Arg);
2069     if (Argument.getKind() == TemplateArgument::Pack) {
2070       if (Argument.pack_size() && !FirstArg)
2071         OS << Comma;
2072       printTo(ArgOS, Argument.getPackAsArray(), Policy, TPL,
2073               /*IsPack*/ true, ParmIndex);
2074     } else {
2075       if (!FirstArg)
2076         OS << Comma;
2077       // Tries to print the argument with location info if exists.
2078       printArgument(Arg, Policy, ArgOS,
2079                     TemplateParameterList::shouldIncludeTypeForArgument(
2080                         Policy, TPL, ParmIndex));
2081     }
2082     StringRef ArgString = ArgOS.str();
2083 
2084     // If this is the first argument and its string representation
2085     // begins with the global scope specifier ('::foo'), add a space
2086     // to avoid printing the diagraph '<:'.
2087     if (FirstArg && !ArgString.empty() && ArgString[0] == ':')
2088       OS << ' ';
2089 
2090     OS << ArgString;
2091 
2092     // If the last character of our string is '>', add another space to
2093     // keep the two '>''s separate tokens.
2094     if (!ArgString.empty()) {
2095       NeedSpace = Policy.SplitTemplateClosers && ArgString.back() == '>';
2096       FirstArg = false;
2097     }
2098 
2099     // Use same template parameter for all elements of Pack
2100     if (!IsPack)
2101       ParmIndex++;
2102   }
2103 
2104   if (!IsPack) {
2105     if (NeedSpace)
2106       OS << ' ';
2107     OS << '>';
2108   }
2109 }
2110 
2111 void clang::printTemplateArgumentList(raw_ostream &OS,
2112                                       const TemplateArgumentListInfo &Args,
2113                                       const PrintingPolicy &Policy,
2114                                       const TemplateParameterList *TPL) {
2115   printTemplateArgumentList(OS, Args.arguments(), Policy, TPL);
2116 }
2117 
2118 void clang::printTemplateArgumentList(raw_ostream &OS,
2119                                       ArrayRef<TemplateArgument> Args,
2120                                       const PrintingPolicy &Policy,
2121                                       const TemplateParameterList *TPL) {
2122   printTo(OS, Args, Policy, TPL, /*isPack*/ false, /*parmIndex*/ 0);
2123 }
2124 
2125 void clang::printTemplateArgumentList(raw_ostream &OS,
2126                                       ArrayRef<TemplateArgumentLoc> Args,
2127                                       const PrintingPolicy &Policy,
2128                                       const TemplateParameterList *TPL) {
2129   printTo(OS, Args, Policy, TPL, /*isPack*/ false, /*parmIndex*/ 0);
2130 }
2131 
2132 std::string Qualifiers::getAsString() const {
2133   LangOptions LO;
2134   return getAsString(PrintingPolicy(LO));
2135 }
2136 
2137 // Appends qualifiers to the given string, separated by spaces.  Will
2138 // prefix a space if the string is non-empty.  Will not append a final
2139 // space.
2140 std::string Qualifiers::getAsString(const PrintingPolicy &Policy) const {
2141   SmallString<64> Buf;
2142   llvm::raw_svector_ostream StrOS(Buf);
2143   print(StrOS, Policy);
2144   return std::string(StrOS.str());
2145 }
2146 
2147 bool Qualifiers::isEmptyWhenPrinted(const PrintingPolicy &Policy) const {
2148   if (getCVRQualifiers())
2149     return false;
2150 
2151   if (getAddressSpace() != LangAS::Default)
2152     return false;
2153 
2154   if (getObjCGCAttr())
2155     return false;
2156 
2157   if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime())
2158     if (!(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime))
2159       return false;
2160 
2161   return true;
2162 }
2163 
2164 std::string Qualifiers::getAddrSpaceAsString(LangAS AS) {
2165   switch (AS) {
2166   case LangAS::Default:
2167     return "";
2168   case LangAS::opencl_global:
2169   case LangAS::sycl_global:
2170     return "__global";
2171   case LangAS::opencl_local:
2172   case LangAS::sycl_local:
2173     return "__local";
2174   case LangAS::opencl_private:
2175   case LangAS::sycl_private:
2176     return "__private";
2177   case LangAS::opencl_constant:
2178     return "__constant";
2179   case LangAS::opencl_generic:
2180     return "__generic";
2181   case LangAS::opencl_global_device:
2182   case LangAS::sycl_global_device:
2183     return "__global_device";
2184   case LangAS::opencl_global_host:
2185   case LangAS::sycl_global_host:
2186     return "__global_host";
2187   case LangAS::cuda_device:
2188     return "__device__";
2189   case LangAS::cuda_constant:
2190     return "__constant__";
2191   case LangAS::cuda_shared:
2192     return "__shared__";
2193   case LangAS::ptr32_sptr:
2194     return "__sptr __ptr32";
2195   case LangAS::ptr32_uptr:
2196     return "__uptr __ptr32";
2197   case LangAS::ptr64:
2198     return "__ptr64";
2199   default:
2200     return std::to_string(toTargetAddressSpace(AS));
2201   }
2202 }
2203 
2204 // Appends qualifiers to the given string, separated by spaces.  Will
2205 // prefix a space if the string is non-empty.  Will not append a final
2206 // space.
2207 void Qualifiers::print(raw_ostream &OS, const PrintingPolicy& Policy,
2208                        bool appendSpaceIfNonEmpty) const {
2209   bool addSpace = false;
2210 
2211   unsigned quals = getCVRQualifiers();
2212   if (quals) {
2213     AppendTypeQualList(OS, quals, Policy.Restrict);
2214     addSpace = true;
2215   }
2216   if (hasUnaligned()) {
2217     if (addSpace)
2218       OS << ' ';
2219     OS << "__unaligned";
2220     addSpace = true;
2221   }
2222   auto ASStr = getAddrSpaceAsString(getAddressSpace());
2223   if (!ASStr.empty()) {
2224     if (addSpace)
2225       OS << ' ';
2226     addSpace = true;
2227     // Wrap target address space into an attribute syntax
2228     if (isTargetAddressSpace(getAddressSpace()))
2229       OS << "__attribute__((address_space(" << ASStr << ")))";
2230     else
2231       OS << ASStr;
2232   }
2233 
2234   if (Qualifiers::GC gc = getObjCGCAttr()) {
2235     if (addSpace)
2236       OS << ' ';
2237     addSpace = true;
2238     if (gc == Qualifiers::Weak)
2239       OS << "__weak";
2240     else
2241       OS << "__strong";
2242   }
2243   if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime()) {
2244     if (!(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime)){
2245       if (addSpace)
2246         OS << ' ';
2247       addSpace = true;
2248     }
2249 
2250     switch (lifetime) {
2251     case Qualifiers::OCL_None: llvm_unreachable("none but true");
2252     case Qualifiers::OCL_ExplicitNone: OS << "__unsafe_unretained"; break;
2253     case Qualifiers::OCL_Strong:
2254       if (!Policy.SuppressStrongLifetime)
2255         OS << "__strong";
2256       break;
2257 
2258     case Qualifiers::OCL_Weak: OS << "__weak"; break;
2259     case Qualifiers::OCL_Autoreleasing: OS << "__autoreleasing"; break;
2260     }
2261   }
2262 
2263   if (appendSpaceIfNonEmpty && addSpace)
2264     OS << ' ';
2265 }
2266 
2267 std::string QualType::getAsString() const {
2268   return getAsString(split(), LangOptions());
2269 }
2270 
2271 std::string QualType::getAsString(const PrintingPolicy &Policy) const {
2272   std::string S;
2273   getAsStringInternal(S, Policy);
2274   return S;
2275 }
2276 
2277 std::string QualType::getAsString(const Type *ty, Qualifiers qs,
2278                                   const PrintingPolicy &Policy) {
2279   std::string buffer;
2280   getAsStringInternal(ty, qs, buffer, Policy);
2281   return buffer;
2282 }
2283 
2284 void QualType::print(raw_ostream &OS, const PrintingPolicy &Policy,
2285                      const Twine &PlaceHolder, unsigned Indentation) const {
2286   print(splitAccordingToPolicy(*this, Policy), OS, Policy, PlaceHolder,
2287         Indentation);
2288 }
2289 
2290 void QualType::print(const Type *ty, Qualifiers qs,
2291                      raw_ostream &OS, const PrintingPolicy &policy,
2292                      const Twine &PlaceHolder, unsigned Indentation) {
2293   SmallString<128> PHBuf;
2294   StringRef PH = PlaceHolder.toStringRef(PHBuf);
2295 
2296   TypePrinter(policy, Indentation).print(ty, qs, OS, PH);
2297 }
2298 
2299 void QualType::getAsStringInternal(std::string &Str,
2300                                    const PrintingPolicy &Policy) const {
2301   return getAsStringInternal(splitAccordingToPolicy(*this, Policy), Str,
2302                              Policy);
2303 }
2304 
2305 void QualType::getAsStringInternal(const Type *ty, Qualifiers qs,
2306                                    std::string &buffer,
2307                                    const PrintingPolicy &policy) {
2308   SmallString<256> Buf;
2309   llvm::raw_svector_ostream StrOS(Buf);
2310   TypePrinter(policy).print(ty, qs, StrOS, buffer);
2311   std::string str = std::string(StrOS.str());
2312   buffer.swap(str);
2313 }
2314 
2315 raw_ostream &clang::operator<<(raw_ostream &OS, QualType QT) {
2316   SplitQualType S = QT.split();
2317   TypePrinter(LangOptions()).print(S.Ty, S.Quals, OS, /*PlaceHolder=*/"");
2318   return OS;
2319 }
2320