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