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