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   /// \brief 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 /// \brief 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 /// \brief 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     if (getExceptionSpecType() == EST_ComputedNoexcept) {
676       OS << '(';
677       if (getNoexceptExpr())
678         getNoexceptExpr()->printPretty(OS, nullptr, Policy);
679       OS << ')';
680     }
681   }
682 }
683 
684 void TypePrinter::printFunctionProtoBefore(const FunctionProtoType *T,
685                                            raw_ostream &OS) {
686   if (T->hasTrailingReturn()) {
687     OS << "auto ";
688     if (!HasEmptyPlaceHolder)
689       OS << '(';
690   } else {
691     // If needed for precedence reasons, wrap the inner part in grouping parens.
692     SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder, false);
693     printBefore(T->getReturnType(), OS);
694     if (!PrevPHIsEmpty.get())
695       OS << '(';
696   }
697 }
698 
699 StringRef clang::getParameterABISpelling(ParameterABI ABI) {
700   switch (ABI) {
701   case ParameterABI::Ordinary:
702     llvm_unreachable("asking for spelling of ordinary parameter ABI");
703   case ParameterABI::SwiftContext:
704     return "swift_context";
705   case ParameterABI::SwiftErrorResult:
706     return "swift_error_result";
707   case ParameterABI::SwiftIndirectResult:
708     return "swift_indirect_result";
709   }
710   llvm_unreachable("bad parameter ABI kind");
711 }
712 
713 void TypePrinter::printFunctionProtoAfter(const FunctionProtoType *T,
714                                           raw_ostream &OS) {
715   // If needed for precedence reasons, wrap the inner part in grouping parens.
716   if (!HasEmptyPlaceHolder)
717     OS << ')';
718   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
719 
720   OS << '(';
721   {
722     ParamPolicyRAII ParamPolicy(Policy);
723     for (unsigned i = 0, e = T->getNumParams(); i != e; ++i) {
724       if (i) OS << ", ";
725 
726       auto EPI = T->getExtParameterInfo(i);
727       if (EPI.isConsumed()) OS << "__attribute__((ns_consumed)) ";
728       if (EPI.isNoEscape())
729         OS << "__attribute__((noescape)) ";
730       auto ABI = EPI.getABI();
731       if (ABI != ParameterABI::Ordinary)
732         OS << "__attribute__((" << getParameterABISpelling(ABI) << ")) ";
733 
734       print(T->getParamType(i), OS, StringRef());
735     }
736   }
737 
738   if (T->isVariadic()) {
739     if (T->getNumParams())
740       OS << ", ";
741     OS << "...";
742   } else if (T->getNumParams() == 0 && Policy.UseVoidForZeroParams) {
743     // Do not emit int() if we have a proto, emit 'int(void)'.
744     OS << "void";
745   }
746 
747   OS << ')';
748 
749   FunctionType::ExtInfo Info = T->getExtInfo();
750 
751   printFunctionAfter(Info, OS);
752 
753   if (unsigned quals = T->getTypeQuals()) {
754     OS << ' ';
755     AppendTypeQualList(OS, quals, Policy.Restrict);
756   }
757 
758   switch (T->getRefQualifier()) {
759   case RQ_None:
760     break;
761 
762   case RQ_LValue:
763     OS << " &";
764     break;
765 
766   case RQ_RValue:
767     OS << " &&";
768     break;
769   }
770   T->printExceptionSpecification(OS, Policy);
771 
772   if (T->hasTrailingReturn()) {
773     OS << " -> ";
774     print(T->getReturnType(), OS, StringRef());
775   } else
776     printAfter(T->getReturnType(), OS);
777 }
778 
779 void TypePrinter::printFunctionAfter(const FunctionType::ExtInfo &Info,
780                                      raw_ostream &OS) {
781   if (!InsideCCAttribute) {
782     switch (Info.getCC()) {
783     case CC_C:
784       // The C calling convention is the default on the vast majority of platforms
785       // we support.  If the user wrote it explicitly, it will usually be printed
786       // while traversing the AttributedType.  If the type has been desugared, let
787       // the canonical spelling be the implicit calling convention.
788       // FIXME: It would be better to be explicit in certain contexts, such as a
789       // cdecl function typedef used to declare a member function with the
790       // Microsoft C++ ABI.
791       break;
792     case CC_X86StdCall:
793       OS << " __attribute__((stdcall))";
794       break;
795     case CC_X86FastCall:
796       OS << " __attribute__((fastcall))";
797       break;
798     case CC_X86ThisCall:
799       OS << " __attribute__((thiscall))";
800       break;
801     case CC_X86VectorCall:
802       OS << " __attribute__((vectorcall))";
803       break;
804     case CC_X86Pascal:
805       OS << " __attribute__((pascal))";
806       break;
807     case CC_AAPCS:
808       OS << " __attribute__((pcs(\"aapcs\")))";
809       break;
810     case CC_AAPCS_VFP:
811       OS << " __attribute__((pcs(\"aapcs-vfp\")))";
812       break;
813     case CC_IntelOclBicc:
814       OS << " __attribute__((intel_ocl_bicc))";
815       break;
816     case CC_Win64:
817       OS << " __attribute__((ms_abi))";
818       break;
819     case CC_X86_64SysV:
820       OS << " __attribute__((sysv_abi))";
821       break;
822     case CC_X86RegCall:
823       OS << " __attribute__((regcall))";
824       break;
825     case CC_SpirFunction:
826     case CC_OpenCLKernel:
827       // Do nothing. These CCs are not available as attributes.
828       break;
829     case CC_Swift:
830       OS << " __attribute__((swiftcall))";
831       break;
832     case CC_PreserveMost:
833       OS << " __attribute__((preserve_most))";
834       break;
835     case CC_PreserveAll:
836       OS << " __attribute__((preserve_all))";
837       break;
838     }
839   }
840 
841   if (Info.getNoReturn())
842     OS << " __attribute__((noreturn))";
843   if (Info.getProducesResult())
844     OS << " __attribute__((ns_returns_retained))";
845   if (Info.getRegParm())
846     OS << " __attribute__((regparm ("
847        << Info.getRegParm() << ")))";
848   if (Info.getNoCallerSavedRegs())
849     OS << " __attribute__((no_caller_saved_registers))";
850   if (Info.getNoCfCheck())
851     OS << " __attribute__((nocf_check))";
852 }
853 
854 void TypePrinter::printFunctionNoProtoBefore(const FunctionNoProtoType *T,
855                                              raw_ostream &OS) {
856   // If needed for precedence reasons, wrap the inner part in grouping parens.
857   SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder, false);
858   printBefore(T->getReturnType(), OS);
859   if (!PrevPHIsEmpty.get())
860     OS << '(';
861 }
862 
863 void TypePrinter::printFunctionNoProtoAfter(const FunctionNoProtoType *T,
864                                             raw_ostream &OS) {
865   // If needed for precedence reasons, wrap the inner part in grouping parens.
866   if (!HasEmptyPlaceHolder)
867     OS << ')';
868   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
869 
870   OS << "()";
871   printFunctionAfter(T->getExtInfo(), OS);
872   printAfter(T->getReturnType(), OS);
873 }
874 
875 void TypePrinter::printTypeSpec(NamedDecl *D, raw_ostream &OS) {
876 
877   // Compute the full nested-name-specifier for this type.
878   // In C, this will always be empty except when the type
879   // being printed is anonymous within other Record.
880   if (!Policy.SuppressScope)
881     AppendScope(D->getDeclContext(), OS);
882 
883   IdentifierInfo *II = D->getIdentifier();
884   OS << II->getName();
885   spaceBeforePlaceHolder(OS);
886 }
887 
888 void TypePrinter::printUnresolvedUsingBefore(const UnresolvedUsingType *T,
889                                              raw_ostream &OS) {
890   printTypeSpec(T->getDecl(), OS);
891 }
892 
893 void TypePrinter::printUnresolvedUsingAfter(const UnresolvedUsingType *T,
894                                             raw_ostream &OS) {}
895 
896 void TypePrinter::printTypedefBefore(const TypedefType *T, raw_ostream &OS) {
897   printTypeSpec(T->getDecl(), OS);
898 }
899 
900 void TypePrinter::printTypedefAfter(const TypedefType *T, raw_ostream &OS) {}
901 
902 void TypePrinter::printTypeOfExprBefore(const TypeOfExprType *T,
903                                         raw_ostream &OS) {
904   OS << "typeof ";
905   if (T->getUnderlyingExpr())
906     T->getUnderlyingExpr()->printPretty(OS, nullptr, Policy);
907   spaceBeforePlaceHolder(OS);
908 }
909 
910 void TypePrinter::printTypeOfExprAfter(const TypeOfExprType *T,
911                                        raw_ostream &OS) {}
912 
913 void TypePrinter::printTypeOfBefore(const TypeOfType *T, raw_ostream &OS) {
914   OS << "typeof(";
915   print(T->getUnderlyingType(), OS, StringRef());
916   OS << ')';
917   spaceBeforePlaceHolder(OS);
918 }
919 
920 void TypePrinter::printTypeOfAfter(const TypeOfType *T, raw_ostream &OS) {}
921 
922 void TypePrinter::printDecltypeBefore(const DecltypeType *T, raw_ostream &OS) {
923   OS << "decltype(";
924   if (T->getUnderlyingExpr())
925     T->getUnderlyingExpr()->printPretty(OS, nullptr, Policy);
926   OS << ')';
927   spaceBeforePlaceHolder(OS);
928 }
929 
930 void TypePrinter::printDecltypeAfter(const DecltypeType *T, raw_ostream &OS) {}
931 
932 void TypePrinter::printUnaryTransformBefore(const UnaryTransformType *T,
933                                             raw_ostream &OS) {
934   IncludeStrongLifetimeRAII Strong(Policy);
935 
936   switch (T->getUTTKind()) {
937     case UnaryTransformType::EnumUnderlyingType:
938       OS << "__underlying_type(";
939       print(T->getBaseType(), OS, StringRef());
940       OS << ')';
941       spaceBeforePlaceHolder(OS);
942       return;
943   }
944 
945   printBefore(T->getBaseType(), OS);
946 }
947 
948 void TypePrinter::printUnaryTransformAfter(const UnaryTransformType *T,
949                                            raw_ostream &OS) {
950   IncludeStrongLifetimeRAII Strong(Policy);
951 
952   switch (T->getUTTKind()) {
953     case UnaryTransformType::EnumUnderlyingType:
954       return;
955   }
956 
957   printAfter(T->getBaseType(), OS);
958 }
959 
960 void TypePrinter::printAutoBefore(const AutoType *T, raw_ostream &OS) {
961   // If the type has been deduced, do not print 'auto'.
962   if (!T->getDeducedType().isNull()) {
963     printBefore(T->getDeducedType(), OS);
964   } else {
965     switch (T->getKeyword()) {
966     case AutoTypeKeyword::Auto: OS << "auto"; break;
967     case AutoTypeKeyword::DecltypeAuto: OS << "decltype(auto)"; break;
968     case AutoTypeKeyword::GNUAutoType: OS << "__auto_type"; break;
969     }
970     spaceBeforePlaceHolder(OS);
971   }
972 }
973 
974 void TypePrinter::printAutoAfter(const AutoType *T, raw_ostream &OS) {
975   // If the type has been deduced, do not print 'auto'.
976   if (!T->getDeducedType().isNull())
977     printAfter(T->getDeducedType(), OS);
978 }
979 
980 void TypePrinter::printDeducedTemplateSpecializationBefore(
981     const DeducedTemplateSpecializationType *T, raw_ostream &OS) {
982   // If the type has been deduced, print the deduced type.
983   if (!T->getDeducedType().isNull()) {
984     printBefore(T->getDeducedType(), OS);
985   } else {
986     IncludeStrongLifetimeRAII Strong(Policy);
987     T->getTemplateName().print(OS, Policy);
988     spaceBeforePlaceHolder(OS);
989   }
990 }
991 
992 void TypePrinter::printDeducedTemplateSpecializationAfter(
993     const DeducedTemplateSpecializationType *T, raw_ostream &OS) {
994   // If the type has been deduced, print the deduced type.
995   if (!T->getDeducedType().isNull())
996     printAfter(T->getDeducedType(), OS);
997 }
998 
999 void TypePrinter::printAtomicBefore(const AtomicType *T, raw_ostream &OS) {
1000   IncludeStrongLifetimeRAII Strong(Policy);
1001 
1002   OS << "_Atomic(";
1003   print(T->getValueType(), OS, StringRef());
1004   OS << ')';
1005   spaceBeforePlaceHolder(OS);
1006 }
1007 
1008 void TypePrinter::printAtomicAfter(const AtomicType *T, raw_ostream &OS) {}
1009 
1010 void TypePrinter::printPipeBefore(const PipeType *T, raw_ostream &OS) {
1011   IncludeStrongLifetimeRAII Strong(Policy);
1012 
1013   if (T->isReadOnly())
1014     OS << "read_only ";
1015   else
1016     OS << "write_only ";
1017   OS << "pipe ";
1018   print(T->getElementType(), OS, StringRef());
1019   spaceBeforePlaceHolder(OS);
1020 }
1021 
1022 void TypePrinter::printPipeAfter(const PipeType *T, raw_ostream &OS) {}
1023 
1024 /// Appends the given scope to the end of a string.
1025 void TypePrinter::AppendScope(DeclContext *DC, raw_ostream &OS) {
1026   if (DC->isTranslationUnit()) return;
1027   if (DC->isFunctionOrMethod()) return;
1028   AppendScope(DC->getParent(), OS);
1029 
1030   if (const auto *NS = dyn_cast<NamespaceDecl>(DC)) {
1031     if (Policy.SuppressUnwrittenScope &&
1032         (NS->isAnonymousNamespace() || NS->isInline()))
1033       return;
1034     if (NS->getIdentifier())
1035       OS << NS->getName() << "::";
1036     else
1037       OS << "(anonymous namespace)::";
1038   } else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
1039     IncludeStrongLifetimeRAII Strong(Policy);
1040     OS << Spec->getIdentifier()->getName();
1041     const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1042     printTemplateArgumentList(OS, TemplateArgs.asArray(), Policy);
1043     OS << "::";
1044   } else if (const auto *Tag = dyn_cast<TagDecl>(DC)) {
1045     if (TypedefNameDecl *Typedef = Tag->getTypedefNameForAnonDecl())
1046       OS << Typedef->getIdentifier()->getName() << "::";
1047     else if (Tag->getIdentifier())
1048       OS << Tag->getIdentifier()->getName() << "::";
1049     else
1050       return;
1051   }
1052 }
1053 
1054 void TypePrinter::printTag(TagDecl *D, raw_ostream &OS) {
1055   if (Policy.IncludeTagDefinition) {
1056     PrintingPolicy SubPolicy = Policy;
1057     SubPolicy.IncludeTagDefinition = false;
1058     D->print(OS, SubPolicy, Indentation);
1059     spaceBeforePlaceHolder(OS);
1060     return;
1061   }
1062 
1063   bool HasKindDecoration = false;
1064 
1065   // We don't print tags unless this is an elaborated type.
1066   // In C, we just assume every RecordType is an elaborated type.
1067   if (!Policy.SuppressTagKeyword && !D->getTypedefNameForAnonDecl()) {
1068     HasKindDecoration = true;
1069     OS << D->getKindName();
1070     OS << ' ';
1071   }
1072 
1073   // Compute the full nested-name-specifier for this type.
1074   // In C, this will always be empty except when the type
1075   // being printed is anonymous within other Record.
1076   if (!Policy.SuppressScope)
1077     AppendScope(D->getDeclContext(), OS);
1078 
1079   if (const IdentifierInfo *II = D->getIdentifier())
1080     OS << II->getName();
1081   else if (TypedefNameDecl *Typedef = D->getTypedefNameForAnonDecl()) {
1082     assert(Typedef->getIdentifier() && "Typedef without identifier?");
1083     OS << Typedef->getIdentifier()->getName();
1084   } else {
1085     // Make an unambiguous representation for anonymous types, e.g.
1086     //   (anonymous enum at /usr/include/string.h:120:9)
1087     OS << (Policy.MSVCFormatting ? '`' : '(');
1088 
1089     if (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda()) {
1090       OS << "lambda";
1091       HasKindDecoration = true;
1092     } else {
1093       OS << "anonymous";
1094     }
1095 
1096     if (Policy.AnonymousTagLocations) {
1097       // Suppress the redundant tag keyword if we just printed one.
1098       // We don't have to worry about ElaboratedTypes here because you can't
1099       // refer to an anonymous type with one.
1100       if (!HasKindDecoration)
1101         OS << " " << D->getKindName();
1102 
1103       PresumedLoc PLoc = D->getASTContext().getSourceManager().getPresumedLoc(
1104           D->getLocation());
1105       if (PLoc.isValid()) {
1106         OS << " at " << PLoc.getFilename()
1107            << ':' << PLoc.getLine()
1108            << ':' << PLoc.getColumn();
1109       }
1110     }
1111 
1112     OS << (Policy.MSVCFormatting ? '\'' : ')');
1113   }
1114 
1115   // If this is a class template specialization, print the template
1116   // arguments.
1117   if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
1118     ArrayRef<TemplateArgument> Args;
1119     if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
1120       const TemplateSpecializationType *TST =
1121         cast<TemplateSpecializationType>(TAW->getType());
1122       Args = TST->template_arguments();
1123     } else {
1124       const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1125       Args = TemplateArgs.asArray();
1126     }
1127     IncludeStrongLifetimeRAII Strong(Policy);
1128     printTemplateArgumentList(OS, Args, Policy);
1129   }
1130 
1131   spaceBeforePlaceHolder(OS);
1132 }
1133 
1134 void TypePrinter::printRecordBefore(const RecordType *T, raw_ostream &OS) {
1135   printTag(T->getDecl(), OS);
1136 }
1137 
1138 void TypePrinter::printRecordAfter(const RecordType *T, raw_ostream &OS) {}
1139 
1140 void TypePrinter::printEnumBefore(const EnumType *T, raw_ostream &OS) {
1141   printTag(T->getDecl(), OS);
1142 }
1143 
1144 void TypePrinter::printEnumAfter(const EnumType *T, raw_ostream &OS) {}
1145 
1146 void TypePrinter::printTemplateTypeParmBefore(const TemplateTypeParmType *T,
1147                                               raw_ostream &OS) {
1148   if (IdentifierInfo *Id = T->getIdentifier())
1149     OS << Id->getName();
1150   else
1151     OS << "type-parameter-" << T->getDepth() << '-' << T->getIndex();
1152   spaceBeforePlaceHolder(OS);
1153 }
1154 
1155 void TypePrinter::printTemplateTypeParmAfter(const TemplateTypeParmType *T,
1156                                              raw_ostream &OS) {}
1157 
1158 void TypePrinter::printSubstTemplateTypeParmBefore(
1159                                              const SubstTemplateTypeParmType *T,
1160                                              raw_ostream &OS) {
1161   IncludeStrongLifetimeRAII Strong(Policy);
1162   printBefore(T->getReplacementType(), OS);
1163 }
1164 
1165 void TypePrinter::printSubstTemplateTypeParmAfter(
1166                                              const SubstTemplateTypeParmType *T,
1167                                              raw_ostream &OS) {
1168   IncludeStrongLifetimeRAII Strong(Policy);
1169   printAfter(T->getReplacementType(), OS);
1170 }
1171 
1172 void TypePrinter::printSubstTemplateTypeParmPackBefore(
1173                                         const SubstTemplateTypeParmPackType *T,
1174                                         raw_ostream &OS) {
1175   IncludeStrongLifetimeRAII Strong(Policy);
1176   printTemplateTypeParmBefore(T->getReplacedParameter(), OS);
1177 }
1178 
1179 void TypePrinter::printSubstTemplateTypeParmPackAfter(
1180                                         const SubstTemplateTypeParmPackType *T,
1181                                         raw_ostream &OS) {
1182   IncludeStrongLifetimeRAII Strong(Policy);
1183   printTemplateTypeParmAfter(T->getReplacedParameter(), OS);
1184 }
1185 
1186 void TypePrinter::printTemplateSpecializationBefore(
1187                                             const TemplateSpecializationType *T,
1188                                             raw_ostream &OS) {
1189   IncludeStrongLifetimeRAII Strong(Policy);
1190   T->getTemplateName().print(OS, Policy);
1191 
1192   printTemplateArgumentList(OS, T->template_arguments(), Policy);
1193   spaceBeforePlaceHolder(OS);
1194 }
1195 
1196 void TypePrinter::printTemplateSpecializationAfter(
1197                                             const TemplateSpecializationType *T,
1198                                             raw_ostream &OS) {}
1199 
1200 void TypePrinter::printInjectedClassNameBefore(const InjectedClassNameType *T,
1201                                                raw_ostream &OS) {
1202   printTemplateSpecializationBefore(T->getInjectedTST(), OS);
1203 }
1204 
1205 void TypePrinter::printInjectedClassNameAfter(const InjectedClassNameType *T,
1206                                                raw_ostream &OS) {}
1207 
1208 void TypePrinter::printElaboratedBefore(const ElaboratedType *T,
1209                                         raw_ostream &OS) {
1210   // The tag definition will take care of these.
1211   if (!Policy.IncludeTagDefinition)
1212   {
1213     OS << TypeWithKeyword::getKeywordName(T->getKeyword());
1214     if (T->getKeyword() != ETK_None)
1215       OS << " ";
1216     NestedNameSpecifier *Qualifier = T->getQualifier();
1217     if (Qualifier)
1218       Qualifier->print(OS, Policy);
1219   }
1220 
1221   ElaboratedTypePolicyRAII PolicyRAII(Policy);
1222   printBefore(T->getNamedType(), OS);
1223 }
1224 
1225 void TypePrinter::printElaboratedAfter(const ElaboratedType *T,
1226                                         raw_ostream &OS) {
1227   ElaboratedTypePolicyRAII PolicyRAII(Policy);
1228   printAfter(T->getNamedType(), OS);
1229 }
1230 
1231 void TypePrinter::printParenBefore(const ParenType *T, raw_ostream &OS) {
1232   if (!HasEmptyPlaceHolder && !isa<FunctionType>(T->getInnerType())) {
1233     printBefore(T->getInnerType(), OS);
1234     OS << '(';
1235   } else
1236     printBefore(T->getInnerType(), OS);
1237 }
1238 
1239 void TypePrinter::printParenAfter(const ParenType *T, raw_ostream &OS) {
1240   if (!HasEmptyPlaceHolder && !isa<FunctionType>(T->getInnerType())) {
1241     OS << ')';
1242     printAfter(T->getInnerType(), OS);
1243   } else
1244     printAfter(T->getInnerType(), OS);
1245 }
1246 
1247 void TypePrinter::printDependentNameBefore(const DependentNameType *T,
1248                                            raw_ostream &OS) {
1249   OS << TypeWithKeyword::getKeywordName(T->getKeyword());
1250   if (T->getKeyword() != ETK_None)
1251     OS << " ";
1252 
1253   T->getQualifier()->print(OS, Policy);
1254 
1255   OS << T->getIdentifier()->getName();
1256   spaceBeforePlaceHolder(OS);
1257 }
1258 
1259 void TypePrinter::printDependentNameAfter(const DependentNameType *T,
1260                                           raw_ostream &OS) {}
1261 
1262 void TypePrinter::printDependentTemplateSpecializationBefore(
1263         const DependentTemplateSpecializationType *T, raw_ostream &OS) {
1264   IncludeStrongLifetimeRAII Strong(Policy);
1265 
1266   OS << TypeWithKeyword::getKeywordName(T->getKeyword());
1267   if (T->getKeyword() != ETK_None)
1268     OS << " ";
1269 
1270   if (T->getQualifier())
1271     T->getQualifier()->print(OS, Policy);
1272   OS << T->getIdentifier()->getName();
1273   printTemplateArgumentList(OS, T->template_arguments(), Policy);
1274   spaceBeforePlaceHolder(OS);
1275 }
1276 
1277 void TypePrinter::printDependentTemplateSpecializationAfter(
1278         const DependentTemplateSpecializationType *T, raw_ostream &OS) {}
1279 
1280 void TypePrinter::printPackExpansionBefore(const PackExpansionType *T,
1281                                            raw_ostream &OS) {
1282   printBefore(T->getPattern(), OS);
1283 }
1284 
1285 void TypePrinter::printPackExpansionAfter(const PackExpansionType *T,
1286                                           raw_ostream &OS) {
1287   printAfter(T->getPattern(), OS);
1288   OS << "...";
1289 }
1290 
1291 void TypePrinter::printAttributedBefore(const AttributedType *T,
1292                                         raw_ostream &OS) {
1293   // Prefer the macro forms of the GC and ownership qualifiers.
1294   if (T->getAttrKind() == AttributedType::attr_objc_gc ||
1295       T->getAttrKind() == AttributedType::attr_objc_ownership)
1296     return printBefore(T->getEquivalentType(), OS);
1297 
1298   if (T->getAttrKind() == AttributedType::attr_objc_kindof)
1299     OS << "__kindof ";
1300 
1301   printBefore(T->getModifiedType(), OS);
1302 
1303   if (T->isMSTypeSpec()) {
1304     switch (T->getAttrKind()) {
1305     default: return;
1306     case AttributedType::attr_ptr32: OS << " __ptr32"; break;
1307     case AttributedType::attr_ptr64: OS << " __ptr64"; break;
1308     case AttributedType::attr_sptr: OS << " __sptr"; break;
1309     case AttributedType::attr_uptr: OS << " __uptr"; break;
1310     }
1311     spaceBeforePlaceHolder(OS);
1312   }
1313 
1314   // Print nullability type specifiers.
1315   if (T->getAttrKind() == AttributedType::attr_nonnull ||
1316       T->getAttrKind() == AttributedType::attr_nullable ||
1317       T->getAttrKind() == AttributedType::attr_null_unspecified) {
1318     if (T->getAttrKind() == AttributedType::attr_nonnull)
1319       OS << " _Nonnull";
1320     else if (T->getAttrKind() == AttributedType::attr_nullable)
1321       OS << " _Nullable";
1322     else if (T->getAttrKind() == AttributedType::attr_null_unspecified)
1323       OS << " _Null_unspecified";
1324     else
1325       llvm_unreachable("unhandled nullability");
1326     spaceBeforePlaceHolder(OS);
1327   }
1328 }
1329 
1330 void TypePrinter::printAttributedAfter(const AttributedType *T,
1331                                        raw_ostream &OS) {
1332   // Prefer the macro forms of the GC and ownership qualifiers.
1333   if (T->getAttrKind() == AttributedType::attr_objc_gc ||
1334       T->getAttrKind() == AttributedType::attr_objc_ownership)
1335     return printAfter(T->getEquivalentType(), OS);
1336 
1337   if (T->getAttrKind() == AttributedType::attr_objc_kindof)
1338     return;
1339 
1340   // TODO: not all attributes are GCC-style attributes.
1341   if (T->isMSTypeSpec())
1342     return;
1343 
1344   // Nothing to print after.
1345   if (T->getAttrKind() == AttributedType::attr_nonnull ||
1346       T->getAttrKind() == AttributedType::attr_nullable ||
1347       T->getAttrKind() == AttributedType::attr_null_unspecified)
1348     return printAfter(T->getModifiedType(), OS);
1349 
1350   // If this is a calling convention attribute, don't print the implicit CC from
1351   // the modified type.
1352   SaveAndRestore<bool> MaybeSuppressCC(InsideCCAttribute, T->isCallingConv());
1353 
1354   printAfter(T->getModifiedType(), OS);
1355 
1356   // Don't print the inert __unsafe_unretained attribute at all.
1357   if (T->getAttrKind() == AttributedType::attr_objc_inert_unsafe_unretained)
1358     return;
1359 
1360   // Don't print ns_returns_retained unless it had an effect.
1361   if (T->getAttrKind() == AttributedType::attr_ns_returns_retained &&
1362       !T->getEquivalentType()->castAs<FunctionType>()
1363                              ->getExtInfo().getProducesResult())
1364     return;
1365 
1366   // Print nullability type specifiers that occur after
1367   if (T->getAttrKind() == AttributedType::attr_nonnull ||
1368       T->getAttrKind() == AttributedType::attr_nullable ||
1369       T->getAttrKind() == AttributedType::attr_null_unspecified) {
1370     if (T->getAttrKind() == AttributedType::attr_nonnull)
1371       OS << " _Nonnull";
1372     else if (T->getAttrKind() == AttributedType::attr_nullable)
1373       OS << " _Nullable";
1374     else if (T->getAttrKind() == AttributedType::attr_null_unspecified)
1375       OS << " _Null_unspecified";
1376     else
1377       llvm_unreachable("unhandled nullability");
1378 
1379     return;
1380   }
1381 
1382   OS << " __attribute__((";
1383   switch (T->getAttrKind()) {
1384   default: llvm_unreachable("This attribute should have been handled already");
1385   case AttributedType::attr_address_space:
1386     OS << "address_space(";
1387     // FIXME: printing the raw LangAS value is wrong. This should probably
1388     // use the same code as Qualifiers::print()
1389     OS << (unsigned)T->getEquivalentType().getAddressSpace();
1390     OS << ')';
1391     break;
1392 
1393   case AttributedType::attr_vector_size:
1394     OS << "__vector_size__(";
1395     if (const auto *vector = T->getEquivalentType()->getAs<VectorType>()) {
1396       OS << vector->getNumElements();
1397       OS << " * sizeof(";
1398       print(vector->getElementType(), OS, StringRef());
1399       OS << ')';
1400     }
1401     OS << ')';
1402     break;
1403 
1404   case AttributedType::attr_neon_vector_type:
1405   case AttributedType::attr_neon_polyvector_type: {
1406     if (T->getAttrKind() == AttributedType::attr_neon_vector_type)
1407       OS << "neon_vector_type(";
1408     else
1409       OS << "neon_polyvector_type(";
1410     const auto *vector = T->getEquivalentType()->getAs<VectorType>();
1411     OS << vector->getNumElements();
1412     OS << ')';
1413     break;
1414   }
1415 
1416   case AttributedType::attr_regparm: {
1417     // FIXME: When Sema learns to form this AttributedType, avoid printing the
1418     // attribute again in printFunctionProtoAfter.
1419     OS << "regparm(";
1420     QualType t = T->getEquivalentType();
1421     while (!t->isFunctionType())
1422       t = t->getPointeeType();
1423     OS << t->getAs<FunctionType>()->getRegParmType();
1424     OS << ')';
1425     break;
1426   }
1427 
1428   case AttributedType::attr_objc_gc: {
1429     OS << "objc_gc(";
1430 
1431     QualType tmp = T->getEquivalentType();
1432     while (tmp.getObjCGCAttr() == Qualifiers::GCNone) {
1433       QualType next = tmp->getPointeeType();
1434       if (next == tmp) break;
1435       tmp = next;
1436     }
1437 
1438     if (tmp.isObjCGCWeak())
1439       OS << "weak";
1440     else
1441       OS << "strong";
1442     OS << ')';
1443     break;
1444   }
1445 
1446   case AttributedType::attr_objc_ownership:
1447     OS << "objc_ownership(";
1448     switch (T->getEquivalentType().getObjCLifetime()) {
1449     case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
1450     case Qualifiers::OCL_ExplicitNone: OS << "none"; break;
1451     case Qualifiers::OCL_Strong: OS << "strong"; break;
1452     case Qualifiers::OCL_Weak: OS << "weak"; break;
1453     case Qualifiers::OCL_Autoreleasing: OS << "autoreleasing"; break;
1454     }
1455     OS << ')';
1456     break;
1457 
1458   case AttributedType::attr_ns_returns_retained:
1459     OS << "ns_returns_retained";
1460     break;
1461 
1462   // FIXME: When Sema learns to form this AttributedType, avoid printing the
1463   // attribute again in printFunctionProtoAfter.
1464   case AttributedType::attr_noreturn: OS << "noreturn"; break;
1465   case AttributedType::attr_nocf_check: OS << "nocf_check"; break;
1466   case AttributedType::attr_cdecl: OS << "cdecl"; break;
1467   case AttributedType::attr_fastcall: OS << "fastcall"; break;
1468   case AttributedType::attr_stdcall: OS << "stdcall"; break;
1469   case AttributedType::attr_thiscall: OS << "thiscall"; break;
1470   case AttributedType::attr_swiftcall: OS << "swiftcall"; break;
1471   case AttributedType::attr_vectorcall: OS << "vectorcall"; break;
1472   case AttributedType::attr_pascal: OS << "pascal"; break;
1473   case AttributedType::attr_ms_abi: OS << "ms_abi"; break;
1474   case AttributedType::attr_sysv_abi: OS << "sysv_abi"; break;
1475   case AttributedType::attr_regcall: OS << "regcall"; break;
1476   case AttributedType::attr_pcs:
1477   case AttributedType::attr_pcs_vfp: {
1478     OS << "pcs(";
1479    QualType t = T->getEquivalentType();
1480    while (!t->isFunctionType())
1481      t = t->getPointeeType();
1482    OS << (t->getAs<FunctionType>()->getCallConv() == CC_AAPCS ?
1483          "\"aapcs\"" : "\"aapcs-vfp\"");
1484    OS << ')';
1485    break;
1486   }
1487 
1488   case AttributedType::attr_inteloclbicc: OS << "inteloclbicc"; break;
1489   case AttributedType::attr_preserve_most:
1490     OS << "preserve_most";
1491     break;
1492 
1493   case AttributedType::attr_preserve_all:
1494     OS << "preserve_all";
1495     break;
1496   }
1497   OS << "))";
1498 }
1499 
1500 void TypePrinter::printObjCInterfaceBefore(const ObjCInterfaceType *T,
1501                                            raw_ostream &OS) {
1502   OS << T->getDecl()->getName();
1503   spaceBeforePlaceHolder(OS);
1504 }
1505 
1506 void TypePrinter::printObjCInterfaceAfter(const ObjCInterfaceType *T,
1507                                           raw_ostream &OS) {}
1508 
1509 void TypePrinter::printObjCTypeParamBefore(const ObjCTypeParamType *T,
1510                                           raw_ostream &OS) {
1511   OS << T->getDecl()->getName();
1512   if (!T->qual_empty()) {
1513     bool isFirst = true;
1514     OS << '<';
1515     for (const auto *I : T->quals()) {
1516       if (isFirst)
1517         isFirst = false;
1518       else
1519         OS << ',';
1520       OS << I->getName();
1521     }
1522     OS << '>';
1523   }
1524 
1525   spaceBeforePlaceHolder(OS);
1526 }
1527 
1528 void TypePrinter::printObjCTypeParamAfter(const ObjCTypeParamType *T,
1529                                           raw_ostream &OS) {}
1530 
1531 void TypePrinter::printObjCObjectBefore(const ObjCObjectType *T,
1532                                         raw_ostream &OS) {
1533   if (T->qual_empty() && T->isUnspecializedAsWritten() &&
1534       !T->isKindOfTypeAsWritten())
1535     return printBefore(T->getBaseType(), OS);
1536 
1537   if (T->isKindOfTypeAsWritten())
1538     OS << "__kindof ";
1539 
1540   print(T->getBaseType(), OS, StringRef());
1541 
1542   if (T->isSpecializedAsWritten()) {
1543     bool isFirst = true;
1544     OS << '<';
1545     for (auto typeArg : T->getTypeArgsAsWritten()) {
1546       if (isFirst)
1547         isFirst = false;
1548       else
1549         OS << ",";
1550 
1551       print(typeArg, OS, StringRef());
1552     }
1553     OS << '>';
1554   }
1555 
1556   if (!T->qual_empty()) {
1557     bool isFirst = true;
1558     OS << '<';
1559     for (const auto *I : T->quals()) {
1560       if (isFirst)
1561         isFirst = false;
1562       else
1563         OS << ',';
1564       OS << I->getName();
1565     }
1566     OS << '>';
1567   }
1568 
1569   spaceBeforePlaceHolder(OS);
1570 }
1571 
1572 void TypePrinter::printObjCObjectAfter(const ObjCObjectType *T,
1573                                         raw_ostream &OS) {
1574   if (T->qual_empty() && T->isUnspecializedAsWritten() &&
1575       !T->isKindOfTypeAsWritten())
1576     return printAfter(T->getBaseType(), OS);
1577 }
1578 
1579 void TypePrinter::printObjCObjectPointerBefore(const ObjCObjectPointerType *T,
1580                                                raw_ostream &OS) {
1581   printBefore(T->getPointeeType(), OS);
1582 
1583   // If we need to print the pointer, print it now.
1584   if (!T->isObjCIdType() && !T->isObjCQualifiedIdType() &&
1585       !T->isObjCClassType() && !T->isObjCQualifiedClassType()) {
1586     if (HasEmptyPlaceHolder)
1587       OS << ' ';
1588     OS << '*';
1589   }
1590 }
1591 
1592 void TypePrinter::printObjCObjectPointerAfter(const ObjCObjectPointerType *T,
1593                                               raw_ostream &OS) {}
1594 
1595 static
1596 const TemplateArgument &getArgument(const TemplateArgument &A) { return A; }
1597 
1598 static const TemplateArgument &getArgument(const TemplateArgumentLoc &A) {
1599   return A.getArgument();
1600 }
1601 
1602 template<typename TA>
1603 static void printTo(raw_ostream &OS, ArrayRef<TA> Args,
1604                     const PrintingPolicy &Policy, bool SkipBrackets) {
1605   const char *Comma = Policy.MSVCFormatting ? "," : ", ";
1606   if (!SkipBrackets)
1607     OS << '<';
1608 
1609   bool NeedSpace = false;
1610   bool FirstArg = true;
1611   for (const auto &Arg : Args) {
1612     // Print the argument into a string.
1613     SmallString<128> Buf;
1614     llvm::raw_svector_ostream ArgOS(Buf);
1615     const TemplateArgument &Argument = getArgument(Arg);
1616     if (Argument.getKind() == TemplateArgument::Pack) {
1617       if (Argument.pack_size() && !FirstArg)
1618         OS << Comma;
1619       printTo(ArgOS, Argument.getPackAsArray(), Policy, true);
1620     } else {
1621       if (!FirstArg)
1622         OS << Comma;
1623       Argument.print(Policy, ArgOS);
1624     }
1625     StringRef ArgString = ArgOS.str();
1626 
1627     // If this is the first argument and its string representation
1628     // begins with the global scope specifier ('::foo'), add a space
1629     // to avoid printing the diagraph '<:'.
1630     if (FirstArg && !ArgString.empty() && ArgString[0] == ':')
1631       OS << ' ';
1632 
1633     OS << ArgString;
1634 
1635     NeedSpace = (!ArgString.empty() && ArgString.back() == '>');
1636     FirstArg = false;
1637   }
1638 
1639   // If the last character of our string is '>', add another space to
1640   // keep the two '>''s separate tokens. We don't *have* to do this in
1641   // C++0x, but it's still good hygiene.
1642   if (NeedSpace)
1643     OS << ' ';
1644 
1645   if (!SkipBrackets)
1646     OS << '>';
1647 }
1648 
1649 void clang::printTemplateArgumentList(raw_ostream &OS,
1650                                       const TemplateArgumentListInfo &Args,
1651                                       const PrintingPolicy &Policy) {
1652   return printTo(OS, Args.arguments(), Policy, false);
1653 }
1654 
1655 void clang::printTemplateArgumentList(raw_ostream &OS,
1656                                       ArrayRef<TemplateArgument> Args,
1657                                       const PrintingPolicy &Policy) {
1658   printTo(OS, Args, Policy, false);
1659 }
1660 
1661 void clang::printTemplateArgumentList(raw_ostream &OS,
1662                                       ArrayRef<TemplateArgumentLoc> Args,
1663                                       const PrintingPolicy &Policy) {
1664   printTo(OS, Args, Policy, false);
1665 }
1666 
1667 std::string Qualifiers::getAsString() const {
1668   LangOptions LO;
1669   return getAsString(PrintingPolicy(LO));
1670 }
1671 
1672 // Appends qualifiers to the given string, separated by spaces.  Will
1673 // prefix a space if the string is non-empty.  Will not append a final
1674 // space.
1675 std::string Qualifiers::getAsString(const PrintingPolicy &Policy) const {
1676   SmallString<64> Buf;
1677   llvm::raw_svector_ostream StrOS(Buf);
1678   print(StrOS, Policy);
1679   return StrOS.str();
1680 }
1681 
1682 bool Qualifiers::isEmptyWhenPrinted(const PrintingPolicy &Policy) const {
1683   if (getCVRQualifiers())
1684     return false;
1685 
1686   if (getAddressSpace() != LangAS::Default)
1687     return false;
1688 
1689   if (getObjCGCAttr())
1690     return false;
1691 
1692   if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime())
1693     if (!(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime))
1694       return false;
1695 
1696   return true;
1697 }
1698 
1699 // Appends qualifiers to the given string, separated by spaces.  Will
1700 // prefix a space if the string is non-empty.  Will not append a final
1701 // space.
1702 void Qualifiers::print(raw_ostream &OS, const PrintingPolicy& Policy,
1703                        bool appendSpaceIfNonEmpty) const {
1704   bool addSpace = false;
1705 
1706   unsigned quals = getCVRQualifiers();
1707   if (quals) {
1708     AppendTypeQualList(OS, quals, Policy.Restrict);
1709     addSpace = true;
1710   }
1711   if (hasUnaligned()) {
1712     if (addSpace)
1713       OS << ' ';
1714     OS << "__unaligned";
1715     addSpace = true;
1716   }
1717   LangAS addrspace = getAddressSpace();
1718   if (addrspace != LangAS::Default) {
1719     if (addrspace != LangAS::opencl_private) {
1720       if (addSpace)
1721         OS << ' ';
1722       addSpace = true;
1723       switch (addrspace) {
1724       case LangAS::opencl_global:
1725         OS << "__global";
1726         break;
1727       case LangAS::opencl_local:
1728         OS << "__local";
1729         break;
1730       case LangAS::opencl_private:
1731         break;
1732       case LangAS::opencl_constant:
1733       case LangAS::cuda_constant:
1734         OS << "__constant";
1735         break;
1736       case LangAS::opencl_generic:
1737         OS << "__generic";
1738         break;
1739       case LangAS::cuda_device:
1740         OS << "__device";
1741         break;
1742       case LangAS::cuda_shared:
1743         OS << "__shared";
1744         break;
1745       default:
1746         OS << "__attribute__((address_space(";
1747         OS << toTargetAddressSpace(addrspace);
1748         OS << ")))";
1749       }
1750     }
1751   }
1752   if (Qualifiers::GC gc = getObjCGCAttr()) {
1753     if (addSpace)
1754       OS << ' ';
1755     addSpace = true;
1756     if (gc == Qualifiers::Weak)
1757       OS << "__weak";
1758     else
1759       OS << "__strong";
1760   }
1761   if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime()) {
1762     if (!(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime)){
1763       if (addSpace)
1764         OS << ' ';
1765       addSpace = true;
1766     }
1767 
1768     switch (lifetime) {
1769     case Qualifiers::OCL_None: llvm_unreachable("none but true");
1770     case Qualifiers::OCL_ExplicitNone: OS << "__unsafe_unretained"; break;
1771     case Qualifiers::OCL_Strong:
1772       if (!Policy.SuppressStrongLifetime)
1773         OS << "__strong";
1774       break;
1775 
1776     case Qualifiers::OCL_Weak: OS << "__weak"; break;
1777     case Qualifiers::OCL_Autoreleasing: OS << "__autoreleasing"; break;
1778     }
1779   }
1780 
1781   if (appendSpaceIfNonEmpty && addSpace)
1782     OS << ' ';
1783 }
1784 
1785 std::string QualType::getAsString() const {
1786   return getAsString(split(), LangOptions());
1787 }
1788 
1789 std::string QualType::getAsString(const PrintingPolicy &Policy) const {
1790   std::string S;
1791   getAsStringInternal(S, Policy);
1792   return S;
1793 }
1794 
1795 std::string QualType::getAsString(const Type *ty, Qualifiers qs,
1796                                   const PrintingPolicy &Policy) {
1797   std::string buffer;
1798   getAsStringInternal(ty, qs, buffer, Policy);
1799   return buffer;
1800 }
1801 
1802 void QualType::print(const Type *ty, Qualifiers qs,
1803                      raw_ostream &OS, const PrintingPolicy &policy,
1804                      const Twine &PlaceHolder, unsigned Indentation) {
1805   SmallString<128> PHBuf;
1806   StringRef PH = PlaceHolder.toStringRef(PHBuf);
1807 
1808   TypePrinter(policy, Indentation).print(ty, qs, OS, PH);
1809 }
1810 
1811 void QualType::getAsStringInternal(const Type *ty, Qualifiers qs,
1812                                    std::string &buffer,
1813                                    const PrintingPolicy &policy) {
1814   SmallString<256> Buf;
1815   llvm::raw_svector_ostream StrOS(Buf);
1816   TypePrinter(policy).print(ty, qs, StrOS, buffer);
1817   std::string str = StrOS.str();
1818   buffer.swap(str);
1819 }
1820