1 //===--- TypePrinter.cpp - Pretty-Print Clang Types -----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This contains code to print types from Clang's type system.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/Decl.h"
15 #include "clang/AST/DeclObjC.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/Type.h"
19 #include "clang/AST/PrettyPrinter.h"
20 #include "clang/Basic/LangOptions.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/Support/raw_ostream.h"
24 using namespace clang;
25 
26 namespace {
27   /// \brief RAII object that enables printing of the ARC __strong lifetime
28   /// qualifier.
29   class IncludeStrongLifetimeRAII {
30     PrintingPolicy &Policy;
31     bool Old;
32 
33   public:
34     explicit IncludeStrongLifetimeRAII(PrintingPolicy &Policy)
35       : Policy(Policy), Old(Policy.SuppressStrongLifetime) {
36       Policy.SuppressStrongLifetime = false;
37     }
38 
39     ~IncludeStrongLifetimeRAII() {
40       Policy.SuppressStrongLifetime = Old;
41     }
42   };
43 
44   class TypePrinter {
45     PrintingPolicy Policy;
46 
47   public:
48     explicit TypePrinter(const PrintingPolicy &Policy) : Policy(Policy) { }
49 
50     void print(const Type *ty, Qualifiers qs, std::string &buffer);
51     void print(QualType T, std::string &S);
52     void AppendScope(DeclContext *DC, std::string &S);
53     void printTag(TagDecl *T, std::string &S);
54 #define ABSTRACT_TYPE(CLASS, PARENT)
55 #define TYPE(CLASS, PARENT) \
56     void print##CLASS(const CLASS##Type *T, std::string &S);
57 #include "clang/AST/TypeNodes.def"
58   };
59 }
60 
61 static void AppendTypeQualList(std::string &S, unsigned TypeQuals) {
62   if (TypeQuals & Qualifiers::Const) {
63     if (!S.empty()) S += ' ';
64     S += "const";
65   }
66   if (TypeQuals & Qualifiers::Volatile) {
67     if (!S.empty()) S += ' ';
68     S += "volatile";
69   }
70   if (TypeQuals & Qualifiers::Restrict) {
71     if (!S.empty()) S += ' ';
72     S += "restrict";
73   }
74 }
75 
76 void TypePrinter::print(QualType t, std::string &buffer) {
77   SplitQualType split = t.split();
78   print(split.Ty, split.Quals, buffer);
79 }
80 
81 void TypePrinter::print(const Type *T, Qualifiers Quals, std::string &buffer) {
82   if (!T) {
83     buffer += "NULL TYPE";
84     return;
85   }
86 
87   if (Policy.SuppressSpecifiers && T->isSpecifierType())
88     return;
89 
90   // Print qualifiers as appropriate.
91 
92   // CanPrefixQualifiers - We prefer to print type qualifiers before the type,
93   // so that we get "const int" instead of "int const", but we can't do this if
94   // the type is complex.  For example if the type is "int*", we *must* print
95   // "int * const", printing "const int *" is different.  Only do this when the
96   // type expands to a simple string.
97   bool CanPrefixQualifiers = false;
98   bool NeedARCStrongQualifier = false;
99   Type::TypeClass TC = T->getTypeClass();
100   if (const AutoType *AT = dyn_cast<AutoType>(T))
101     TC = AT->desugar()->getTypeClass();
102   if (const SubstTemplateTypeParmType *Subst
103                                       = dyn_cast<SubstTemplateTypeParmType>(T))
104     TC = Subst->getReplacementType()->getTypeClass();
105 
106   switch (TC) {
107     case Type::Builtin:
108     case Type::Complex:
109     case Type::UnresolvedUsing:
110     case Type::Typedef:
111     case Type::TypeOfExpr:
112     case Type::TypeOf:
113     case Type::Decltype:
114     case Type::UnaryTransform:
115     case Type::Record:
116     case Type::Enum:
117     case Type::Elaborated:
118     case Type::TemplateTypeParm:
119     case Type::SubstTemplateTypeParmPack:
120     case Type::TemplateSpecialization:
121     case Type::InjectedClassName:
122     case Type::DependentName:
123     case Type::DependentTemplateSpecialization:
124     case Type::ObjCObject:
125     case Type::ObjCInterface:
126     case Type::Atomic:
127       CanPrefixQualifiers = true;
128       break;
129 
130     case Type::ObjCObjectPointer:
131       CanPrefixQualifiers = T->isObjCIdType() || T->isObjCClassType() ||
132         T->isObjCQualifiedIdType() || T->isObjCQualifiedClassType();
133       break;
134 
135     case Type::ConstantArray:
136     case Type::IncompleteArray:
137     case Type::VariableArray:
138     case Type::DependentSizedArray:
139       NeedARCStrongQualifier = true;
140       // Fall through
141 
142     case Type::Pointer:
143     case Type::BlockPointer:
144     case Type::LValueReference:
145     case Type::RValueReference:
146     case Type::MemberPointer:
147     case Type::DependentSizedExtVector:
148     case Type::Vector:
149     case Type::ExtVector:
150     case Type::FunctionProto:
151     case Type::FunctionNoProto:
152     case Type::Paren:
153     case Type::Attributed:
154     case Type::PackExpansion:
155     case Type::SubstTemplateTypeParm:
156     case Type::Auto:
157       CanPrefixQualifiers = false;
158       break;
159   }
160 
161   if (!CanPrefixQualifiers && !Quals.empty()) {
162     std::string qualsBuffer;
163     if (NeedARCStrongQualifier) {
164       IncludeStrongLifetimeRAII Strong(Policy);
165       Quals.getAsStringInternal(qualsBuffer, Policy);
166     } else {
167       Quals.getAsStringInternal(qualsBuffer, Policy);
168     }
169 
170     if (!qualsBuffer.empty()) {
171       if (!buffer.empty()) {
172         qualsBuffer += ' ';
173         qualsBuffer += buffer;
174       }
175       std::swap(buffer, qualsBuffer);
176     }
177   }
178 
179   switch (T->getTypeClass()) {
180 #define ABSTRACT_TYPE(CLASS, PARENT)
181 #define TYPE(CLASS, PARENT) case Type::CLASS: \
182     print##CLASS(cast<CLASS##Type>(T), buffer); \
183     break;
184 #include "clang/AST/TypeNodes.def"
185   }
186 
187   // If we're adding the qualifiers as a prefix, do it now.
188   if (CanPrefixQualifiers && !Quals.empty()) {
189     std::string qualsBuffer;
190     if (NeedARCStrongQualifier) {
191       IncludeStrongLifetimeRAII Strong(Policy);
192       Quals.getAsStringInternal(qualsBuffer, Policy);
193     } else {
194       Quals.getAsStringInternal(qualsBuffer, Policy);
195     }
196 
197     if (!qualsBuffer.empty()) {
198       if (!buffer.empty()) {
199         qualsBuffer += ' ';
200         qualsBuffer += buffer;
201       }
202       std::swap(buffer, qualsBuffer);
203     }
204   }
205 }
206 
207 void TypePrinter::printBuiltin(const BuiltinType *T, std::string &S) {
208   if (S.empty()) {
209     S = T->getName(Policy);
210   } else {
211     // Prefix the basic type, e.g. 'int X'.
212     S = ' ' + S;
213     S = T->getName(Policy) + S;
214   }
215 }
216 
217 void TypePrinter::printComplex(const ComplexType *T, std::string &S) {
218   print(T->getElementType(), S);
219   S = "_Complex " + S;
220 }
221 
222 void TypePrinter::printPointer(const PointerType *T, std::string &S) {
223   S = '*' + S;
224 
225   // Handle things like 'int (*A)[4];' correctly.
226   // FIXME: this should include vectors, but vectors use attributes I guess.
227   if (isa<ArrayType>(T->getPointeeType()))
228     S = '(' + S + ')';
229 
230   IncludeStrongLifetimeRAII Strong(Policy);
231   print(T->getPointeeType(), S);
232 }
233 
234 void TypePrinter::printBlockPointer(const BlockPointerType *T, std::string &S) {
235   S = '^' + S;
236   print(T->getPointeeType(), S);
237 }
238 
239 void TypePrinter::printLValueReference(const LValueReferenceType *T,
240                                        std::string &S) {
241   S = '&' + S;
242 
243   // Handle things like 'int (&A)[4];' correctly.
244   // FIXME: this should include vectors, but vectors use attributes I guess.
245   if (isa<ArrayType>(T->getPointeeTypeAsWritten()))
246     S = '(' + S + ')';
247 
248   IncludeStrongLifetimeRAII Strong(Policy);
249   print(T->getPointeeTypeAsWritten(), S);
250 }
251 
252 void TypePrinter::printRValueReference(const RValueReferenceType *T,
253                                        std::string &S) {
254   S = "&&" + S;
255 
256   // Handle things like 'int (&&A)[4];' correctly.
257   // FIXME: this should include vectors, but vectors use attributes I guess.
258   if (isa<ArrayType>(T->getPointeeTypeAsWritten()))
259     S = '(' + S + ')';
260 
261   IncludeStrongLifetimeRAII Strong(Policy);
262   print(T->getPointeeTypeAsWritten(), S);
263 }
264 
265 void TypePrinter::printMemberPointer(const MemberPointerType *T,
266                                      std::string &S) {
267   std::string C;
268   print(QualType(T->getClass(), 0), C);
269   C += "::*";
270   S = C + S;
271 
272   // Handle things like 'int (Cls::*A)[4];' correctly.
273   // FIXME: this should include vectors, but vectors use attributes I guess.
274   if (isa<ArrayType>(T->getPointeeType()))
275     S = '(' + S + ')';
276 
277   IncludeStrongLifetimeRAII Strong(Policy);
278   print(T->getPointeeType(), S);
279 }
280 
281 void TypePrinter::printConstantArray(const ConstantArrayType *T,
282                                      std::string &S) {
283   S += '[';
284   S += llvm::utostr(T->getSize().getZExtValue());
285   S += ']';
286 
287   IncludeStrongLifetimeRAII Strong(Policy);
288   print(T->getElementType(), S);
289 }
290 
291 void TypePrinter::printIncompleteArray(const IncompleteArrayType *T,
292                                        std::string &S) {
293   S += "[]";
294   IncludeStrongLifetimeRAII Strong(Policy);
295   print(T->getElementType(), S);
296 }
297 
298 void TypePrinter::printVariableArray(const VariableArrayType *T,
299                                      std::string &S) {
300   S += '[';
301 
302   if (T->getIndexTypeQualifiers().hasQualifiers()) {
303     AppendTypeQualList(S, T->getIndexTypeCVRQualifiers());
304     S += ' ';
305   }
306 
307   if (T->getSizeModifier() == VariableArrayType::Static)
308     S += "static";
309   else if (T->getSizeModifier() == VariableArrayType::Star)
310     S += '*';
311 
312   if (T->getSizeExpr()) {
313     std::string SStr;
314     llvm::raw_string_ostream s(SStr);
315     T->getSizeExpr()->printPretty(s, 0, Policy);
316     S += s.str();
317   }
318   S += ']';
319 
320   IncludeStrongLifetimeRAII Strong(Policy);
321   print(T->getElementType(), S);
322 }
323 
324 void TypePrinter::printDependentSizedArray(const DependentSizedArrayType *T,
325                                            std::string &S) {
326   S += '[';
327 
328   if (T->getSizeExpr()) {
329     std::string SStr;
330     llvm::raw_string_ostream s(SStr);
331     T->getSizeExpr()->printPretty(s, 0, Policy);
332     S += s.str();
333   }
334   S += ']';
335 
336   IncludeStrongLifetimeRAII Strong(Policy);
337   print(T->getElementType(), S);
338 }
339 
340 void TypePrinter::printDependentSizedExtVector(
341                                           const DependentSizedExtVectorType *T,
342                                                std::string &S) {
343   print(T->getElementType(), S);
344 
345   S += " __attribute__((ext_vector_type(";
346   if (T->getSizeExpr()) {
347     std::string SStr;
348     llvm::raw_string_ostream s(SStr);
349     T->getSizeExpr()->printPretty(s, 0, Policy);
350     S += s.str();
351   }
352   S += ")))";
353 }
354 
355 void TypePrinter::printVector(const VectorType *T, std::string &S) {
356   switch (T->getVectorKind()) {
357   case VectorType::AltiVecPixel:
358     S = "__vector __pixel " + S;
359     break;
360   case VectorType::AltiVecBool:
361     print(T->getElementType(), S);
362     S = "__vector __bool " + S;
363     break;
364   case VectorType::AltiVecVector:
365     print(T->getElementType(), S);
366     S = "__vector " + S;
367     break;
368   case VectorType::NeonVector:
369     print(T->getElementType(), S);
370     S = ("__attribute__((neon_vector_type(" +
371          llvm::utostr_32(T->getNumElements()) + "))) " + S);
372     break;
373   case VectorType::NeonPolyVector:
374     print(T->getElementType(), S);
375     S = ("__attribute__((neon_polyvector_type(" +
376          llvm::utostr_32(T->getNumElements()) + "))) " + S);
377     break;
378   case VectorType::GenericVector: {
379     // FIXME: We prefer to print the size directly here, but have no way
380     // to get the size of the type.
381     print(T->getElementType(), S);
382     std::string V = "__attribute__((__vector_size__(";
383     V += llvm::utostr_32(T->getNumElements()); // convert back to bytes.
384     std::string ET;
385     print(T->getElementType(), ET);
386     V += " * sizeof(" + ET + ")))) ";
387     S = V + S;
388     break;
389   }
390   }
391 }
392 
393 void TypePrinter::printExtVector(const ExtVectorType *T, std::string &S) {
394   S += " __attribute__((ext_vector_type(";
395   S += llvm::utostr_32(T->getNumElements());
396   S += ")))";
397   print(T->getElementType(), S);
398 }
399 
400 void
401 FunctionProtoType::printExceptionSpecification(std::string &S,
402                                                PrintingPolicy Policy) const {
403 
404   if (hasDynamicExceptionSpec()) {
405     S += " throw(";
406     if (getExceptionSpecType() == EST_MSAny)
407       S += "...";
408     else
409       for (unsigned I = 0, N = getNumExceptions(); I != N; ++I) {
410         if (I)
411           S += ", ";
412 
413         S += getExceptionType(I).getAsString(Policy);
414       }
415     S += ")";
416   } else if (isNoexceptExceptionSpec(getExceptionSpecType())) {
417     S += " noexcept";
418     if (getExceptionSpecType() == EST_ComputedNoexcept) {
419       S += "(";
420       llvm::raw_string_ostream EOut(S);
421       getNoexceptExpr()->printPretty(EOut, 0, Policy);
422       EOut.flush();
423       S += EOut.str();
424       S += ")";
425     }
426   }
427 }
428 
429 void TypePrinter::printFunctionProto(const FunctionProtoType *T,
430                                      std::string &S) {
431   // If needed for precedence reasons, wrap the inner part in grouping parens.
432   if (!S.empty())
433     S = "(" + S + ")";
434 
435   S += "(";
436   std::string Tmp;
437   PrintingPolicy ParamPolicy(Policy);
438   ParamPolicy.SuppressSpecifiers = false;
439   for (unsigned i = 0, e = T->getNumArgs(); i != e; ++i) {
440     if (i) S += ", ";
441     print(T->getArgType(i), Tmp);
442     S += Tmp;
443     Tmp.clear();
444   }
445 
446   if (T->isVariadic()) {
447     if (T->getNumArgs())
448       S += ", ";
449     S += "...";
450   } else if (T->getNumArgs() == 0 && !Policy.LangOpts.CPlusPlus) {
451     // Do not emit int() if we have a proto, emit 'int(void)'.
452     S += "void";
453   }
454 
455   S += ")";
456 
457   FunctionType::ExtInfo Info = T->getExtInfo();
458   switch(Info.getCC()) {
459   case CC_Default: break;
460   case CC_C:
461     S += " __attribute__((cdecl))";
462     break;
463   case CC_X86StdCall:
464     S += " __attribute__((stdcall))";
465     break;
466   case CC_X86FastCall:
467     S += " __attribute__((fastcall))";
468     break;
469   case CC_X86ThisCall:
470     S += " __attribute__((thiscall))";
471     break;
472   case CC_X86Pascal:
473     S += " __attribute__((pascal))";
474     break;
475   case CC_AAPCS:
476     S += " __attribute__((pcs(\"aapcs\")))";
477     break;
478   case CC_AAPCS_VFP:
479     S += " __attribute__((pcs(\"aapcs-vfp\")))";
480     break;
481   }
482   if (Info.getNoReturn())
483     S += " __attribute__((noreturn))";
484   if (Info.getRegParm())
485     S += " __attribute__((regparm (" +
486         llvm::utostr_32(Info.getRegParm()) + ")))";
487 
488   AppendTypeQualList(S, T->getTypeQuals());
489 
490   switch (T->getRefQualifier()) {
491   case RQ_None:
492     break;
493 
494   case RQ_LValue:
495     S += " &";
496     break;
497 
498   case RQ_RValue:
499     S += " &&";
500     break;
501   }
502   T->printExceptionSpecification(S, Policy);
503   if (T->hasTrailingReturn()) {
504     std::string ResultS;
505     print(T->getResultType(), ResultS);
506     S = "auto " + S + " -> " + ResultS;
507   } else
508     print(T->getResultType(), S);
509 }
510 
511 void TypePrinter::printFunctionNoProto(const FunctionNoProtoType *T,
512                                        std::string &S) {
513   // If needed for precedence reasons, wrap the inner part in grouping parens.
514   if (!S.empty())
515     S = "(" + S + ")";
516 
517   S += "()";
518   if (T->getNoReturnAttr())
519     S += " __attribute__((noreturn))";
520   print(T->getResultType(), S);
521 }
522 
523 static void printTypeSpec(const NamedDecl *D, std::string &S) {
524   IdentifierInfo *II = D->getIdentifier();
525   if (S.empty())
526     S = II->getName().str();
527   else
528     S = II->getName().str() + ' ' + S;
529 }
530 
531 void TypePrinter::printUnresolvedUsing(const UnresolvedUsingType *T,
532                                        std::string &S) {
533   printTypeSpec(T->getDecl(), S);
534 }
535 
536 void TypePrinter::printTypedef(const TypedefType *T, std::string &S) {
537   printTypeSpec(T->getDecl(), S);
538 }
539 
540 void TypePrinter::printTypeOfExpr(const TypeOfExprType *T, std::string &S) {
541   if (!S.empty())    // Prefix the basic type, e.g. 'typeof(e) X'.
542     S = ' ' + S;
543   std::string Str;
544   llvm::raw_string_ostream s(Str);
545   T->getUnderlyingExpr()->printPretty(s, 0, Policy);
546   S = "typeof " + s.str() + S;
547 }
548 
549 void TypePrinter::printTypeOf(const TypeOfType *T, std::string &S) {
550   if (!S.empty())    // Prefix the basic type, e.g. 'typeof(t) X'.
551     S = ' ' + S;
552   std::string Tmp;
553   print(T->getUnderlyingType(), Tmp);
554   S = "typeof(" + Tmp + ")" + S;
555 }
556 
557 void TypePrinter::printDecltype(const DecltypeType *T, std::string &S) {
558   if (!S.empty())    // Prefix the basic type, e.g. 'decltype(t) X'.
559     S = ' ' + S;
560   std::string Str;
561   llvm::raw_string_ostream s(Str);
562   T->getUnderlyingExpr()->printPretty(s, 0, Policy);
563   S = "decltype(" + s.str() + ")" + S;
564 }
565 
566 void TypePrinter::printUnaryTransform(const UnaryTransformType *T,
567                                            std::string &S) {
568   if (!S.empty())
569     S = ' ' + S;
570   std::string Str;
571   IncludeStrongLifetimeRAII Strong(Policy);
572   print(T->getBaseType(), Str);
573 
574   switch (T->getUTTKind()) {
575     case UnaryTransformType::EnumUnderlyingType:
576       S = "__underlying_type(" + Str + ")" + S;
577       break;
578   }
579 }
580 
581 void TypePrinter::printAuto(const AutoType *T, std::string &S) {
582   // If the type has been deduced, do not print 'auto'.
583   if (T->isDeduced()) {
584     print(T->getDeducedType(), S);
585   } else {
586     if (!S.empty())    // Prefix the basic type, e.g. 'auto X'.
587       S = ' ' + S;
588     S = "auto" + S;
589   }
590 }
591 
592 void TypePrinter::printAtomic(const AtomicType *T, std::string &S) {
593   if (!S.empty())
594     S = ' ' + S;
595   std::string Str;
596   IncludeStrongLifetimeRAII Strong(Policy);
597   print(T->getValueType(), Str);
598 
599   S = "_Atomic(" + Str + ")" + S;
600 }
601 
602 /// Appends the given scope to the end of a string.
603 void TypePrinter::AppendScope(DeclContext *DC, std::string &Buffer) {
604   if (DC->isTranslationUnit()) return;
605   AppendScope(DC->getParent(), Buffer);
606 
607   unsigned OldSize = Buffer.size();
608 
609   if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(DC)) {
610     if (Policy.SuppressUnwrittenScope &&
611         (NS->isAnonymousNamespace() || NS->isInline()))
612       return;
613     if (NS->getIdentifier())
614       Buffer += NS->getNameAsString();
615     else
616       Buffer += "<anonymous>";
617   } else if (ClassTemplateSpecializationDecl *Spec
618                = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
619     IncludeStrongLifetimeRAII Strong(Policy);
620     const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
621     std::string TemplateArgsStr
622       = TemplateSpecializationType::PrintTemplateArgumentList(
623                                             TemplateArgs.data(),
624                                             TemplateArgs.size(),
625                                             Policy);
626     Buffer += Spec->getIdentifier()->getName();
627     Buffer += TemplateArgsStr;
628   } else if (TagDecl *Tag = dyn_cast<TagDecl>(DC)) {
629     if (TypedefNameDecl *Typedef = Tag->getTypedefNameForAnonDecl())
630       Buffer += Typedef->getIdentifier()->getName();
631     else if (Tag->getIdentifier())
632       Buffer += Tag->getIdentifier()->getName();
633     else
634       return;
635   }
636 
637   if (Buffer.size() != OldSize)
638     Buffer += "::";
639 }
640 
641 void TypePrinter::printTag(TagDecl *D, std::string &InnerString) {
642   if (Policy.SuppressTag)
643     return;
644 
645   std::string Buffer;
646   bool HasKindDecoration = false;
647 
648   // bool SuppressTagKeyword
649   //   = Policy.LangOpts.CPlusPlus || Policy.SuppressTagKeyword;
650 
651   // We don't print tags unless this is an elaborated type.
652   // In C, we just assume every RecordType is an elaborated type.
653   if (!(Policy.LangOpts.CPlusPlus || Policy.SuppressTagKeyword ||
654         D->getTypedefNameForAnonDecl())) {
655     HasKindDecoration = true;
656     Buffer += D->getKindName();
657     Buffer += ' ';
658   }
659 
660   // Compute the full nested-name-specifier for this type.
661   // In C, this will always be empty except when the type
662   // being printed is anonymous within other Record.
663   if (!Policy.SuppressScope)
664     AppendScope(D->getDeclContext(), Buffer);
665 
666   if (const IdentifierInfo *II = D->getIdentifier())
667     Buffer += II->getNameStart();
668   else if (TypedefNameDecl *Typedef = D->getTypedefNameForAnonDecl()) {
669     assert(Typedef->getIdentifier() && "Typedef without identifier?");
670     Buffer += Typedef->getIdentifier()->getNameStart();
671   } else {
672     // Make an unambiguous representation for anonymous types, e.g.
673     //   <anonymous enum at /usr/include/string.h:120:9>
674     llvm::raw_string_ostream OS(Buffer);
675 
676     if (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda()) {
677       OS << "<lambda";
678       HasKindDecoration = true;
679     } else {
680       OS << "<anonymous";
681     }
682 
683     if (Policy.AnonymousTagLocations) {
684       // Suppress the redundant tag keyword if we just printed one.
685       // We don't have to worry about ElaboratedTypes here because you can't
686       // refer to an anonymous type with one.
687       if (!HasKindDecoration)
688         OS << " " << D->getKindName();
689 
690       PresumedLoc PLoc = D->getASTContext().getSourceManager().getPresumedLoc(
691           D->getLocation());
692       if (PLoc.isValid()) {
693         OS << " at " << PLoc.getFilename()
694            << ':' << PLoc.getLine()
695            << ':' << PLoc.getColumn();
696       }
697     }
698 
699     OS << '>';
700   }
701 
702   // If this is a class template specialization, print the template
703   // arguments.
704   if (ClassTemplateSpecializationDecl *Spec
705         = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
706     const TemplateArgument *Args;
707     unsigned NumArgs;
708     if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
709       const TemplateSpecializationType *TST =
710         cast<TemplateSpecializationType>(TAW->getType());
711       Args = TST->getArgs();
712       NumArgs = TST->getNumArgs();
713     } else {
714       const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
715       Args = TemplateArgs.data();
716       NumArgs = TemplateArgs.size();
717     }
718     IncludeStrongLifetimeRAII Strong(Policy);
719     Buffer += TemplateSpecializationType::PrintTemplateArgumentList(Args,
720                                                                     NumArgs,
721                                                                     Policy);
722   }
723 
724   if (!InnerString.empty()) {
725     Buffer += ' ';
726     Buffer += InnerString;
727   }
728 
729   std::swap(Buffer, InnerString);
730 }
731 
732 void TypePrinter::printRecord(const RecordType *T, std::string &S) {
733   printTag(T->getDecl(), S);
734 }
735 
736 void TypePrinter::printEnum(const EnumType *T, std::string &S) {
737   printTag(T->getDecl(), S);
738 }
739 
740 void TypePrinter::printTemplateTypeParm(const TemplateTypeParmType *T,
741                                         std::string &S) {
742   if (!S.empty())    // Prefix the basic type, e.g. 'parmname X'.
743     S = ' ' + S;
744 
745   if (IdentifierInfo *Id = T->getIdentifier())
746     S = Id->getName().str() + S;
747   else
748     S = "type-parameter-" + llvm::utostr_32(T->getDepth()) + '-' +
749         llvm::utostr_32(T->getIndex()) + S;
750 }
751 
752 void TypePrinter::printSubstTemplateTypeParm(const SubstTemplateTypeParmType *T,
753                                              std::string &S) {
754   IncludeStrongLifetimeRAII Strong(Policy);
755   print(T->getReplacementType(), S);
756 }
757 
758 void TypePrinter::printSubstTemplateTypeParmPack(
759                                         const SubstTemplateTypeParmPackType *T,
760                                              std::string &S) {
761   IncludeStrongLifetimeRAII Strong(Policy);
762   printTemplateTypeParm(T->getReplacedParameter(), S);
763 }
764 
765 void TypePrinter::printTemplateSpecialization(
766                                             const TemplateSpecializationType *T,
767                                               std::string &S) {
768   IncludeStrongLifetimeRAII Strong(Policy);
769   std::string SpecString;
770 
771   {
772     llvm::raw_string_ostream OS(SpecString);
773     T->getTemplateName().print(OS, Policy);
774   }
775 
776   SpecString += TemplateSpecializationType::PrintTemplateArgumentList(
777                                                                   T->getArgs(),
778                                                                 T->getNumArgs(),
779                                                                       Policy);
780   if (S.empty())
781     S.swap(SpecString);
782   else
783     S = SpecString + ' ' + S;
784 }
785 
786 void TypePrinter::printInjectedClassName(const InjectedClassNameType *T,
787                                          std::string &S) {
788   printTemplateSpecialization(T->getInjectedTST(), S);
789 }
790 
791 void TypePrinter::printElaborated(const ElaboratedType *T, std::string &S) {
792   std::string MyString;
793 
794   {
795     llvm::raw_string_ostream OS(MyString);
796     OS << TypeWithKeyword::getKeywordName(T->getKeyword());
797     if (T->getKeyword() != ETK_None)
798       OS << " ";
799     NestedNameSpecifier* Qualifier = T->getQualifier();
800     if (Qualifier)
801       Qualifier->print(OS, Policy);
802   }
803 
804   std::string TypeStr;
805   PrintingPolicy InnerPolicy(Policy);
806   InnerPolicy.SuppressTagKeyword = true;
807   InnerPolicy.SuppressScope = true;
808   TypePrinter(InnerPolicy).print(T->getNamedType(), TypeStr);
809 
810   MyString += TypeStr;
811   if (S.empty())
812     S.swap(MyString);
813   else
814     S = MyString + ' ' + S;
815 }
816 
817 void TypePrinter::printParen(const ParenType *T, std::string &S) {
818   if (!S.empty() && !isa<FunctionType>(T->getInnerType()))
819     S = '(' + S + ')';
820   print(T->getInnerType(), S);
821 }
822 
823 void TypePrinter::printDependentName(const DependentNameType *T, std::string &S) {
824   std::string MyString;
825 
826   {
827     llvm::raw_string_ostream OS(MyString);
828     OS << TypeWithKeyword::getKeywordName(T->getKeyword());
829     if (T->getKeyword() != ETK_None)
830       OS << " ";
831 
832     T->getQualifier()->print(OS, Policy);
833 
834     OS << T->getIdentifier()->getName();
835   }
836 
837   if (S.empty())
838     S.swap(MyString);
839   else
840     S = MyString + ' ' + S;
841 }
842 
843 void TypePrinter::printDependentTemplateSpecialization(
844         const DependentTemplateSpecializationType *T, std::string &S) {
845   IncludeStrongLifetimeRAII Strong(Policy);
846   std::string MyString;
847   {
848     llvm::raw_string_ostream OS(MyString);
849 
850     OS << TypeWithKeyword::getKeywordName(T->getKeyword());
851     if (T->getKeyword() != ETK_None)
852       OS << " ";
853 
854     if (T->getQualifier())
855       T->getQualifier()->print(OS, Policy);
856     OS << T->getIdentifier()->getName();
857     OS << TemplateSpecializationType::PrintTemplateArgumentList(
858                                                             T->getArgs(),
859                                                             T->getNumArgs(),
860                                                             Policy);
861   }
862 
863   if (S.empty())
864     S.swap(MyString);
865   else
866     S = MyString + ' ' + S;
867 }
868 
869 void TypePrinter::printPackExpansion(const PackExpansionType *T,
870                                      std::string &S) {
871   print(T->getPattern(), S);
872   S += "...";
873 }
874 
875 void TypePrinter::printAttributed(const AttributedType *T,
876                                   std::string &S) {
877   // Prefer the macro forms of the GC and ownership qualifiers.
878   if (T->getAttrKind() == AttributedType::attr_objc_gc ||
879       T->getAttrKind() == AttributedType::attr_objc_ownership)
880     return print(T->getEquivalentType(), S);
881 
882   print(T->getModifiedType(), S);
883 
884   // TODO: not all attributes are GCC-style attributes.
885   S += " __attribute__((";
886   switch (T->getAttrKind()) {
887   case AttributedType::attr_address_space:
888     S += "address_space(";
889     S += T->getEquivalentType().getAddressSpace();
890     S += ")";
891     break;
892 
893   case AttributedType::attr_vector_size: {
894     S += "__vector_size__(";
895     if (const VectorType *vector =T->getEquivalentType()->getAs<VectorType>()) {
896       S += vector->getNumElements();
897       S += " * sizeof(";
898 
899       std::string tmp;
900       print(vector->getElementType(), tmp);
901       S += tmp;
902       S += ")";
903     }
904     S += ")";
905     break;
906   }
907 
908   case AttributedType::attr_neon_vector_type:
909   case AttributedType::attr_neon_polyvector_type: {
910     if (T->getAttrKind() == AttributedType::attr_neon_vector_type)
911       S += "neon_vector_type(";
912     else
913       S += "neon_polyvector_type(";
914     const VectorType *vector = T->getEquivalentType()->getAs<VectorType>();
915     S += llvm::utostr_32(vector->getNumElements());
916     S += ")";
917     break;
918   }
919 
920   case AttributedType::attr_regparm: {
921     S += "regparm(";
922     QualType t = T->getEquivalentType();
923     while (!t->isFunctionType())
924       t = t->getPointeeType();
925     S += t->getAs<FunctionType>()->getRegParmType();
926     S += ")";
927     break;
928   }
929 
930   case AttributedType::attr_objc_gc: {
931     S += "objc_gc(";
932 
933     QualType tmp = T->getEquivalentType();
934     while (tmp.getObjCGCAttr() == Qualifiers::GCNone) {
935       QualType next = tmp->getPointeeType();
936       if (next == tmp) break;
937       tmp = next;
938     }
939 
940     if (tmp.isObjCGCWeak())
941       S += "weak";
942     else
943       S += "strong";
944     S += ")";
945     break;
946   }
947 
948   case AttributedType::attr_objc_ownership:
949     S += "objc_ownership(";
950     switch (T->getEquivalentType().getObjCLifetime()) {
951     case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
952     case Qualifiers::OCL_ExplicitNone: S += "none"; break;
953     case Qualifiers::OCL_Strong: S += "strong"; break;
954     case Qualifiers::OCL_Weak: S += "weak"; break;
955     case Qualifiers::OCL_Autoreleasing: S += "autoreleasing"; break;
956     }
957     S += ")";
958     break;
959 
960   case AttributedType::attr_noreturn: S += "noreturn"; break;
961   case AttributedType::attr_cdecl: S += "cdecl"; break;
962   case AttributedType::attr_fastcall: S += "fastcall"; break;
963   case AttributedType::attr_stdcall: S += "stdcall"; break;
964   case AttributedType::attr_thiscall: S += "thiscall"; break;
965   case AttributedType::attr_pascal: S += "pascal"; break;
966   case AttributedType::attr_pcs: {
967    S += "pcs(";
968    QualType t = T->getEquivalentType();
969    while (!t->isFunctionType())
970      t = t->getPointeeType();
971    S += (t->getAs<FunctionType>()->getCallConv() == CC_AAPCS ?
972          "\"aapcs\"" : "\"aapcs-vfp\"");
973    S += ")";
974    break;
975   }
976   }
977   S += "))";
978 }
979 
980 void TypePrinter::printObjCInterface(const ObjCInterfaceType *T,
981                                      std::string &S) {
982   if (!S.empty())    // Prefix the basic type, e.g. 'typedefname X'.
983     S = ' ' + S;
984 
985   std::string ObjCQIString = T->getDecl()->getNameAsString();
986   S = ObjCQIString + S;
987 }
988 
989 void TypePrinter::printObjCObject(const ObjCObjectType *T,
990                                   std::string &S) {
991   if (T->qual_empty())
992     return print(T->getBaseType(), S);
993 
994   std::string tmp;
995   print(T->getBaseType(), tmp);
996   tmp += '<';
997   bool isFirst = true;
998   for (ObjCObjectType::qual_iterator
999          I = T->qual_begin(), E = T->qual_end(); I != E; ++I) {
1000     if (isFirst)
1001       isFirst = false;
1002     else
1003       tmp += ',';
1004     tmp += (*I)->getNameAsString();
1005   }
1006   tmp += '>';
1007 
1008   if (!S.empty()) {
1009     tmp += ' ';
1010     tmp += S;
1011   }
1012   std::swap(tmp, S);
1013 }
1014 
1015 void TypePrinter::printObjCObjectPointer(const ObjCObjectPointerType *T,
1016                                          std::string &S) {
1017   std::string ObjCQIString;
1018 
1019   T->getPointeeType().getLocalQualifiers().getAsStringInternal(ObjCQIString,
1020                                                                Policy);
1021   if (!ObjCQIString.empty())
1022     ObjCQIString += ' ';
1023 
1024   if (T->isObjCIdType() || T->isObjCQualifiedIdType())
1025     ObjCQIString += "id";
1026   else if (T->isObjCClassType() || T->isObjCQualifiedClassType())
1027     ObjCQIString += "Class";
1028   else if (T->isObjCSelType())
1029     ObjCQIString += "SEL";
1030   else
1031     ObjCQIString += T->getInterfaceDecl()->getNameAsString();
1032 
1033   if (!T->qual_empty()) {
1034     ObjCQIString += '<';
1035     for (ObjCObjectPointerType::qual_iterator I = T->qual_begin(),
1036                                               E = T->qual_end();
1037          I != E; ++I) {
1038       ObjCQIString += (*I)->getNameAsString();
1039       if (I+1 != E)
1040         ObjCQIString += ',';
1041     }
1042     ObjCQIString += '>';
1043   }
1044 
1045   if (!T->isObjCIdType() && !T->isObjCQualifiedIdType())
1046     ObjCQIString += " *"; // Don't forget the implicit pointer.
1047   else if (!S.empty()) // Prefix the basic type, e.g. 'typedefname X'.
1048     S = ' ' + S;
1049 
1050   S = ObjCQIString + S;
1051 }
1052 
1053 std::string TemplateSpecializationType::
1054   PrintTemplateArgumentList(const TemplateArgumentListInfo &Args,
1055                             const PrintingPolicy &Policy) {
1056   return PrintTemplateArgumentList(Args.getArgumentArray(),
1057                                    Args.size(),
1058                                    Policy);
1059 }
1060 
1061 std::string
1062 TemplateSpecializationType::PrintTemplateArgumentList(
1063                                                 const TemplateArgument *Args,
1064                                                 unsigned NumArgs,
1065                                                   const PrintingPolicy &Policy,
1066                                                       bool SkipBrackets) {
1067   std::string SpecString;
1068   if (!SkipBrackets)
1069     SpecString += '<';
1070 
1071   for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1072     if (SpecString.size() > unsigned(!SkipBrackets))
1073       SpecString += ", ";
1074 
1075     // Print the argument into a string.
1076     std::string ArgString;
1077     if (Args[Arg].getKind() == TemplateArgument::Pack) {
1078       ArgString = PrintTemplateArgumentList(Args[Arg].pack_begin(),
1079                                             Args[Arg].pack_size(),
1080                                             Policy, true);
1081     } else {
1082       llvm::raw_string_ostream ArgOut(ArgString);
1083       Args[Arg].print(Policy, ArgOut);
1084     }
1085 
1086     // If this is the first argument and its string representation
1087     // begins with the global scope specifier ('::foo'), add a space
1088     // to avoid printing the diagraph '<:'.
1089     if (!Arg && !ArgString.empty() && ArgString[0] == ':')
1090       SpecString += ' ';
1091 
1092     SpecString += ArgString;
1093   }
1094 
1095   // If the last character of our string is '>', add another space to
1096   // keep the two '>''s separate tokens. We don't *have* to do this in
1097   // C++0x, but it's still good hygiene.
1098   if (!SpecString.empty() && SpecString[SpecString.size() - 1] == '>')
1099     SpecString += ' ';
1100 
1101   if (!SkipBrackets)
1102     SpecString += '>';
1103 
1104   return SpecString;
1105 }
1106 
1107 // Sadly, repeat all that with TemplateArgLoc.
1108 std::string TemplateSpecializationType::
1109 PrintTemplateArgumentList(const TemplateArgumentLoc *Args, unsigned NumArgs,
1110                           const PrintingPolicy &Policy) {
1111   std::string SpecString;
1112   SpecString += '<';
1113   for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1114     if (SpecString.size() > 1)
1115       SpecString += ", ";
1116 
1117     // Print the argument into a string.
1118     std::string ArgString;
1119     if (Args[Arg].getArgument().getKind() == TemplateArgument::Pack) {
1120       ArgString = PrintTemplateArgumentList(
1121                                            Args[Arg].getArgument().pack_begin(),
1122                                             Args[Arg].getArgument().pack_size(),
1123                                             Policy, true);
1124     } else {
1125       llvm::raw_string_ostream ArgOut(ArgString);
1126       Args[Arg].getArgument().print(Policy, ArgOut);
1127     }
1128 
1129     // If this is the first argument and its string representation
1130     // begins with the global scope specifier ('::foo'), add a space
1131     // to avoid printing the diagraph '<:'.
1132     if (!Arg && !ArgString.empty() && ArgString[0] == ':')
1133       SpecString += ' ';
1134 
1135     SpecString += ArgString;
1136   }
1137 
1138   // If the last character of our string is '>', add another space to
1139   // keep the two '>''s separate tokens. We don't *have* to do this in
1140   // C++0x, but it's still good hygiene.
1141   if (SpecString[SpecString.size() - 1] == '>')
1142     SpecString += ' ';
1143 
1144   SpecString += '>';
1145 
1146   return SpecString;
1147 }
1148 
1149 void QualType::dump(const char *msg) const {
1150   std::string R = "identifier";
1151   LangOptions LO;
1152   getAsStringInternal(R, PrintingPolicy(LO));
1153   if (msg)
1154     llvm::errs() << msg << ": ";
1155   llvm::errs() << R << "\n";
1156 }
1157 void QualType::dump() const {
1158   dump("");
1159 }
1160 
1161 void Type::dump() const {
1162   QualType(this, 0).dump();
1163 }
1164 
1165 std::string Qualifiers::getAsString() const {
1166   LangOptions LO;
1167   return getAsString(PrintingPolicy(LO));
1168 }
1169 
1170 // Appends qualifiers to the given string, separated by spaces.  Will
1171 // prefix a space if the string is non-empty.  Will not append a final
1172 // space.
1173 void Qualifiers::getAsStringInternal(std::string &S,
1174                                      const PrintingPolicy& Policy) const {
1175   AppendTypeQualList(S, getCVRQualifiers());
1176   if (unsigned addrspace = getAddressSpace()) {
1177     if (!S.empty()) S += ' ';
1178     switch (addrspace) {
1179       case LangAS::opencl_global:
1180         S += "__global";
1181         break;
1182       case LangAS::opencl_local:
1183         S += "__local";
1184         break;
1185       case LangAS::opencl_constant:
1186         S += "__constant";
1187         break;
1188       default:
1189         S += "__attribute__((address_space(";
1190         S += llvm::utostr_32(addrspace);
1191         S += ")))";
1192     }
1193   }
1194   if (Qualifiers::GC gc = getObjCGCAttr()) {
1195     if (!S.empty()) S += ' ';
1196     if (gc == Qualifiers::Weak)
1197       S += "__weak";
1198     else
1199       S += "__strong";
1200   }
1201   if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime()) {
1202     if (!S.empty() &&
1203         !(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime))
1204       S += ' ';
1205 
1206     switch (lifetime) {
1207     case Qualifiers::OCL_None: llvm_unreachable("none but true");
1208     case Qualifiers::OCL_ExplicitNone: S += "__unsafe_unretained"; break;
1209     case Qualifiers::OCL_Strong:
1210       if (!Policy.SuppressStrongLifetime)
1211         S += "__strong";
1212       break;
1213 
1214     case Qualifiers::OCL_Weak: S += "__weak"; break;
1215     case Qualifiers::OCL_Autoreleasing: S += "__autoreleasing"; break;
1216     }
1217   }
1218 }
1219 
1220 std::string QualType::getAsString(const Type *ty, Qualifiers qs) {
1221   std::string buffer;
1222   LangOptions options;
1223   getAsStringInternal(ty, qs, buffer, PrintingPolicy(options));
1224   return buffer;
1225 }
1226 
1227 void QualType::getAsStringInternal(const Type *ty, Qualifiers qs,
1228                                    std::string &buffer,
1229                                    const PrintingPolicy &policy) {
1230   TypePrinter(policy).print(ty, qs, buffer);
1231 }
1232