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