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