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