xref: /llvm-project/clang/lib/Frontend/InterfaceStubFunctionsConsumer.cpp (revision dc5f805d31f62e094bd3eb105b47620633f65e5b)
1 //===--- InterfaceStubFunctionsConsumer.cpp -------------------------------===//
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 #include "clang/AST/Mangle.h"
10 #include "clang/AST/RecursiveASTVisitor.h"
11 #include "clang/Frontend/CompilerInstance.h"
12 #include "clang/Frontend/FrontendActions.h"
13 #include "clang/Sema/TemplateInstCallback.h"
14 #include "llvm/BinaryFormat/ELF.h"
15 
16 using namespace clang;
17 
18 namespace {
19 class InterfaceStubFunctionsConsumer : public ASTConsumer {
20   CompilerInstance &Instance;
21   StringRef InFile;
22   StringRef Format;
23   std::set<std::string> ParsedTemplates;
24 
25   enum RootDeclOrigin { TopLevel = 0, FromTU = 1, IsLate = 2 };
26   struct MangledSymbol {
27     std::string ParentName;
28     uint8_t Type;
29     uint8_t Binding;
30     std::vector<std::string> Names;
31     MangledSymbol() = delete;
32 
33     MangledSymbol(const std::string &ParentName, uint8_t Type, uint8_t Binding,
34                   std::vector<std::string> Names)
35         : ParentName(ParentName), Type(Type), Binding(Binding), Names(Names) {}
36   };
37   using MangledSymbols = std::map<const NamedDecl *, MangledSymbol>;
38 
39   bool WriteNamedDecl(const NamedDecl *ND, MangledSymbols &Symbols, int RDO) {
40     // Here we filter out anything that's not set to DefaultVisibility.
41     // DefaultVisibility is set on a decl when -fvisibility is not specified on
42     // the command line (or specified as default) and the decl does not have
43     // __attribute__((visibility("hidden"))) set or when the command line
44     // argument is set to hidden but the decl explicitly has
45     // __attribute__((visibility ("default"))) set. We do this so that the user
46     // can have fine grain control of what they want to expose in the stub.
47     auto isVisible = [](const NamedDecl *ND) -> bool {
48       return ND->getVisibility() == DefaultVisibility;
49     };
50 
51     auto ignoreDecl = [this, isVisible](const NamedDecl *ND) -> bool {
52       if (!isVisible(ND))
53         return true;
54 
55       if (const VarDecl *VD = dyn_cast<VarDecl>(ND))
56         if ((VD->getStorageClass() == StorageClass::SC_Extern) ||
57             (VD->getStorageClass() == StorageClass::SC_Static &&
58              VD->getParentFunctionOrMethod() == nullptr))
59           return true;
60 
61       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
62         if (FD->isInlined() && !isa<CXXMethodDecl>(FD) &&
63             !Instance.getLangOpts().GNUInline)
64           return true;
65         if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
66           if (const auto *RC = dyn_cast<CXXRecordDecl>(MD->getParent()))
67             if (isa<ClassTemplateDecl>(RC->getParent()) || !isVisible(RC))
68               return true;
69           if (MD->isDependentContext() || !MD->hasBody())
70             return true;
71         }
72         if (FD->getStorageClass() == StorageClass::SC_Static)
73           return true;
74       }
75       return false;
76     };
77 
78     auto getParentFunctionDecl = [](const NamedDecl *ND) -> const NamedDecl * {
79       if (const VarDecl *VD = dyn_cast<VarDecl>(ND))
80         if (const auto *FD =
81                 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()))
82           return FD;
83       return nullptr;
84     };
85 
86     auto getMangledNames = [](const NamedDecl *ND) -> std::vector<std::string> {
87       if (!ND)
88         return {""};
89       ASTNameGenerator NameGen(ND->getASTContext());
90       std::vector<std::string> MangledNames = NameGen.getAllManglings(ND);
91       if (isa<CXXConstructorDecl>(ND) || isa<CXXDestructorDecl>(ND))
92         return MangledNames;
93 #ifdef EXPENSIVE_CHECKS
94       assert(MangledNames.size() <= 1 && "Expected only one name mangling.");
95 #endif
96       return {NameGen.getName(ND)};
97     };
98 
99     if (!(RDO & FromTU))
100       return true;
101     if (Symbols.find(ND) != Symbols.end())
102       return true;
103     // - Currently have not figured out how to produce the names for FieldDecls.
104     // - Do not want to produce symbols for function paremeters.
105     if (isa<FieldDecl>(ND) || isa<ParmVarDecl>(ND))
106       return true;
107 
108     const NamedDecl *ParentDecl = getParentFunctionDecl(ND);
109     if ((ParentDecl && ignoreDecl(ParentDecl)) || ignoreDecl(ND))
110       return true;
111 
112     if (RDO & IsLate) {
113       Instance.getDiagnostics().Report(diag::err_asm_invalid_type_in_input)
114           << "Generating Interface Stubs is not supported with "
115              "delayed template parsing.";
116     } else {
117       if (const auto *FD = dyn_cast<FunctionDecl>(ND))
118         if (FD->isDependentContext())
119           return true;
120 
121       const bool IsWeak = (ND->hasAttr<WeakAttr>() ||
122                            ND->hasAttr<WeakRefAttr>() || ND->isWeakImported());
123 
124       Symbols.insert(std::make_pair(
125           ND,
126           MangledSymbol(getMangledNames(ParentDecl).front(),
127                         // Type:
128                         isa<VarDecl>(ND) ? llvm::ELF::STT_OBJECT
129                                          : llvm::ELF::STT_FUNC,
130                         // Binding:
131                         IsWeak ? llvm::ELF::STB_WEAK : llvm::ELF::STB_GLOBAL,
132                         getMangledNames(ND))));
133     }
134     return true;
135   }
136 
137   void
138   HandleDecls(const llvm::iterator_range<DeclContext::decl_iterator> &Decls,
139               MangledSymbols &Symbols, int RDO) {
140     for (const auto *D : Decls)
141       HandleNamedDecl(dyn_cast<NamedDecl>(D), Symbols, RDO);
142   }
143 
144   void HandleTemplateSpecializations(const FunctionTemplateDecl &FTD,
145                                      MangledSymbols &Symbols, int RDO) {
146     for (const auto *D : FTD.specializations())
147       HandleNamedDecl(dyn_cast<NamedDecl>(D), Symbols, RDO);
148   }
149 
150   void HandleTemplateSpecializations(const ClassTemplateDecl &CTD,
151                                      MangledSymbols &Symbols, int RDO) {
152     for (const auto *D : CTD.specializations())
153       HandleNamedDecl(dyn_cast<NamedDecl>(D), Symbols, RDO);
154   }
155 
156   bool HandleNamedDecl(const NamedDecl *ND, MangledSymbols &Symbols, int RDO) {
157     if (!ND)
158       return false;
159 
160     switch (ND->getKind()) {
161     default:
162       break;
163     case Decl::Kind::Namespace:
164       HandleDecls(cast<NamespaceDecl>(ND)->decls(), Symbols, RDO);
165       return true;
166     case Decl::Kind::CXXRecord:
167       HandleDecls(cast<CXXRecordDecl>(ND)->decls(), Symbols, RDO);
168       return true;
169     case Decl::Kind::ClassTemplateSpecialization:
170       HandleDecls(cast<ClassTemplateSpecializationDecl>(ND)->decls(), Symbols,
171                   RDO);
172       return true;
173     case Decl::Kind::ClassTemplate:
174       HandleTemplateSpecializations(*cast<ClassTemplateDecl>(ND), Symbols, RDO);
175       return true;
176     case Decl::Kind::FunctionTemplate:
177       HandleTemplateSpecializations(*cast<FunctionTemplateDecl>(ND), Symbols,
178                                     RDO);
179       return true;
180     case Decl::Kind::TemplateTypeParm:
181       return true;
182     case Decl::Kind::Var:
183     case Decl::Kind::ParmVar:
184     case Decl::Kind::CXXMethod:
185     case Decl::Kind::CXXConstructor:
186     case Decl::Kind::CXXDestructor:
187     case Decl::Kind::Function:
188     case Decl::Kind::Field:
189       if (WriteNamedDecl(ND, Symbols, RDO))
190         return true;
191     }
192 
193     // While interface stubs are in the development stage, it's probably best to
194     // catch anything that's not a VarDecl or Template/FunctionDecl.
195     Instance.getDiagnostics().Report(diag::err_asm_invalid_type_in_input)
196         << "Expected a function or function template decl.";
197     return false;
198   }
199 
200 public:
201   InterfaceStubFunctionsConsumer(CompilerInstance &Instance, StringRef InFile,
202                                  StringRef Format)
203       : Instance(Instance), InFile(InFile), Format(Format) {}
204 
205   void HandleTranslationUnit(ASTContext &context) override {
206     struct Visitor : public RecursiveASTVisitor<Visitor> {
207       bool VisitNamedDecl(NamedDecl *ND) {
208         if (const auto *FD = dyn_cast<FunctionDecl>(ND))
209           if (FD->isLateTemplateParsed()) {
210             LateParsedDecls.insert(FD);
211             return true;
212           }
213 
214         if (const auto *VD = dyn_cast<ValueDecl>(ND)) {
215           ValueDecls.insert(VD);
216           return true;
217         }
218 
219         NamedDecls.insert(ND);
220         return true;
221       }
222 
223       std::set<const NamedDecl *> LateParsedDecls;
224       std::set<NamedDecl *> NamedDecls;
225       std::set<const ValueDecl *> ValueDecls;
226     } v;
227 
228     v.TraverseDecl(context.getTranslationUnitDecl());
229 
230     MangledSymbols Symbols;
231     auto OS = Instance.createDefaultOutputFile(/*Binary=*/false, InFile, "ifs");
232     if (!OS)
233       return;
234 
235     if (Instance.getLangOpts().DelayedTemplateParsing) {
236       clang::Sema &S = Instance.getSema();
237       for (const auto *FD : v.LateParsedDecls) {
238         clang::LateParsedTemplate &LPT =
239             *S.LateParsedTemplateMap.find(cast<FunctionDecl>(FD))->second;
240         S.LateTemplateParser(S.OpaqueParser, LPT);
241         HandleNamedDecl(FD, Symbols, (FromTU | IsLate));
242       }
243     }
244 
245     for (const NamedDecl *ND : v.ValueDecls)
246       HandleNamedDecl(ND, Symbols, FromTU);
247     for (const NamedDecl *ND : v.NamedDecls)
248       HandleNamedDecl(ND, Symbols, FromTU);
249 
250     auto writeIfsV1 =
251         [this](const llvm::Triple &T, const MangledSymbols &Symbols,
252                const ASTContext &context, StringRef Format,
253                raw_ostream &OS) -> void {
254       OS << "--- !" << Format << "\n";
255       OS << "IfsVersion: 1.0\n";
256       OS << "Triple: " << T.str() << "\n";
257       OS << "ObjectFileFormat: " << "ELF" << "\n"; // TODO: For now, just ELF.
258       OS << "Symbols:\n";
259       for (const auto &E : Symbols) {
260         const MangledSymbol &Symbol = E.second;
261         for (auto Name : Symbol.Names) {
262           OS << "  "
263              << (Symbol.ParentName.empty() || Instance.getLangOpts().CPlusPlus
264                      ? ""
265                      : (Symbol.ParentName + "."))
266              << Name << ": { Type: ";
267           switch (Symbol.Type) {
268           default:
269             llvm_unreachable(
270                 "clang -emit-iterface-stubs: Unexpected symbol type.");
271           case llvm::ELF::STT_NOTYPE:
272             OS << "NoType";
273             break;
274           case llvm::ELF::STT_OBJECT: {
275             auto VD = cast<ValueDecl>(E.first)->getType();
276             OS << "Object, Size: "
277                << context.getTypeSizeInChars(VD).getQuantity();
278             break;
279           }
280           case llvm::ELF::STT_FUNC:
281             OS << "Func";
282             break;
283           }
284           if (Symbol.Binding == llvm::ELF::STB_WEAK)
285             OS << ", Weak: true";
286           OS << " }\n";
287         }
288       }
289       OS << "...\n";
290       OS.flush();
291     };
292 
293     assert(Format == "experimental-ifs-v1" && "Unexpected IFS Format.");
294     writeIfsV1(Instance.getTarget().getTriple(), Symbols, context, Format, *OS);
295   }
296 };
297 } // namespace
298 
299 std::unique_ptr<ASTConsumer>
300 GenerateInterfaceIfsExpV1Action::CreateASTConsumer(CompilerInstance &CI,
301                                                    StringRef InFile) {
302   return std::make_unique<InterfaceStubFunctionsConsumer>(
303       CI, InFile, "experimental-ifs-v1");
304 }
305