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