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