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