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