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