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   print(T->getElementType(), OS, StringRef());
900   spaceBeforePlaceHolder(OS);
901 }
902 
903 void TypePrinter::printPipeAfter(const PipeType *T, raw_ostream &OS) {
904 }
905 /// Appends the given scope to the end of a string.
906 void TypePrinter::AppendScope(DeclContext *DC, raw_ostream &OS) {
907   if (DC->isTranslationUnit()) return;
908   if (DC->isFunctionOrMethod()) return;
909   AppendScope(DC->getParent(), OS);
910 
911   if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(DC)) {
912     if (Policy.SuppressUnwrittenScope &&
913         (NS->isAnonymousNamespace() || NS->isInline()))
914       return;
915     if (NS->getIdentifier())
916       OS << NS->getName() << "::";
917     else
918       OS << "(anonymous namespace)::";
919   } else if (ClassTemplateSpecializationDecl *Spec
920                = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
921     IncludeStrongLifetimeRAII Strong(Policy);
922     OS << Spec->getIdentifier()->getName();
923     const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
924     TemplateSpecializationType::PrintTemplateArgumentList(OS,
925                                             TemplateArgs.data(),
926                                             TemplateArgs.size(),
927                                             Policy);
928     OS << "::";
929   } else if (TagDecl *Tag = dyn_cast<TagDecl>(DC)) {
930     if (TypedefNameDecl *Typedef = Tag->getTypedefNameForAnonDecl())
931       OS << Typedef->getIdentifier()->getName() << "::";
932     else if (Tag->getIdentifier())
933       OS << Tag->getIdentifier()->getName() << "::";
934     else
935       return;
936   }
937 }
938 
939 void TypePrinter::printTag(TagDecl *D, raw_ostream &OS) {
940   if (Policy.IncludeTagDefinition) {
941     PrintingPolicy SubPolicy = Policy;
942     SubPolicy.IncludeTagDefinition = false;
943     D->print(OS, SubPolicy, Indentation);
944     spaceBeforePlaceHolder(OS);
945     return;
946   }
947 
948   bool HasKindDecoration = false;
949 
950   // bool SuppressTagKeyword
951   //   = Policy.LangOpts.CPlusPlus || Policy.SuppressTagKeyword;
952 
953   // We don't print tags unless this is an elaborated type.
954   // In C, we just assume every RecordType is an elaborated type.
955   if (!(Policy.LangOpts.CPlusPlus || Policy.SuppressTagKeyword ||
956         D->getTypedefNameForAnonDecl())) {
957     HasKindDecoration = true;
958     OS << D->getKindName();
959     OS << ' ';
960   }
961 
962   // Compute the full nested-name-specifier for this type.
963   // In C, this will always be empty except when the type
964   // being printed is anonymous within other Record.
965   if (!Policy.SuppressScope)
966     AppendScope(D->getDeclContext(), OS);
967 
968   if (const IdentifierInfo *II = D->getIdentifier())
969     OS << II->getName();
970   else if (TypedefNameDecl *Typedef = D->getTypedefNameForAnonDecl()) {
971     assert(Typedef->getIdentifier() && "Typedef without identifier?");
972     OS << Typedef->getIdentifier()->getName();
973   } else {
974     // Make an unambiguous representation for anonymous types, e.g.
975     //   (anonymous enum at /usr/include/string.h:120:9)
976     OS << (Policy.MSVCFormatting ? '`' : '(');
977 
978     if (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda()) {
979       OS << "lambda";
980       HasKindDecoration = true;
981     } else {
982       OS << "anonymous";
983     }
984 
985     if (Policy.AnonymousTagLocations) {
986       // Suppress the redundant tag keyword if we just printed one.
987       // We don't have to worry about ElaboratedTypes here because you can't
988       // refer to an anonymous type with one.
989       if (!HasKindDecoration)
990         OS << " " << D->getKindName();
991 
992       PresumedLoc PLoc = D->getASTContext().getSourceManager().getPresumedLoc(
993           D->getLocation());
994       if (PLoc.isValid()) {
995         OS << " at " << PLoc.getFilename()
996            << ':' << PLoc.getLine()
997            << ':' << PLoc.getColumn();
998       }
999     }
1000 
1001     OS << (Policy.MSVCFormatting ? '\'' : ')');
1002   }
1003 
1004   // If this is a class template specialization, print the template
1005   // arguments.
1006   if (ClassTemplateSpecializationDecl *Spec
1007         = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
1008     const TemplateArgument *Args;
1009     unsigned NumArgs;
1010     if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
1011       const TemplateSpecializationType *TST =
1012         cast<TemplateSpecializationType>(TAW->getType());
1013       Args = TST->getArgs();
1014       NumArgs = TST->getNumArgs();
1015     } else {
1016       const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1017       Args = TemplateArgs.data();
1018       NumArgs = TemplateArgs.size();
1019     }
1020     IncludeStrongLifetimeRAII Strong(Policy);
1021     TemplateSpecializationType::PrintTemplateArgumentList(OS,
1022                                                           Args, NumArgs,
1023                                                           Policy);
1024   }
1025 
1026   spaceBeforePlaceHolder(OS);
1027 }
1028 
1029 void TypePrinter::printRecordBefore(const RecordType *T, raw_ostream &OS) {
1030   printTag(T->getDecl(), OS);
1031 }
1032 void TypePrinter::printRecordAfter(const RecordType *T, raw_ostream &OS) { }
1033 
1034 void TypePrinter::printEnumBefore(const EnumType *T, raw_ostream &OS) {
1035   printTag(T->getDecl(), OS);
1036 }
1037 void TypePrinter::printEnumAfter(const EnumType *T, raw_ostream &OS) { }
1038 
1039 void TypePrinter::printTemplateTypeParmBefore(const TemplateTypeParmType *T,
1040                                               raw_ostream &OS) {
1041   if (IdentifierInfo *Id = T->getIdentifier())
1042     OS << Id->getName();
1043   else
1044     OS << "type-parameter-" << T->getDepth() << '-' << T->getIndex();
1045   spaceBeforePlaceHolder(OS);
1046 }
1047 void TypePrinter::printTemplateTypeParmAfter(const TemplateTypeParmType *T,
1048                                              raw_ostream &OS) { }
1049 
1050 void TypePrinter::printSubstTemplateTypeParmBefore(
1051                                              const SubstTemplateTypeParmType *T,
1052                                              raw_ostream &OS) {
1053   IncludeStrongLifetimeRAII Strong(Policy);
1054   printBefore(T->getReplacementType(), OS);
1055 }
1056 void TypePrinter::printSubstTemplateTypeParmAfter(
1057                                              const SubstTemplateTypeParmType *T,
1058                                              raw_ostream &OS) {
1059   IncludeStrongLifetimeRAII Strong(Policy);
1060   printAfter(T->getReplacementType(), OS);
1061 }
1062 
1063 void TypePrinter::printSubstTemplateTypeParmPackBefore(
1064                                         const SubstTemplateTypeParmPackType *T,
1065                                         raw_ostream &OS) {
1066   IncludeStrongLifetimeRAII Strong(Policy);
1067   printTemplateTypeParmBefore(T->getReplacedParameter(), OS);
1068 }
1069 void TypePrinter::printSubstTemplateTypeParmPackAfter(
1070                                         const SubstTemplateTypeParmPackType *T,
1071                                         raw_ostream &OS) {
1072   IncludeStrongLifetimeRAII Strong(Policy);
1073   printTemplateTypeParmAfter(T->getReplacedParameter(), OS);
1074 }
1075 
1076 void TypePrinter::printTemplateSpecializationBefore(
1077                                             const TemplateSpecializationType *T,
1078                                             raw_ostream &OS) {
1079   IncludeStrongLifetimeRAII Strong(Policy);
1080   T->getTemplateName().print(OS, Policy);
1081 
1082   TemplateSpecializationType::PrintTemplateArgumentList(OS,
1083                                                         T->getArgs(),
1084                                                         T->getNumArgs(),
1085                                                         Policy);
1086   spaceBeforePlaceHolder(OS);
1087 }
1088 void TypePrinter::printTemplateSpecializationAfter(
1089                                             const TemplateSpecializationType *T,
1090                                             raw_ostream &OS) { }
1091 
1092 void TypePrinter::printInjectedClassNameBefore(const InjectedClassNameType *T,
1093                                                raw_ostream &OS) {
1094   printTemplateSpecializationBefore(T->getInjectedTST(), OS);
1095 }
1096 void TypePrinter::printInjectedClassNameAfter(const InjectedClassNameType *T,
1097                                                raw_ostream &OS) { }
1098 
1099 void TypePrinter::printElaboratedBefore(const ElaboratedType *T,
1100                                         raw_ostream &OS) {
1101   // The tag definition will take care of these.
1102   if (!Policy.IncludeTagDefinition)
1103   {
1104     OS << TypeWithKeyword::getKeywordName(T->getKeyword());
1105     if (T->getKeyword() != ETK_None)
1106       OS << " ";
1107     NestedNameSpecifier* Qualifier = T->getQualifier();
1108     if (Qualifier)
1109       Qualifier->print(OS, Policy);
1110   }
1111 
1112   ElaboratedTypePolicyRAII PolicyRAII(Policy);
1113   printBefore(T->getNamedType(), OS);
1114 }
1115 void TypePrinter::printElaboratedAfter(const ElaboratedType *T,
1116                                         raw_ostream &OS) {
1117   ElaboratedTypePolicyRAII PolicyRAII(Policy);
1118   printAfter(T->getNamedType(), OS);
1119 }
1120 
1121 void TypePrinter::printParenBefore(const ParenType *T, raw_ostream &OS) {
1122   if (!HasEmptyPlaceHolder && !isa<FunctionType>(T->getInnerType())) {
1123     printBefore(T->getInnerType(), OS);
1124     OS << '(';
1125   } else
1126     printBefore(T->getInnerType(), OS);
1127 }
1128 void TypePrinter::printParenAfter(const ParenType *T, raw_ostream &OS) {
1129   if (!HasEmptyPlaceHolder && !isa<FunctionType>(T->getInnerType())) {
1130     OS << ')';
1131     printAfter(T->getInnerType(), OS);
1132   } else
1133     printAfter(T->getInnerType(), OS);
1134 }
1135 
1136 void TypePrinter::printDependentNameBefore(const DependentNameType *T,
1137                                            raw_ostream &OS) {
1138   OS << TypeWithKeyword::getKeywordName(T->getKeyword());
1139   if (T->getKeyword() != ETK_None)
1140     OS << " ";
1141 
1142   T->getQualifier()->print(OS, Policy);
1143 
1144   OS << T->getIdentifier()->getName();
1145   spaceBeforePlaceHolder(OS);
1146 }
1147 void TypePrinter::printDependentNameAfter(const DependentNameType *T,
1148                                           raw_ostream &OS) { }
1149 
1150 void TypePrinter::printDependentTemplateSpecializationBefore(
1151         const DependentTemplateSpecializationType *T, raw_ostream &OS) {
1152   IncludeStrongLifetimeRAII Strong(Policy);
1153 
1154   OS << TypeWithKeyword::getKeywordName(T->getKeyword());
1155   if (T->getKeyword() != ETK_None)
1156     OS << " ";
1157 
1158   if (T->getQualifier())
1159     T->getQualifier()->print(OS, Policy);
1160   OS << T->getIdentifier()->getName();
1161   TemplateSpecializationType::PrintTemplateArgumentList(OS,
1162                                                         T->getArgs(),
1163                                                         T->getNumArgs(),
1164                                                         Policy);
1165   spaceBeforePlaceHolder(OS);
1166 }
1167 void TypePrinter::printDependentTemplateSpecializationAfter(
1168         const DependentTemplateSpecializationType *T, raw_ostream &OS) { }
1169 
1170 void TypePrinter::printPackExpansionBefore(const PackExpansionType *T,
1171                                            raw_ostream &OS) {
1172   printBefore(T->getPattern(), OS);
1173 }
1174 void TypePrinter::printPackExpansionAfter(const PackExpansionType *T,
1175                                           raw_ostream &OS) {
1176   printAfter(T->getPattern(), OS);
1177   OS << "...";
1178 }
1179 
1180 void TypePrinter::printAttributedBefore(const AttributedType *T,
1181                                         raw_ostream &OS) {
1182   // Prefer the macro forms of the GC and ownership qualifiers.
1183   if (T->getAttrKind() == AttributedType::attr_objc_gc ||
1184       T->getAttrKind() == AttributedType::attr_objc_ownership)
1185     return printBefore(T->getEquivalentType(), OS);
1186 
1187   if (T->getAttrKind() == AttributedType::attr_objc_kindof)
1188     OS << "__kindof ";
1189 
1190   printBefore(T->getModifiedType(), OS);
1191 
1192   if (T->isMSTypeSpec()) {
1193     switch (T->getAttrKind()) {
1194     default: return;
1195     case AttributedType::attr_ptr32: OS << " __ptr32"; break;
1196     case AttributedType::attr_ptr64: OS << " __ptr64"; break;
1197     case AttributedType::attr_sptr: OS << " __sptr"; break;
1198     case AttributedType::attr_uptr: OS << " __uptr"; break;
1199     }
1200     spaceBeforePlaceHolder(OS);
1201   }
1202 
1203   // Print nullability type specifiers.
1204   if (T->getAttrKind() == AttributedType::attr_nonnull ||
1205       T->getAttrKind() == AttributedType::attr_nullable ||
1206       T->getAttrKind() == AttributedType::attr_null_unspecified) {
1207     if (T->getAttrKind() == AttributedType::attr_nonnull)
1208       OS << " _Nonnull";
1209     else if (T->getAttrKind() == AttributedType::attr_nullable)
1210       OS << " _Nullable";
1211     else if (T->getAttrKind() == AttributedType::attr_null_unspecified)
1212       OS << " _Null_unspecified";
1213     else
1214       llvm_unreachable("unhandled nullability");
1215     spaceBeforePlaceHolder(OS);
1216   }
1217 }
1218 
1219 void TypePrinter::printAttributedAfter(const AttributedType *T,
1220                                        raw_ostream &OS) {
1221   // Prefer the macro forms of the GC and ownership qualifiers.
1222   if (T->getAttrKind() == AttributedType::attr_objc_gc ||
1223       T->getAttrKind() == AttributedType::attr_objc_ownership)
1224     return printAfter(T->getEquivalentType(), OS);
1225 
1226   if (T->getAttrKind() == AttributedType::attr_objc_kindof)
1227     return;
1228 
1229   // TODO: not all attributes are GCC-style attributes.
1230   if (T->isMSTypeSpec())
1231     return;
1232 
1233   // Nothing to print after.
1234   if (T->getAttrKind() == AttributedType::attr_nonnull ||
1235       T->getAttrKind() == AttributedType::attr_nullable ||
1236       T->getAttrKind() == AttributedType::attr_null_unspecified)
1237     return printAfter(T->getModifiedType(), OS);
1238 
1239   // If this is a calling convention attribute, don't print the implicit CC from
1240   // the modified type.
1241   SaveAndRestore<bool> MaybeSuppressCC(InsideCCAttribute, T->isCallingConv());
1242 
1243   printAfter(T->getModifiedType(), OS);
1244 
1245   // Don't print the inert __unsafe_unretained attribute at all.
1246   if (T->getAttrKind() == AttributedType::attr_objc_inert_unsafe_unretained)
1247     return;
1248 
1249   // Print nullability type specifiers that occur after
1250   if (T->getAttrKind() == AttributedType::attr_nonnull ||
1251       T->getAttrKind() == AttributedType::attr_nullable ||
1252       T->getAttrKind() == AttributedType::attr_null_unspecified) {
1253     if (T->getAttrKind() == AttributedType::attr_nonnull)
1254       OS << " _Nonnull";
1255     else if (T->getAttrKind() == AttributedType::attr_nullable)
1256       OS << " _Nullable";
1257     else if (T->getAttrKind() == AttributedType::attr_null_unspecified)
1258       OS << " _Null_unspecified";
1259     else
1260       llvm_unreachable("unhandled nullability");
1261 
1262     return;
1263   }
1264 
1265   OS << " __attribute__((";
1266   switch (T->getAttrKind()) {
1267   default: llvm_unreachable("This attribute should have been handled already");
1268   case AttributedType::attr_address_space:
1269     OS << "address_space(";
1270     OS << T->getEquivalentType().getAddressSpace();
1271     OS << ')';
1272     break;
1273 
1274   case AttributedType::attr_vector_size: {
1275     OS << "__vector_size__(";
1276     if (const VectorType *vector =T->getEquivalentType()->getAs<VectorType>()) {
1277       OS << vector->getNumElements();
1278       OS << " * sizeof(";
1279       print(vector->getElementType(), OS, StringRef());
1280       OS << ')';
1281     }
1282     OS << ')';
1283     break;
1284   }
1285 
1286   case AttributedType::attr_neon_vector_type:
1287   case AttributedType::attr_neon_polyvector_type: {
1288     if (T->getAttrKind() == AttributedType::attr_neon_vector_type)
1289       OS << "neon_vector_type(";
1290     else
1291       OS << "neon_polyvector_type(";
1292     const VectorType *vector = T->getEquivalentType()->getAs<VectorType>();
1293     OS << vector->getNumElements();
1294     OS << ')';
1295     break;
1296   }
1297 
1298   case AttributedType::attr_regparm: {
1299     // FIXME: When Sema learns to form this AttributedType, avoid printing the
1300     // attribute again in printFunctionProtoAfter.
1301     OS << "regparm(";
1302     QualType t = T->getEquivalentType();
1303     while (!t->isFunctionType())
1304       t = t->getPointeeType();
1305     OS << t->getAs<FunctionType>()->getRegParmType();
1306     OS << ')';
1307     break;
1308   }
1309 
1310   case AttributedType::attr_objc_gc: {
1311     OS << "objc_gc(";
1312 
1313     QualType tmp = T->getEquivalentType();
1314     while (tmp.getObjCGCAttr() == Qualifiers::GCNone) {
1315       QualType next = tmp->getPointeeType();
1316       if (next == tmp) break;
1317       tmp = next;
1318     }
1319 
1320     if (tmp.isObjCGCWeak())
1321       OS << "weak";
1322     else
1323       OS << "strong";
1324     OS << ')';
1325     break;
1326   }
1327 
1328   case AttributedType::attr_objc_ownership:
1329     OS << "objc_ownership(";
1330     switch (T->getEquivalentType().getObjCLifetime()) {
1331     case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
1332     case Qualifiers::OCL_ExplicitNone: OS << "none"; break;
1333     case Qualifiers::OCL_Strong: OS << "strong"; break;
1334     case Qualifiers::OCL_Weak: OS << "weak"; break;
1335     case Qualifiers::OCL_Autoreleasing: OS << "autoreleasing"; break;
1336     }
1337     OS << ')';
1338     break;
1339 
1340   // FIXME: When Sema learns to form this AttributedType, avoid printing the
1341   // attribute again in printFunctionProtoAfter.
1342   case AttributedType::attr_noreturn: OS << "noreturn"; break;
1343 
1344   case AttributedType::attr_cdecl: OS << "cdecl"; break;
1345   case AttributedType::attr_fastcall: OS << "fastcall"; break;
1346   case AttributedType::attr_stdcall: OS << "stdcall"; break;
1347   case AttributedType::attr_thiscall: OS << "thiscall"; break;
1348   case AttributedType::attr_swiftcall: OS << "swiftcall"; break;
1349   case AttributedType::attr_vectorcall: OS << "vectorcall"; break;
1350   case AttributedType::attr_pascal: OS << "pascal"; break;
1351   case AttributedType::attr_ms_abi: OS << "ms_abi"; break;
1352   case AttributedType::attr_sysv_abi: OS << "sysv_abi"; break;
1353   case AttributedType::attr_pcs:
1354   case AttributedType::attr_pcs_vfp: {
1355     OS << "pcs(";
1356    QualType t = T->getEquivalentType();
1357    while (!t->isFunctionType())
1358      t = t->getPointeeType();
1359    OS << (t->getAs<FunctionType>()->getCallConv() == CC_AAPCS ?
1360          "\"aapcs\"" : "\"aapcs-vfp\"");
1361    OS << ')';
1362    break;
1363   }
1364   case AttributedType::attr_inteloclbicc: OS << "inteloclbicc"; break;
1365   case AttributedType::attr_preserve_most:
1366     OS << "preserve_most";
1367     break;
1368   case AttributedType::attr_preserve_all:
1369     OS << "preserve_all";
1370     break;
1371   }
1372   OS << "))";
1373 }
1374 
1375 void TypePrinter::printObjCInterfaceBefore(const ObjCInterfaceType *T,
1376                                            raw_ostream &OS) {
1377   OS << T->getDecl()->getName();
1378   spaceBeforePlaceHolder(OS);
1379 }
1380 void TypePrinter::printObjCInterfaceAfter(const ObjCInterfaceType *T,
1381                                           raw_ostream &OS) { }
1382 
1383 void TypePrinter::printObjCObjectBefore(const ObjCObjectType *T,
1384                                         raw_ostream &OS) {
1385   if (T->qual_empty() && T->isUnspecializedAsWritten() &&
1386       !T->isKindOfTypeAsWritten())
1387     return printBefore(T->getBaseType(), OS);
1388 
1389   if (T->isKindOfTypeAsWritten())
1390     OS << "__kindof ";
1391 
1392   print(T->getBaseType(), OS, StringRef());
1393 
1394   if (T->isSpecializedAsWritten()) {
1395     bool isFirst = true;
1396     OS << '<';
1397     for (auto typeArg : T->getTypeArgsAsWritten()) {
1398       if (isFirst)
1399         isFirst = false;
1400       else
1401         OS << ",";
1402 
1403       print(typeArg, OS, StringRef());
1404     }
1405     OS << '>';
1406   }
1407 
1408   if (!T->qual_empty()) {
1409     bool isFirst = true;
1410     OS << '<';
1411     for (const auto *I : T->quals()) {
1412       if (isFirst)
1413         isFirst = false;
1414       else
1415         OS << ',';
1416       OS << I->getName();
1417     }
1418     OS << '>';
1419   }
1420 
1421   spaceBeforePlaceHolder(OS);
1422 }
1423 void TypePrinter::printObjCObjectAfter(const ObjCObjectType *T,
1424                                         raw_ostream &OS) {
1425   if (T->qual_empty() && T->isUnspecializedAsWritten() &&
1426       !T->isKindOfTypeAsWritten())
1427     return printAfter(T->getBaseType(), OS);
1428 }
1429 
1430 void TypePrinter::printObjCObjectPointerBefore(const ObjCObjectPointerType *T,
1431                                                raw_ostream &OS) {
1432   printBefore(T->getPointeeType(), OS);
1433 
1434   // If we need to print the pointer, print it now.
1435   if (!T->isObjCIdType() && !T->isObjCQualifiedIdType() &&
1436       !T->isObjCClassType() && !T->isObjCQualifiedClassType()) {
1437     if (HasEmptyPlaceHolder)
1438       OS << ' ';
1439     OS << '*';
1440   }
1441 }
1442 void TypePrinter::printObjCObjectPointerAfter(const ObjCObjectPointerType *T,
1443                                               raw_ostream &OS) { }
1444 
1445 void TemplateSpecializationType::
1446   PrintTemplateArgumentList(raw_ostream &OS,
1447                             const TemplateArgumentListInfo &Args,
1448                             const PrintingPolicy &Policy) {
1449   return PrintTemplateArgumentList(OS,
1450                                    Args.getArgumentArray(),
1451                                    Args.size(),
1452                                    Policy);
1453 }
1454 
1455 void
1456 TemplateSpecializationType::PrintTemplateArgumentList(
1457                                                 raw_ostream &OS,
1458                                                 const TemplateArgument *Args,
1459                                                 unsigned NumArgs,
1460                                                   const PrintingPolicy &Policy,
1461                                                       bool SkipBrackets) {
1462   const char *Comma = Policy.MSVCFormatting ? "," : ", ";
1463   if (!SkipBrackets)
1464     OS << '<';
1465 
1466   bool needSpace = false;
1467   for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1468     // Print the argument into a string.
1469     SmallString<128> Buf;
1470     llvm::raw_svector_ostream ArgOS(Buf);
1471     if (Args[Arg].getKind() == TemplateArgument::Pack) {
1472       if (Args[Arg].pack_size() && Arg > 0)
1473         OS << Comma;
1474       PrintTemplateArgumentList(ArgOS,
1475                                 Args[Arg].pack_begin(),
1476                                 Args[Arg].pack_size(),
1477                                 Policy, true);
1478     } else {
1479       if (Arg > 0)
1480         OS << Comma;
1481       Args[Arg].print(Policy, ArgOS);
1482     }
1483     StringRef ArgString = ArgOS.str();
1484 
1485     // If this is the first argument and its string representation
1486     // begins with the global scope specifier ('::foo'), add a space
1487     // to avoid printing the diagraph '<:'.
1488     if (!Arg && !ArgString.empty() && ArgString[0] == ':')
1489       OS << ' ';
1490 
1491     OS << ArgString;
1492 
1493     needSpace = (!ArgString.empty() && ArgString.back() == '>');
1494   }
1495 
1496   // If the last character of our string is '>', add another space to
1497   // keep the two '>''s separate tokens. We don't *have* to do this in
1498   // C++0x, but it's still good hygiene.
1499   if (needSpace)
1500     OS << ' ';
1501 
1502   if (!SkipBrackets)
1503     OS << '>';
1504 }
1505 
1506 // Sadly, repeat all that with TemplateArgLoc.
1507 void TemplateSpecializationType::
1508 PrintTemplateArgumentList(raw_ostream &OS,
1509                           const TemplateArgumentLoc *Args, unsigned NumArgs,
1510                           const PrintingPolicy &Policy) {
1511   OS << '<';
1512   const char *Comma = Policy.MSVCFormatting ? "," : ", ";
1513 
1514   bool needSpace = false;
1515   for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1516     if (Arg > 0)
1517       OS << Comma;
1518 
1519     // Print the argument into a string.
1520     SmallString<128> Buf;
1521     llvm::raw_svector_ostream ArgOS(Buf);
1522     if (Args[Arg].getArgument().getKind() == TemplateArgument::Pack) {
1523       PrintTemplateArgumentList(ArgOS,
1524                                 Args[Arg].getArgument().pack_begin(),
1525                                 Args[Arg].getArgument().pack_size(),
1526                                 Policy, true);
1527     } else {
1528       Args[Arg].getArgument().print(Policy, ArgOS);
1529     }
1530     StringRef ArgString = ArgOS.str();
1531 
1532     // If this is the first argument and its string representation
1533     // begins with the global scope specifier ('::foo'), add a space
1534     // to avoid printing the diagraph '<:'.
1535     if (!Arg && !ArgString.empty() && ArgString[0] == ':')
1536       OS << ' ';
1537 
1538     OS << ArgString;
1539 
1540     needSpace = (!ArgString.empty() && ArgString.back() == '>');
1541   }
1542 
1543   // If the last character of our string is '>', add another space to
1544   // keep the two '>''s separate tokens. We don't *have* to do this in
1545   // C++0x, but it's still good hygiene.
1546   if (needSpace)
1547     OS << ' ';
1548 
1549   OS << '>';
1550 }
1551 
1552 std::string Qualifiers::getAsString() const {
1553   LangOptions LO;
1554   return getAsString(PrintingPolicy(LO));
1555 }
1556 
1557 // Appends qualifiers to the given string, separated by spaces.  Will
1558 // prefix a space if the string is non-empty.  Will not append a final
1559 // space.
1560 std::string Qualifiers::getAsString(const PrintingPolicy &Policy) const {
1561   SmallString<64> Buf;
1562   llvm::raw_svector_ostream StrOS(Buf);
1563   print(StrOS, Policy);
1564   return StrOS.str();
1565 }
1566 
1567 bool Qualifiers::isEmptyWhenPrinted(const PrintingPolicy &Policy) const {
1568   if (getCVRQualifiers())
1569     return false;
1570 
1571   if (getAddressSpace())
1572     return false;
1573 
1574   if (getObjCGCAttr())
1575     return false;
1576 
1577   if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime())
1578     if (!(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime))
1579       return false;
1580 
1581   return true;
1582 }
1583 
1584 // Appends qualifiers to the given string, separated by spaces.  Will
1585 // prefix a space if the string is non-empty.  Will not append a final
1586 // space.
1587 void Qualifiers::print(raw_ostream &OS, const PrintingPolicy& Policy,
1588                        bool appendSpaceIfNonEmpty) const {
1589   bool addSpace = false;
1590 
1591   unsigned quals = getCVRQualifiers();
1592   if (quals) {
1593     AppendTypeQualList(OS, quals, Policy.LangOpts.C99);
1594     addSpace = true;
1595   }
1596   if (hasUnaligned()) {
1597     if (addSpace)
1598       OS << ' ';
1599     OS << "__unaligned";
1600     addSpace = true;
1601   }
1602   if (unsigned addrspace = getAddressSpace()) {
1603     if (addSpace)
1604       OS << ' ';
1605     addSpace = true;
1606     switch (addrspace) {
1607       case LangAS::opencl_global:
1608         OS << "__global";
1609         break;
1610       case LangAS::opencl_local:
1611         OS << "__local";
1612         break;
1613       case LangAS::opencl_constant:
1614         OS << "__constant";
1615         break;
1616       case LangAS::opencl_generic:
1617         OS << "__generic";
1618         break;
1619       default:
1620         OS << "__attribute__((address_space(";
1621         OS << addrspace;
1622         OS << ")))";
1623     }
1624   }
1625   if (Qualifiers::GC gc = getObjCGCAttr()) {
1626     if (addSpace)
1627       OS << ' ';
1628     addSpace = true;
1629     if (gc == Qualifiers::Weak)
1630       OS << "__weak";
1631     else
1632       OS << "__strong";
1633   }
1634   if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime()) {
1635     if (!(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime)){
1636       if (addSpace)
1637         OS << ' ';
1638       addSpace = true;
1639     }
1640 
1641     switch (lifetime) {
1642     case Qualifiers::OCL_None: llvm_unreachable("none but true");
1643     case Qualifiers::OCL_ExplicitNone: OS << "__unsafe_unretained"; break;
1644     case Qualifiers::OCL_Strong:
1645       if (!Policy.SuppressStrongLifetime)
1646         OS << "__strong";
1647       break;
1648 
1649     case Qualifiers::OCL_Weak: OS << "__weak"; break;
1650     case Qualifiers::OCL_Autoreleasing: OS << "__autoreleasing"; break;
1651     }
1652   }
1653 
1654   if (appendSpaceIfNonEmpty && addSpace)
1655     OS << ' ';
1656 }
1657 
1658 std::string QualType::getAsString(const PrintingPolicy &Policy) const {
1659   std::string S;
1660   getAsStringInternal(S, Policy);
1661   return S;
1662 }
1663 
1664 std::string QualType::getAsString(const Type *ty, Qualifiers qs) {
1665   std::string buffer;
1666   LangOptions options;
1667   getAsStringInternal(ty, qs, buffer, PrintingPolicy(options));
1668   return buffer;
1669 }
1670 
1671 void QualType::print(const Type *ty, Qualifiers qs,
1672                      raw_ostream &OS, const PrintingPolicy &policy,
1673                      const Twine &PlaceHolder, unsigned Indentation) {
1674   SmallString<128> PHBuf;
1675   StringRef PH = PlaceHolder.toStringRef(PHBuf);
1676 
1677   TypePrinter(policy, Indentation).print(ty, qs, OS, PH);
1678 }
1679 
1680 void QualType::getAsStringInternal(const Type *ty, Qualifiers qs,
1681                                    std::string &buffer,
1682                                    const PrintingPolicy &policy) {
1683   SmallString<256> Buf;
1684   llvm::raw_svector_ostream StrOS(Buf);
1685   TypePrinter(policy).print(ty, qs, StrOS, buffer);
1686   std::string str = StrOS.str();
1687   buffer.swap(str);
1688 }
1689