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