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