xref: /freebsd/contrib/llvm-project/clang/lib/AST/TemplateBase.cpp (revision 0d8fe2373503aeac48492f28073049a8bfa4feb5)
1 //===- TemplateBase.cpp - Common template AST class implementation --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements common classes used throughout C++ template
10 // representations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/TemplateBase.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclBase.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/DependenceFlags.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/PrettyPrinter.h"
23 #include "clang/AST/TemplateName.h"
24 #include "clang/AST/Type.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/Basic/Diagnostic.h"
27 #include "clang/Basic/LLVM.h"
28 #include "clang/Basic/LangOptions.h"
29 #include "clang/Basic/SourceLocation.h"
30 #include "llvm/ADT/APSInt.h"
31 #include "llvm/ADT/FoldingSet.h"
32 #include "llvm/ADT/None.h"
33 #include "llvm/ADT/SmallString.h"
34 #include "llvm/ADT/StringRef.h"
35 #include "llvm/Support/Casting.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include <cassert>
40 #include <cstddef>
41 #include <cstdint>
42 #include <cstring>
43 
44 using namespace clang;
45 
46 /// Print a template integral argument value.
47 ///
48 /// \param TemplArg the TemplateArgument instance to print.
49 ///
50 /// \param Out the raw_ostream instance to use for printing.
51 ///
52 /// \param Policy the printing policy for EnumConstantDecl printing.
53 static void printIntegral(const TemplateArgument &TemplArg,
54                           raw_ostream &Out, const PrintingPolicy& Policy) {
55   const Type *T = TemplArg.getIntegralType().getTypePtr();
56   const llvm::APSInt &Val = TemplArg.getAsIntegral();
57 
58   if (const EnumType *ET = T->getAs<EnumType>()) {
59     for (const EnumConstantDecl* ECD : ET->getDecl()->enumerators()) {
60       // In Sema::CheckTemplateArugment, enum template arguments value are
61       // extended to the size of the integer underlying the enum type.  This
62       // may create a size difference between the enum value and template
63       // argument value, requiring isSameValue here instead of operator==.
64       if (llvm::APSInt::isSameValue(ECD->getInitVal(), Val)) {
65         ECD->printQualifiedName(Out, Policy);
66         return;
67       }
68     }
69   }
70 
71   if (T->isBooleanType() && !Policy.MSVCFormatting) {
72     Out << (Val.getBoolValue() ? "true" : "false");
73   } else if (T->isCharType()) {
74     const char Ch = Val.getZExtValue();
75     Out << ((Ch == '\'') ? "'\\" : "'");
76     Out.write_escaped(StringRef(&Ch, 1), /*UseHexEscapes=*/ true);
77     Out << "'";
78   } else {
79     Out << Val;
80   }
81 }
82 
83 //===----------------------------------------------------------------------===//
84 // TemplateArgument Implementation
85 //===----------------------------------------------------------------------===//
86 
87 TemplateArgument::TemplateArgument(ASTContext &Ctx, const llvm::APSInt &Value,
88                                    QualType Type) {
89   Integer.Kind = Integral;
90   // Copy the APSInt value into our decomposed form.
91   Integer.BitWidth = Value.getBitWidth();
92   Integer.IsUnsigned = Value.isUnsigned();
93   // If the value is large, we have to get additional memory from the ASTContext
94   unsigned NumWords = Value.getNumWords();
95   if (NumWords > 1) {
96     void *Mem = Ctx.Allocate(NumWords * sizeof(uint64_t));
97     std::memcpy(Mem, Value.getRawData(), NumWords * sizeof(uint64_t));
98     Integer.pVal = static_cast<uint64_t *>(Mem);
99   } else {
100     Integer.VAL = Value.getZExtValue();
101   }
102 
103   Integer.Type = Type.getAsOpaquePtr();
104 }
105 
106 TemplateArgument
107 TemplateArgument::CreatePackCopy(ASTContext &Context,
108                                  ArrayRef<TemplateArgument> Args) {
109   if (Args.empty())
110     return getEmptyPack();
111 
112   return TemplateArgument(Args.copy(Context));
113 }
114 
115 TemplateArgumentDependence TemplateArgument::getDependence() const {
116   auto Deps = TemplateArgumentDependence::None;
117   switch (getKind()) {
118   case Null:
119     llvm_unreachable("Should not have a NULL template argument");
120 
121   case Type:
122     Deps = toTemplateArgumentDependence(getAsType()->getDependence());
123     if (isa<PackExpansionType>(getAsType()))
124       Deps |= TemplateArgumentDependence::Dependent;
125     return Deps;
126 
127   case Template:
128     return toTemplateArgumentDependence(getAsTemplate().getDependence());
129 
130   case TemplateExpansion:
131     return TemplateArgumentDependence::Dependent |
132            TemplateArgumentDependence::Instantiation;
133 
134   case Declaration: {
135     auto *DC = dyn_cast<DeclContext>(getAsDecl());
136     if (!DC)
137       DC = getAsDecl()->getDeclContext();
138     if (DC->isDependentContext())
139       Deps = TemplateArgumentDependence::Dependent |
140              TemplateArgumentDependence::Instantiation;
141     return Deps;
142   }
143 
144   case NullPtr:
145   case Integral:
146     return TemplateArgumentDependence::None;
147 
148   case Expression:
149     Deps = toTemplateArgumentDependence(getAsExpr()->getDependence());
150     if (isa<PackExpansionExpr>(getAsExpr()))
151       Deps |= TemplateArgumentDependence::Dependent |
152               TemplateArgumentDependence::Instantiation;
153     return Deps;
154 
155   case Pack:
156     for (const auto &P : pack_elements())
157       Deps |= P.getDependence();
158     return Deps;
159   }
160   llvm_unreachable("unhandled ArgKind");
161 }
162 
163 bool TemplateArgument::isDependent() const {
164   return getDependence() & TemplateArgumentDependence::Dependent;
165 }
166 
167 bool TemplateArgument::isInstantiationDependent() const {
168   return getDependence() & TemplateArgumentDependence::Instantiation;
169 }
170 
171 bool TemplateArgument::isPackExpansion() const {
172   switch (getKind()) {
173   case Null:
174   case Declaration:
175   case Integral:
176   case Pack:
177   case Template:
178   case NullPtr:
179     return false;
180 
181   case TemplateExpansion:
182     return true;
183 
184   case Type:
185     return isa<PackExpansionType>(getAsType());
186 
187   case Expression:
188     return isa<PackExpansionExpr>(getAsExpr());
189   }
190 
191   llvm_unreachable("Invalid TemplateArgument Kind!");
192 }
193 
194 bool TemplateArgument::containsUnexpandedParameterPack() const {
195   return getDependence() & TemplateArgumentDependence::UnexpandedPack;
196 }
197 
198 Optional<unsigned> TemplateArgument::getNumTemplateExpansions() const {
199   assert(getKind() == TemplateExpansion);
200   if (TemplateArg.NumExpansions)
201     return TemplateArg.NumExpansions - 1;
202 
203   return None;
204 }
205 
206 QualType TemplateArgument::getNonTypeTemplateArgumentType() const {
207   switch (getKind()) {
208   case TemplateArgument::Null:
209   case TemplateArgument::Type:
210   case TemplateArgument::Template:
211   case TemplateArgument::TemplateExpansion:
212   case TemplateArgument::Pack:
213     return QualType();
214 
215   case TemplateArgument::Integral:
216     return getIntegralType();
217 
218   case TemplateArgument::Expression:
219     return getAsExpr()->getType();
220 
221   case TemplateArgument::Declaration:
222     return getParamTypeForDecl();
223 
224   case TemplateArgument::NullPtr:
225     return getNullPtrType();
226   }
227 
228   llvm_unreachable("Invalid TemplateArgument Kind!");
229 }
230 
231 void TemplateArgument::Profile(llvm::FoldingSetNodeID &ID,
232                                const ASTContext &Context) const {
233   ID.AddInteger(getKind());
234   switch (getKind()) {
235   case Null:
236     break;
237 
238   case Type:
239     getAsType().Profile(ID);
240     break;
241 
242   case NullPtr:
243     getNullPtrType().Profile(ID);
244     break;
245 
246   case Declaration:
247     getParamTypeForDecl().Profile(ID);
248     ID.AddPointer(getAsDecl()? getAsDecl()->getCanonicalDecl() : nullptr);
249     break;
250 
251   case Template:
252   case TemplateExpansion: {
253     TemplateName Template = getAsTemplateOrTemplatePattern();
254     if (TemplateTemplateParmDecl *TTP
255           = dyn_cast_or_null<TemplateTemplateParmDecl>(
256                                                 Template.getAsTemplateDecl())) {
257       ID.AddBoolean(true);
258       ID.AddInteger(TTP->getDepth());
259       ID.AddInteger(TTP->getPosition());
260       ID.AddBoolean(TTP->isParameterPack());
261     } else {
262       ID.AddBoolean(false);
263       ID.AddPointer(Context.getCanonicalTemplateName(Template)
264                                                           .getAsVoidPointer());
265     }
266     break;
267   }
268 
269   case Integral:
270     getAsIntegral().Profile(ID);
271     getIntegralType().Profile(ID);
272     break;
273 
274   case Expression:
275     getAsExpr()->Profile(ID, Context, true);
276     break;
277 
278   case Pack:
279     ID.AddInteger(Args.NumArgs);
280     for (unsigned I = 0; I != Args.NumArgs; ++I)
281       Args.Args[I].Profile(ID, Context);
282   }
283 }
284 
285 bool TemplateArgument::structurallyEquals(const TemplateArgument &Other) const {
286   if (getKind() != Other.getKind()) return false;
287 
288   switch (getKind()) {
289   case Null:
290   case Type:
291   case Expression:
292   case NullPtr:
293     return TypeOrValue.V == Other.TypeOrValue.V;
294 
295   case Template:
296   case TemplateExpansion:
297     return TemplateArg.Name == Other.TemplateArg.Name &&
298            TemplateArg.NumExpansions == Other.TemplateArg.NumExpansions;
299 
300   case Declaration:
301     return getAsDecl() == Other.getAsDecl();
302 
303   case Integral:
304     return getIntegralType() == Other.getIntegralType() &&
305            getAsIntegral() == Other.getAsIntegral();
306 
307   case Pack:
308     if (Args.NumArgs != Other.Args.NumArgs) return false;
309     for (unsigned I = 0, E = Args.NumArgs; I != E; ++I)
310       if (!Args.Args[I].structurallyEquals(Other.Args.Args[I]))
311         return false;
312     return true;
313   }
314 
315   llvm_unreachable("Invalid TemplateArgument Kind!");
316 }
317 
318 TemplateArgument TemplateArgument::getPackExpansionPattern() const {
319   assert(isPackExpansion());
320 
321   switch (getKind()) {
322   case Type:
323     return getAsType()->castAs<PackExpansionType>()->getPattern();
324 
325   case Expression:
326     return cast<PackExpansionExpr>(getAsExpr())->getPattern();
327 
328   case TemplateExpansion:
329     return TemplateArgument(getAsTemplateOrTemplatePattern());
330 
331   case Declaration:
332   case Integral:
333   case Pack:
334   case Null:
335   case Template:
336   case NullPtr:
337     return TemplateArgument();
338   }
339 
340   llvm_unreachable("Invalid TemplateArgument Kind!");
341 }
342 
343 void TemplateArgument::print(const PrintingPolicy &Policy,
344                              raw_ostream &Out) const {
345   switch (getKind()) {
346   case Null:
347     Out << "(no value)";
348     break;
349 
350   case Type: {
351     PrintingPolicy SubPolicy(Policy);
352     SubPolicy.SuppressStrongLifetime = true;
353     getAsType().print(Out, SubPolicy);
354     break;
355   }
356 
357   case Declaration: {
358     NamedDecl *ND = getAsDecl();
359     if (getParamTypeForDecl()->isRecordType()) {
360       if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
361         // FIXME: Include the type if it's not obvious from the context.
362         TPO->printAsInit(Out);
363         break;
364       }
365     }
366     if (!getParamTypeForDecl()->isReferenceType())
367       Out << '&';
368     ND->printQualifiedName(Out);
369     break;
370   }
371 
372   case NullPtr:
373     Out << "nullptr";
374     break;
375 
376   case Template:
377     getAsTemplate().print(Out, Policy);
378     break;
379 
380   case TemplateExpansion:
381     getAsTemplateOrTemplatePattern().print(Out, Policy);
382     Out << "...";
383     break;
384 
385   case Integral:
386     printIntegral(*this, Out, Policy);
387     break;
388 
389   case Expression:
390     getAsExpr()->printPretty(Out, nullptr, Policy);
391     break;
392 
393   case Pack:
394     Out << "<";
395     bool First = true;
396     for (const auto &P : pack_elements()) {
397       if (First)
398         First = false;
399       else
400         Out << ", ";
401 
402       P.print(Policy, Out);
403     }
404     Out << ">";
405     break;
406   }
407 }
408 
409 void TemplateArgument::dump(raw_ostream &Out) const {
410   LangOptions LO; // FIXME! see also TemplateName::dump().
411   LO.CPlusPlus = true;
412   LO.Bool = true;
413   print(PrintingPolicy(LO), Out);
414 }
415 
416 LLVM_DUMP_METHOD void TemplateArgument::dump() const { dump(llvm::errs()); }
417 
418 //===----------------------------------------------------------------------===//
419 // TemplateArgumentLoc Implementation
420 //===----------------------------------------------------------------------===//
421 
422 SourceRange TemplateArgumentLoc::getSourceRange() const {
423   switch (Argument.getKind()) {
424   case TemplateArgument::Expression:
425     return getSourceExpression()->getSourceRange();
426 
427   case TemplateArgument::Declaration:
428     return getSourceDeclExpression()->getSourceRange();
429 
430   case TemplateArgument::NullPtr:
431     return getSourceNullPtrExpression()->getSourceRange();
432 
433   case TemplateArgument::Type:
434     if (TypeSourceInfo *TSI = getTypeSourceInfo())
435       return TSI->getTypeLoc().getSourceRange();
436     else
437       return SourceRange();
438 
439   case TemplateArgument::Template:
440     if (getTemplateQualifierLoc())
441       return SourceRange(getTemplateQualifierLoc().getBeginLoc(),
442                          getTemplateNameLoc());
443     return SourceRange(getTemplateNameLoc());
444 
445   case TemplateArgument::TemplateExpansion:
446     if (getTemplateQualifierLoc())
447       return SourceRange(getTemplateQualifierLoc().getBeginLoc(),
448                          getTemplateEllipsisLoc());
449     return SourceRange(getTemplateNameLoc(), getTemplateEllipsisLoc());
450 
451   case TemplateArgument::Integral:
452     return getSourceIntegralExpression()->getSourceRange();
453 
454   case TemplateArgument::Pack:
455   case TemplateArgument::Null:
456     return SourceRange();
457   }
458 
459   llvm_unreachable("Invalid TemplateArgument Kind!");
460 }
461 
462 template <typename T>
463 static const T &DiagTemplateArg(const T &DB, const TemplateArgument &Arg) {
464   switch (Arg.getKind()) {
465   case TemplateArgument::Null:
466     // This is bad, but not as bad as crashing because of argument
467     // count mismatches.
468     return DB << "(null template argument)";
469 
470   case TemplateArgument::Type:
471     return DB << Arg.getAsType();
472 
473   case TemplateArgument::Declaration:
474     return DB << Arg.getAsDecl();
475 
476   case TemplateArgument::NullPtr:
477     return DB << "nullptr";
478 
479   case TemplateArgument::Integral:
480     return DB << Arg.getAsIntegral().toString(10);
481 
482   case TemplateArgument::Template:
483     return DB << Arg.getAsTemplate();
484 
485   case TemplateArgument::TemplateExpansion:
486     return DB << Arg.getAsTemplateOrTemplatePattern() << "...";
487 
488   case TemplateArgument::Expression: {
489     // This shouldn't actually ever happen, so it's okay that we're
490     // regurgitating an expression here.
491     // FIXME: We're guessing at LangOptions!
492     SmallString<32> Str;
493     llvm::raw_svector_ostream OS(Str);
494     LangOptions LangOpts;
495     LangOpts.CPlusPlus = true;
496     PrintingPolicy Policy(LangOpts);
497     Arg.getAsExpr()->printPretty(OS, nullptr, Policy);
498     return DB << OS.str();
499   }
500 
501   case TemplateArgument::Pack: {
502     // FIXME: We're guessing at LangOptions!
503     SmallString<32> Str;
504     llvm::raw_svector_ostream OS(Str);
505     LangOptions LangOpts;
506     LangOpts.CPlusPlus = true;
507     PrintingPolicy Policy(LangOpts);
508     Arg.print(Policy, OS);
509     return DB << OS.str();
510   }
511   }
512 
513   llvm_unreachable("Invalid TemplateArgument Kind!");
514 }
515 
516 const StreamingDiagnostic &clang::operator<<(const StreamingDiagnostic &DB,
517                                              const TemplateArgument &Arg) {
518   return DiagTemplateArg(DB, Arg);
519 }
520 
521 clang::TemplateArgumentLocInfo::TemplateArgumentLocInfo(
522     ASTContext &Ctx, NestedNameSpecifierLoc QualifierLoc,
523     SourceLocation TemplateNameLoc, SourceLocation EllipsisLoc) {
524   TemplateTemplateArgLocInfo *Template = new (Ctx) TemplateTemplateArgLocInfo;
525   Template->Qualifier = QualifierLoc.getNestedNameSpecifier();
526   Template->QualifierLocData = QualifierLoc.getOpaqueData();
527   Template->TemplateNameLoc = TemplateNameLoc;
528   Template->EllipsisLoc = EllipsisLoc;
529   Pointer = Template;
530 }
531 
532 const ASTTemplateArgumentListInfo *
533 ASTTemplateArgumentListInfo::Create(const ASTContext &C,
534                                     const TemplateArgumentListInfo &List) {
535   std::size_t size = totalSizeToAlloc<TemplateArgumentLoc>(List.size());
536   void *Mem = C.Allocate(size, alignof(ASTTemplateArgumentListInfo));
537   return new (Mem) ASTTemplateArgumentListInfo(List);
538 }
539 
540 ASTTemplateArgumentListInfo::ASTTemplateArgumentListInfo(
541     const TemplateArgumentListInfo &Info) {
542   LAngleLoc = Info.getLAngleLoc();
543   RAngleLoc = Info.getRAngleLoc();
544   NumTemplateArgs = Info.size();
545 
546   TemplateArgumentLoc *ArgBuffer = getTrailingObjects<TemplateArgumentLoc>();
547   for (unsigned i = 0; i != NumTemplateArgs; ++i)
548     new (&ArgBuffer[i]) TemplateArgumentLoc(Info[i]);
549 }
550 
551 void ASTTemplateKWAndArgsInfo::initializeFrom(
552     SourceLocation TemplateKWLoc, const TemplateArgumentListInfo &Info,
553     TemplateArgumentLoc *OutArgArray) {
554   this->TemplateKWLoc = TemplateKWLoc;
555   LAngleLoc = Info.getLAngleLoc();
556   RAngleLoc = Info.getRAngleLoc();
557   NumTemplateArgs = Info.size();
558 
559   for (unsigned i = 0; i != NumTemplateArgs; ++i)
560     new (&OutArgArray[i]) TemplateArgumentLoc(Info[i]);
561 }
562 
563 void ASTTemplateKWAndArgsInfo::initializeFrom(SourceLocation TemplateKWLoc) {
564   assert(TemplateKWLoc.isValid());
565   LAngleLoc = SourceLocation();
566   RAngleLoc = SourceLocation();
567   this->TemplateKWLoc = TemplateKWLoc;
568   NumTemplateArgs = 0;
569 }
570 
571 void ASTTemplateKWAndArgsInfo::initializeFrom(
572     SourceLocation TemplateKWLoc, const TemplateArgumentListInfo &Info,
573     TemplateArgumentLoc *OutArgArray, TemplateArgumentDependence &Deps) {
574   this->TemplateKWLoc = TemplateKWLoc;
575   LAngleLoc = Info.getLAngleLoc();
576   RAngleLoc = Info.getRAngleLoc();
577   NumTemplateArgs = Info.size();
578 
579   for (unsigned i = 0; i != NumTemplateArgs; ++i) {
580     Deps |= Info[i].getArgument().getDependence();
581 
582     new (&OutArgArray[i]) TemplateArgumentLoc(Info[i]);
583   }
584 }
585 
586 void ASTTemplateKWAndArgsInfo::copyInto(const TemplateArgumentLoc *ArgArray,
587                                         TemplateArgumentListInfo &Info) const {
588   Info.setLAngleLoc(LAngleLoc);
589   Info.setRAngleLoc(RAngleLoc);
590   for (unsigned I = 0; I != NumTemplateArgs; ++I)
591     Info.addArgument(ArgArray[I]);
592 }
593