TypePrinter.cpp revision 63cf68a4fcb93b502934d0d9c4e2ea407180ceb9
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"
24using namespace clang;
25
26namespace {
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
61static 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
76void TypePrinter::print(QualType t, std::string &buffer) {
77  SplitQualType split = t.split();
78  print(split.first, split.second, buffer);
79}
80
81void 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
207void 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
217void TypePrinter::printComplex(const ComplexType *T, std::string &S) {
218  print(T->getElementType(), S);
219  S = "_Complex " + S;
220}
221
222void 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
234void TypePrinter::printBlockPointer(const BlockPointerType *T, std::string &S) {
235  S = '^' + S;
236  print(T->getPointeeType(), S);
237}
238
239void 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
252void 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
265void 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
281void 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
291void TypePrinter::printIncompleteArray(const IncompleteArrayType *T,
292                                       std::string &S) {
293  S += "[]";
294  IncludeStrongLifetimeRAII Strong(Policy);
295  print(T->getElementType(), S);
296}
297
298void 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
324void 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
340void 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
355void 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
393void 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
400void TypePrinter::printFunctionProto(const FunctionProtoType *T,
401                                     std::string &S) {
402  // If needed for precedence reasons, wrap the inner part in grouping parens.
403  if (!S.empty())
404    S = "(" + S + ")";
405
406  S += "(";
407  std::string Tmp;
408  PrintingPolicy ParamPolicy(Policy);
409  ParamPolicy.SuppressSpecifiers = false;
410  for (unsigned i = 0, e = T->getNumArgs(); i != e; ++i) {
411    if (i) S += ", ";
412    print(T->getArgType(i), Tmp);
413    S += Tmp;
414    Tmp.clear();
415  }
416
417  if (T->isVariadic()) {
418    if (T->getNumArgs())
419      S += ", ";
420    S += "...";
421  } else if (T->getNumArgs() == 0 && !Policy.LangOpts.CPlusPlus) {
422    // Do not emit int() if we have a proto, emit 'int(void)'.
423    S += "void";
424  }
425
426  S += ")";
427
428  FunctionType::ExtInfo Info = T->getExtInfo();
429  switch(Info.getCC()) {
430  case CC_Default:
431  default: break;
432  case CC_C:
433    S += " __attribute__((cdecl))";
434    break;
435  case CC_X86StdCall:
436    S += " __attribute__((stdcall))";
437    break;
438  case CC_X86FastCall:
439    S += " __attribute__((fastcall))";
440    break;
441  case CC_X86ThisCall:
442    S += " __attribute__((thiscall))";
443    break;
444  case CC_X86Pascal:
445    S += " __attribute__((pascal))";
446    break;
447  case CC_AAPCS:
448    S += " __attribute__((pcs(\"aapcs\")))";
449    break;
450  case CC_AAPCS_VFP:
451    S += " __attribute__((pcs(\"aapcs-vfp\")))";
452    break;
453  }
454  if (Info.getNoReturn())
455    S += " __attribute__((noreturn))";
456  if (Info.getRegParm())
457    S += " __attribute__((regparm (" +
458        llvm::utostr_32(Info.getRegParm()) + ")))";
459
460  AppendTypeQualList(S, T->getTypeQuals());
461
462  switch (T->getRefQualifier()) {
463  case RQ_None:
464    break;
465
466  case RQ_LValue:
467    S += " &";
468    break;
469
470  case RQ_RValue:
471    S += " &&";
472    break;
473  }
474
475  if (T->hasDynamicExceptionSpec()) {
476    S += " throw(";
477    if (T->getExceptionSpecType() == EST_MSAny)
478      S += "...";
479    else
480      for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I) {
481        if (I)
482          S += ", ";
483
484        std::string ExceptionType;
485        print(T->getExceptionType(I), ExceptionType);
486        S += ExceptionType;
487      }
488    S += ")";
489  } else if (isNoexceptExceptionSpec(T->getExceptionSpecType())) {
490    S += " noexcept";
491    if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
492      S += "(";
493      llvm::raw_string_ostream EOut(S);
494      T->getNoexceptExpr()->printPretty(EOut, 0, Policy);
495      EOut.flush();
496      S += EOut.str();
497      S += ")";
498    }
499  }
500
501  print(T->getResultType(), S);
502}
503
504void TypePrinter::printFunctionNoProto(const FunctionNoProtoType *T,
505                                       std::string &S) {
506  // If needed for precedence reasons, wrap the inner part in grouping parens.
507  if (!S.empty())
508    S = "(" + S + ")";
509
510  S += "()";
511  if (T->getNoReturnAttr())
512    S += " __attribute__((noreturn))";
513  print(T->getResultType(), S);
514}
515
516static void printTypeSpec(const NamedDecl *D, std::string &S) {
517  IdentifierInfo *II = D->getIdentifier();
518  if (S.empty())
519    S = II->getName().str();
520  else
521    S = II->getName().str() + ' ' + S;
522}
523
524void TypePrinter::printUnresolvedUsing(const UnresolvedUsingType *T,
525                                       std::string &S) {
526  printTypeSpec(T->getDecl(), S);
527}
528
529void TypePrinter::printTypedef(const TypedefType *T, std::string &S) {
530  printTypeSpec(T->getDecl(), S);
531}
532
533void TypePrinter::printTypeOfExpr(const TypeOfExprType *T, std::string &S) {
534  if (!S.empty())    // Prefix the basic type, e.g. 'typeof(e) X'.
535    S = ' ' + S;
536  std::string Str;
537  llvm::raw_string_ostream s(Str);
538  T->getUnderlyingExpr()->printPretty(s, 0, Policy);
539  S = "typeof " + s.str() + S;
540}
541
542void TypePrinter::printTypeOf(const TypeOfType *T, std::string &S) {
543  if (!S.empty())    // Prefix the basic type, e.g. 'typeof(t) X'.
544    S = ' ' + S;
545  std::string Tmp;
546  print(T->getUnderlyingType(), Tmp);
547  S = "typeof(" + Tmp + ")" + S;
548}
549
550void TypePrinter::printDecltype(const DecltypeType *T, std::string &S) {
551  if (!S.empty())    // Prefix the basic type, e.g. 'decltype(t) X'.
552    S = ' ' + S;
553  std::string Str;
554  llvm::raw_string_ostream s(Str);
555  T->getUnderlyingExpr()->printPretty(s, 0, Policy);
556  S = "decltype(" + s.str() + ")" + S;
557}
558
559void TypePrinter::printUnaryTransform(const UnaryTransformType *T,
560                                           std::string &S) {
561  if (!S.empty())
562    S = ' ' + S;
563  std::string Str;
564  IncludeStrongLifetimeRAII Strong(Policy);
565  print(T->getBaseType(), Str);
566
567  switch (T->getUTTKind()) {
568    case UnaryTransformType::EnumUnderlyingType:
569      S = "__underlying_type(" + Str + ")" + S;
570      break;
571  }
572}
573
574void TypePrinter::printAuto(const AutoType *T, std::string &S) {
575  // If the type has been deduced, do not print 'auto'.
576  if (T->isDeduced()) {
577    print(T->getDeducedType(), S);
578  } else {
579    if (!S.empty())    // Prefix the basic type, e.g. 'auto X'.
580      S = ' ' + S;
581    S = "auto" + S;
582  }
583}
584
585void TypePrinter::printAtomic(const AtomicType *T, std::string &S) {
586  if (!S.empty())
587    S = ' ' + S;
588  std::string Str;
589  IncludeStrongLifetimeRAII Strong(Policy);
590  print(T->getValueType(), Str);
591
592  S = "_Atomic(" + Str + ")" + S;
593}
594
595/// Appends the given scope to the end of a string.
596void TypePrinter::AppendScope(DeclContext *DC, std::string &Buffer) {
597  if (DC->isTranslationUnit()) return;
598  AppendScope(DC->getParent(), Buffer);
599
600  unsigned OldSize = Buffer.size();
601
602  if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(DC)) {
603    if (Policy.SuppressUnwrittenScope &&
604        (NS->isAnonymousNamespace() || NS->isInline()))
605      return;
606    if (NS->getIdentifier())
607      Buffer += NS->getNameAsString();
608    else
609      Buffer += "<anonymous>";
610  } else if (ClassTemplateSpecializationDecl *Spec
611               = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
612    IncludeStrongLifetimeRAII Strong(Policy);
613    const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
614    std::string TemplateArgsStr
615      = TemplateSpecializationType::PrintTemplateArgumentList(
616                                            TemplateArgs.data(),
617                                            TemplateArgs.size(),
618                                            Policy);
619    Buffer += Spec->getIdentifier()->getName();
620    Buffer += TemplateArgsStr;
621  } else if (TagDecl *Tag = dyn_cast<TagDecl>(DC)) {
622    if (TypedefNameDecl *Typedef = Tag->getTypedefNameForAnonDecl())
623      Buffer += Typedef->getIdentifier()->getName();
624    else if (Tag->getIdentifier())
625      Buffer += Tag->getIdentifier()->getName();
626    else
627      return;
628  }
629
630  if (Buffer.size() != OldSize)
631    Buffer += "::";
632}
633
634void TypePrinter::printTag(TagDecl *D, std::string &InnerString) {
635  if (Policy.SuppressTag)
636    return;
637
638  std::string Buffer;
639  bool HasKindDecoration = false;
640
641  // bool SuppressTagKeyword
642  //   = Policy.LangOpts.CPlusPlus || Policy.SuppressTagKeyword;
643
644  // We don't print tags unless this is an elaborated type.
645  // In C, we just assume every RecordType is an elaborated type.
646  if (!(Policy.LangOpts.CPlusPlus || Policy.SuppressTagKeyword ||
647        D->getTypedefNameForAnonDecl())) {
648    HasKindDecoration = true;
649    Buffer += D->getKindName();
650    Buffer += ' ';
651  }
652
653  // Compute the full nested-name-specifier for this type.
654  // In C, this will always be empty except when the type
655  // being printed is anonymous within other Record.
656  if (!Policy.SuppressScope)
657    AppendScope(D->getDeclContext(), Buffer);
658
659  if (const IdentifierInfo *II = D->getIdentifier())
660    Buffer += II->getNameStart();
661  else if (TypedefNameDecl *Typedef = D->getTypedefNameForAnonDecl()) {
662    assert(Typedef->getIdentifier() && "Typedef without identifier?");
663    Buffer += Typedef->getIdentifier()->getNameStart();
664  } else {
665    // Make an unambiguous representation for anonymous types, e.g.
666    //   <anonymous enum at /usr/include/string.h:120:9>
667    llvm::raw_string_ostream OS(Buffer);
668    OS << "<anonymous";
669
670    if (Policy.AnonymousTagLocations) {
671      // Suppress the redundant tag keyword if we just printed one.
672      // We don't have to worry about ElaboratedTypes here because you can't
673      // refer to an anonymous type with one.
674      if (!HasKindDecoration)
675        OS << " " << D->getKindName();
676
677      PresumedLoc PLoc = D->getASTContext().getSourceManager().getPresumedLoc(
678          D->getLocation());
679      if (PLoc.isValid()) {
680        OS << " at " << PLoc.getFilename()
681           << ':' << PLoc.getLine()
682           << ':' << PLoc.getColumn();
683      }
684    }
685
686    OS << '>';
687  }
688
689  // If this is a class template specialization, print the template
690  // arguments.
691  if (ClassTemplateSpecializationDecl *Spec
692        = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
693    const TemplateArgument *Args;
694    unsigned NumArgs;
695    if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
696      const TemplateSpecializationType *TST =
697        cast<TemplateSpecializationType>(TAW->getType());
698      Args = TST->getArgs();
699      NumArgs = TST->getNumArgs();
700    } else {
701      const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
702      Args = TemplateArgs.data();
703      NumArgs = TemplateArgs.size();
704    }
705    IncludeStrongLifetimeRAII Strong(Policy);
706    Buffer += TemplateSpecializationType::PrintTemplateArgumentList(Args,
707                                                                    NumArgs,
708                                                                    Policy);
709  }
710
711  if (!InnerString.empty()) {
712    Buffer += ' ';
713    Buffer += InnerString;
714  }
715
716  std::swap(Buffer, InnerString);
717}
718
719void TypePrinter::printRecord(const RecordType *T, std::string &S) {
720  printTag(T->getDecl(), S);
721}
722
723void TypePrinter::printEnum(const EnumType *T, std::string &S) {
724  printTag(T->getDecl(), S);
725}
726
727void TypePrinter::printTemplateTypeParm(const TemplateTypeParmType *T,
728                                        std::string &S) {
729  if (!S.empty())    // Prefix the basic type, e.g. 'parmname X'.
730    S = ' ' + S;
731
732  if (IdentifierInfo *Id = T->getIdentifier())
733    S = Id->getName().str() + S;
734  else
735    S = "type-parameter-" + llvm::utostr_32(T->getDepth()) + '-' +
736        llvm::utostr_32(T->getIndex()) + S;
737}
738
739void TypePrinter::printSubstTemplateTypeParm(const SubstTemplateTypeParmType *T,
740                                             std::string &S) {
741  IncludeStrongLifetimeRAII Strong(Policy);
742  print(T->getReplacementType(), S);
743}
744
745void TypePrinter::printSubstTemplateTypeParmPack(
746                                        const SubstTemplateTypeParmPackType *T,
747                                             std::string &S) {
748  IncludeStrongLifetimeRAII Strong(Policy);
749  printTemplateTypeParm(T->getReplacedParameter(), S);
750}
751
752void TypePrinter::printTemplateSpecialization(
753                                            const TemplateSpecializationType *T,
754                                              std::string &S) {
755  IncludeStrongLifetimeRAII Strong(Policy);
756  std::string SpecString;
757
758  {
759    llvm::raw_string_ostream OS(SpecString);
760    T->getTemplateName().print(OS, Policy);
761  }
762
763  SpecString += TemplateSpecializationType::PrintTemplateArgumentList(
764                                                                  T->getArgs(),
765                                                                T->getNumArgs(),
766                                                                      Policy);
767  if (S.empty())
768    S.swap(SpecString);
769  else
770    S = SpecString + ' ' + S;
771}
772
773void TypePrinter::printInjectedClassName(const InjectedClassNameType *T,
774                                         std::string &S) {
775  printTemplateSpecialization(T->getInjectedTST(), S);
776}
777
778void TypePrinter::printElaborated(const ElaboratedType *T, std::string &S) {
779  std::string MyString;
780
781  {
782    llvm::raw_string_ostream OS(MyString);
783    OS << TypeWithKeyword::getKeywordName(T->getKeyword());
784    if (T->getKeyword() != ETK_None)
785      OS << " ";
786    NestedNameSpecifier* Qualifier = T->getQualifier();
787    if (Qualifier)
788      Qualifier->print(OS, Policy);
789  }
790
791  std::string TypeStr;
792  PrintingPolicy InnerPolicy(Policy);
793  InnerPolicy.SuppressTagKeyword = true;
794  InnerPolicy.SuppressScope = true;
795  TypePrinter(InnerPolicy).print(T->getNamedType(), TypeStr);
796
797  MyString += TypeStr;
798  if (S.empty())
799    S.swap(MyString);
800  else
801    S = MyString + ' ' + S;
802}
803
804void TypePrinter::printParen(const ParenType *T, std::string &S) {
805  if (!S.empty() && !isa<FunctionType>(T->getInnerType()))
806    S = '(' + S + ')';
807  print(T->getInnerType(), S);
808}
809
810void TypePrinter::printDependentName(const DependentNameType *T, std::string &S) {
811  std::string MyString;
812
813  {
814    llvm::raw_string_ostream OS(MyString);
815    OS << TypeWithKeyword::getKeywordName(T->getKeyword());
816    if (T->getKeyword() != ETK_None)
817      OS << " ";
818
819    T->getQualifier()->print(OS, Policy);
820
821    OS << T->getIdentifier()->getName();
822  }
823
824  if (S.empty())
825    S.swap(MyString);
826  else
827    S = MyString + ' ' + S;
828}
829
830void TypePrinter::printDependentTemplateSpecialization(
831        const DependentTemplateSpecializationType *T, std::string &S) {
832  IncludeStrongLifetimeRAII Strong(Policy);
833  std::string MyString;
834  {
835    llvm::raw_string_ostream OS(MyString);
836
837    OS << TypeWithKeyword::getKeywordName(T->getKeyword());
838    if (T->getKeyword() != ETK_None)
839      OS << " ";
840
841    if (T->getQualifier())
842      T->getQualifier()->print(OS, Policy);
843    OS << T->getIdentifier()->getName();
844    OS << TemplateSpecializationType::PrintTemplateArgumentList(
845                                                            T->getArgs(),
846                                                            T->getNumArgs(),
847                                                            Policy);
848  }
849
850  if (S.empty())
851    S.swap(MyString);
852  else
853    S = MyString + ' ' + S;
854}
855
856void TypePrinter::printPackExpansion(const PackExpansionType *T,
857                                     std::string &S) {
858  print(T->getPattern(), S);
859  S += "...";
860}
861
862void TypePrinter::printAttributed(const AttributedType *T,
863                                  std::string &S) {
864  // Prefer the macro forms of the GC and ownership qualifiers.
865  if (T->getAttrKind() == AttributedType::attr_objc_gc ||
866      T->getAttrKind() == AttributedType::attr_objc_ownership)
867    return print(T->getEquivalentType(), S);
868
869  print(T->getModifiedType(), S);
870
871  // TODO: not all attributes are GCC-style attributes.
872  S += " __attribute__((";
873  switch (T->getAttrKind()) {
874  case AttributedType::attr_address_space:
875    S += "address_space(";
876    S += T->getEquivalentType().getAddressSpace();
877    S += ")";
878    break;
879
880  case AttributedType::attr_vector_size: {
881    S += "__vector_size__(";
882    if (const VectorType *vector =T->getEquivalentType()->getAs<VectorType>()) {
883      S += vector->getNumElements();
884      S += " * sizeof(";
885
886      std::string tmp;
887      print(vector->getElementType(), tmp);
888      S += tmp;
889      S += ")";
890    }
891    S += ")";
892    break;
893  }
894
895  case AttributedType::attr_neon_vector_type:
896  case AttributedType::attr_neon_polyvector_type: {
897    if (T->getAttrKind() == AttributedType::attr_neon_vector_type)
898      S += "neon_vector_type(";
899    else
900      S += "neon_polyvector_type(";
901    const VectorType *vector = T->getEquivalentType()->getAs<VectorType>();
902    S += llvm::utostr_32(vector->getNumElements());
903    S += ")";
904    break;
905  }
906
907  case AttributedType::attr_regparm: {
908    S += "regparm(";
909    QualType t = T->getEquivalentType();
910    while (!t->isFunctionType())
911      t = t->getPointeeType();
912    S += t->getAs<FunctionType>()->getRegParmType();
913    S += ")";
914    break;
915  }
916
917  case AttributedType::attr_objc_gc: {
918    S += "objc_gc(";
919
920    QualType tmp = T->getEquivalentType();
921    while (tmp.getObjCGCAttr() == Qualifiers::GCNone) {
922      QualType next = tmp->getPointeeType();
923      if (next == tmp) break;
924      tmp = next;
925    }
926
927    if (tmp.isObjCGCWeak())
928      S += "weak";
929    else
930      S += "strong";
931    S += ")";
932    break;
933  }
934
935  case AttributedType::attr_objc_ownership:
936    S += "objc_ownership(";
937    switch (T->getEquivalentType().getObjCLifetime()) {
938    case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); break;
939    case Qualifiers::OCL_ExplicitNone: S += "none"; break;
940    case Qualifiers::OCL_Strong: S += "strong"; break;
941    case Qualifiers::OCL_Weak: S += "weak"; break;
942    case Qualifiers::OCL_Autoreleasing: S += "autoreleasing"; break;
943    }
944    S += ")";
945    break;
946
947  case AttributedType::attr_noreturn: S += "noreturn"; break;
948  case AttributedType::attr_cdecl: S += "cdecl"; break;
949  case AttributedType::attr_fastcall: S += "fastcall"; break;
950  case AttributedType::attr_stdcall: S += "stdcall"; break;
951  case AttributedType::attr_thiscall: S += "thiscall"; break;
952  case AttributedType::attr_pascal: S += "pascal"; break;
953  case AttributedType::attr_pcs: {
954   S += "pcs(";
955   QualType t = T->getEquivalentType();
956   while (!t->isFunctionType())
957     t = t->getPointeeType();
958   S += (t->getAs<FunctionType>()->getCallConv() == CC_AAPCS ?
959         "\"aapcs\"" : "\"aapcs-vfp\"");
960   S += ")";
961   break;
962  }
963  }
964  S += "))";
965}
966
967void TypePrinter::printObjCInterface(const ObjCInterfaceType *T,
968                                     std::string &S) {
969  if (!S.empty())    // Prefix the basic type, e.g. 'typedefname X'.
970    S = ' ' + S;
971
972  std::string ObjCQIString = T->getDecl()->getNameAsString();
973  S = ObjCQIString + S;
974}
975
976void TypePrinter::printObjCObject(const ObjCObjectType *T,
977                                  std::string &S) {
978  if (T->qual_empty())
979    return print(T->getBaseType(), S);
980
981  std::string tmp;
982  print(T->getBaseType(), tmp);
983  tmp += '<';
984  bool isFirst = true;
985  for (ObjCObjectType::qual_iterator
986         I = T->qual_begin(), E = T->qual_end(); I != E; ++I) {
987    if (isFirst)
988      isFirst = false;
989    else
990      tmp += ',';
991    tmp += (*I)->getNameAsString();
992  }
993  tmp += '>';
994
995  if (!S.empty()) {
996    tmp += ' ';
997    tmp += S;
998  }
999  std::swap(tmp, S);
1000}
1001
1002void TypePrinter::printObjCObjectPointer(const ObjCObjectPointerType *T,
1003                                         std::string &S) {
1004  std::string ObjCQIString;
1005
1006  T->getPointeeType().getLocalQualifiers().getAsStringInternal(ObjCQIString,
1007                                                               Policy);
1008  if (!ObjCQIString.empty())
1009    ObjCQIString += ' ';
1010
1011  if (T->isObjCIdType() || T->isObjCQualifiedIdType())
1012    ObjCQIString += "id";
1013  else if (T->isObjCClassType() || T->isObjCQualifiedClassType())
1014    ObjCQIString += "Class";
1015  else if (T->isObjCSelType())
1016    ObjCQIString += "SEL";
1017  else
1018    ObjCQIString += T->getInterfaceDecl()->getNameAsString();
1019
1020  if (!T->qual_empty()) {
1021    ObjCQIString += '<';
1022    for (ObjCObjectPointerType::qual_iterator I = T->qual_begin(),
1023                                              E = T->qual_end();
1024         I != E; ++I) {
1025      ObjCQIString += (*I)->getNameAsString();
1026      if (I+1 != E)
1027        ObjCQIString += ',';
1028    }
1029    ObjCQIString += '>';
1030  }
1031
1032  if (!T->isObjCIdType() && !T->isObjCQualifiedIdType())
1033    ObjCQIString += " *"; // Don't forget the implicit pointer.
1034  else if (!S.empty()) // Prefix the basic type, e.g. 'typedefname X'.
1035    S = ' ' + S;
1036
1037  S = ObjCQIString + S;
1038}
1039
1040std::string TemplateSpecializationType::
1041  PrintTemplateArgumentList(const TemplateArgumentListInfo &Args,
1042                            const PrintingPolicy &Policy) {
1043  return PrintTemplateArgumentList(Args.getArgumentArray(),
1044                                   Args.size(),
1045                                   Policy);
1046}
1047
1048std::string
1049TemplateSpecializationType::PrintTemplateArgumentList(
1050                                                const TemplateArgument *Args,
1051                                                unsigned NumArgs,
1052                                                  const PrintingPolicy &Policy,
1053                                                      bool SkipBrackets) {
1054  std::string SpecString;
1055  if (!SkipBrackets)
1056    SpecString += '<';
1057
1058  for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1059    if (SpecString.size() > unsigned(!SkipBrackets))
1060      SpecString += ", ";
1061
1062    // Print the argument into a string.
1063    std::string ArgString;
1064    if (Args[Arg].getKind() == TemplateArgument::Pack) {
1065      ArgString = PrintTemplateArgumentList(Args[Arg].pack_begin(),
1066                                            Args[Arg].pack_size(),
1067                                            Policy, true);
1068    } else {
1069      llvm::raw_string_ostream ArgOut(ArgString);
1070      Args[Arg].print(Policy, ArgOut);
1071    }
1072
1073    // If this is the first argument and its string representation
1074    // begins with the global scope specifier ('::foo'), add a space
1075    // to avoid printing the diagraph '<:'.
1076    if (!Arg && !ArgString.empty() && ArgString[0] == ':')
1077      SpecString += ' ';
1078
1079    SpecString += ArgString;
1080  }
1081
1082  // If the last character of our string is '>', add another space to
1083  // keep the two '>''s separate tokens. We don't *have* to do this in
1084  // C++0x, but it's still good hygiene.
1085  if (!SpecString.empty() && SpecString[SpecString.size() - 1] == '>')
1086    SpecString += ' ';
1087
1088  if (!SkipBrackets)
1089    SpecString += '>';
1090
1091  return SpecString;
1092}
1093
1094// Sadly, repeat all that with TemplateArgLoc.
1095std::string TemplateSpecializationType::
1096PrintTemplateArgumentList(const TemplateArgumentLoc *Args, unsigned NumArgs,
1097                          const PrintingPolicy &Policy) {
1098  std::string SpecString;
1099  SpecString += '<';
1100  for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1101    if (SpecString.size() > 1)
1102      SpecString += ", ";
1103
1104    // Print the argument into a string.
1105    std::string ArgString;
1106    if (Args[Arg].getArgument().getKind() == TemplateArgument::Pack) {
1107      ArgString = PrintTemplateArgumentList(
1108                                           Args[Arg].getArgument().pack_begin(),
1109                                            Args[Arg].getArgument().pack_size(),
1110                                            Policy, true);
1111    } else {
1112      llvm::raw_string_ostream ArgOut(ArgString);
1113      Args[Arg].getArgument().print(Policy, ArgOut);
1114    }
1115
1116    // If this is the first argument and its string representation
1117    // begins with the global scope specifier ('::foo'), add a space
1118    // to avoid printing the diagraph '<:'.
1119    if (!Arg && !ArgString.empty() && ArgString[0] == ':')
1120      SpecString += ' ';
1121
1122    SpecString += ArgString;
1123  }
1124
1125  // If the last character of our string is '>', add another space to
1126  // keep the two '>''s separate tokens. We don't *have* to do this in
1127  // C++0x, but it's still good hygiene.
1128  if (SpecString[SpecString.size() - 1] == '>')
1129    SpecString += ' ';
1130
1131  SpecString += '>';
1132
1133  return SpecString;
1134}
1135
1136void QualType::dump(const char *msg) const {
1137  std::string R = "identifier";
1138  LangOptions LO;
1139  getAsStringInternal(R, PrintingPolicy(LO));
1140  if (msg)
1141    llvm::errs() << msg << ": ";
1142  llvm::errs() << R << "\n";
1143}
1144void QualType::dump() const {
1145  dump("");
1146}
1147
1148void Type::dump() const {
1149  QualType(this, 0).dump();
1150}
1151
1152std::string Qualifiers::getAsString() const {
1153  LangOptions LO;
1154  return getAsString(PrintingPolicy(LO));
1155}
1156
1157// Appends qualifiers to the given string, separated by spaces.  Will
1158// prefix a space if the string is non-empty.  Will not append a final
1159// space.
1160void Qualifiers::getAsStringInternal(std::string &S,
1161                                     const PrintingPolicy& Policy) const {
1162  AppendTypeQualList(S, getCVRQualifiers());
1163  if (unsigned addrspace = getAddressSpace()) {
1164    if (!S.empty()) S += ' ';
1165    switch (addrspace) {
1166      case LangAS::opencl_global:
1167        S += "__global";
1168        break;
1169      case LangAS::opencl_local:
1170        S += "__local";
1171        break;
1172      case LangAS::opencl_constant:
1173        S += "__constant";
1174        break;
1175      default:
1176        S += "__attribute__((address_space(";
1177        S += llvm::utostr_32(addrspace);
1178        S += ")))";
1179    }
1180  }
1181  if (Qualifiers::GC gc = getObjCGCAttr()) {
1182    if (!S.empty()) S += ' ';
1183    if (gc == Qualifiers::Weak)
1184      S += "__weak";
1185    else
1186      S += "__strong";
1187  }
1188  if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime()) {
1189    if (!S.empty() &&
1190        !(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime))
1191      S += ' ';
1192
1193    switch (lifetime) {
1194    case Qualifiers::OCL_None: llvm_unreachable("none but true");
1195    case Qualifiers::OCL_ExplicitNone: S += "__unsafe_unretained"; break;
1196    case Qualifiers::OCL_Strong:
1197      if (!Policy.SuppressStrongLifetime)
1198        S += "__strong";
1199      break;
1200
1201    case Qualifiers::OCL_Weak: S += "__weak"; break;
1202    case Qualifiers::OCL_Autoreleasing: S += "__autoreleasing"; break;
1203    }
1204  }
1205}
1206
1207std::string QualType::getAsString(const Type *ty, Qualifiers qs) {
1208  std::string buffer;
1209  LangOptions options;
1210  getAsStringInternal(ty, qs, buffer, PrintingPolicy(options));
1211  return buffer;
1212}
1213
1214void QualType::getAsStringInternal(const Type *ty, Qualifiers qs,
1215                                   std::string &buffer,
1216                                   const PrintingPolicy &policy) {
1217  TypePrinter(policy).print(ty, qs, buffer);
1218}
1219