xref: /freebsd/contrib/llvm-project/clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp (revision a7dea1671b87c07d2d266f836bfa8b58efc7c134)
10b57cec5SDimitry Andric //===- ClangOpenCLBuiltinEmitter.cpp - Generate Clang OpenCL Builtin handling
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric //                     The LLVM Compiler Infrastructure
40b57cec5SDimitry Andric //
50b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
60b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
70b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric // This tablegen backend emits code for checking whether a function is an
120b57cec5SDimitry Andric // OpenCL builtin function. If so, all overloads of this function are
130b57cec5SDimitry Andric // added to the LookupResult. The generated include file is used by
140b57cec5SDimitry Andric // SemaLookup.cpp
150b57cec5SDimitry Andric //
160b57cec5SDimitry Andric // For a successful lookup of e.g. the "cos" builtin, isOpenCLBuiltin("cos")
170b57cec5SDimitry Andric // returns a pair <Index, Len>.
18*a7dea167SDimitry Andric // BuiltinTable[Index] to BuiltinTable[Index + Len] contains the pairs
190b57cec5SDimitry Andric // <SigIndex, SigLen> of the overloads of "cos".
20*a7dea167SDimitry Andric // SignatureTable[SigIndex] to SignatureTable[SigIndex + SigLen] contains
21*a7dea167SDimitry Andric // one of the signatures of "cos". The SignatureTable entry can be
22*a7dea167SDimitry Andric // referenced by other functions, e.g. "sin", to exploit the fact that
23*a7dea167SDimitry Andric // many OpenCL builtins share the same signature.
24*a7dea167SDimitry Andric //
25*a7dea167SDimitry Andric // The file generated by this TableGen emitter contains the following:
26*a7dea167SDimitry Andric //
27*a7dea167SDimitry Andric //  * Structs and enums to represent types and function signatures.
28*a7dea167SDimitry Andric //
29*a7dea167SDimitry Andric //  * OpenCLTypeStruct TypeTable[]
30*a7dea167SDimitry Andric //    Type information for return types and arguments.
31*a7dea167SDimitry Andric //
32*a7dea167SDimitry Andric //  * unsigned SignatureTable[]
33*a7dea167SDimitry Andric //    A list of types representing function signatures.  Each entry is an index
34*a7dea167SDimitry Andric //    into the above TypeTable.  Multiple entries following each other form a
35*a7dea167SDimitry Andric //    signature, where the first entry is the return type and subsequent
36*a7dea167SDimitry Andric //    entries are the argument types.
37*a7dea167SDimitry Andric //
38*a7dea167SDimitry Andric //  * OpenCLBuiltinStruct BuiltinTable[]
39*a7dea167SDimitry Andric //    Each entry represents one overload of an OpenCL builtin function and
40*a7dea167SDimitry Andric //    consists of an index into the SignatureTable and the number of arguments.
41*a7dea167SDimitry Andric //
42*a7dea167SDimitry Andric //  * std::pair<unsigned, unsigned> isOpenCLBuiltin(llvm::StringRef Name)
43*a7dea167SDimitry Andric //    Find out whether a string matches an existing OpenCL builtin function
44*a7dea167SDimitry Andric //    name and return an index into BuiltinTable and the number of overloads.
45*a7dea167SDimitry Andric //
46*a7dea167SDimitry Andric //  * void OCL2Qual(ASTContext&, OpenCLTypeStruct, std::vector<QualType>&)
47*a7dea167SDimitry Andric //    Convert an OpenCLTypeStruct type to a list of QualType instances.
48*a7dea167SDimitry Andric //    One OpenCLTypeStruct can represent multiple types, primarily when using
49*a7dea167SDimitry Andric //    GenTypes.
50*a7dea167SDimitry Andric //
510b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
520b57cec5SDimitry Andric 
53*a7dea167SDimitry Andric #include "TableGenBackends.h"
540b57cec5SDimitry Andric #include "llvm/ADT/MapVector.h"
550b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
560b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
570b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
580b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
590b57cec5SDimitry Andric #include "llvm/ADT/StringSet.h"
60*a7dea167SDimitry Andric #include "llvm/ADT/StringSwitch.h"
610b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
620b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
630b57cec5SDimitry Andric #include "llvm/TableGen/Error.h"
640b57cec5SDimitry Andric #include "llvm/TableGen/Record.h"
650b57cec5SDimitry Andric #include "llvm/TableGen/StringMatcher.h"
660b57cec5SDimitry Andric #include "llvm/TableGen/TableGenBackend.h"
670b57cec5SDimitry Andric #include <set>
680b57cec5SDimitry Andric 
690b57cec5SDimitry Andric using namespace llvm;
700b57cec5SDimitry Andric 
710b57cec5SDimitry Andric namespace {
720b57cec5SDimitry Andric class BuiltinNameEmitter {
730b57cec5SDimitry Andric public:
740b57cec5SDimitry Andric   BuiltinNameEmitter(RecordKeeper &Records, raw_ostream &OS)
750b57cec5SDimitry Andric       : Records(Records), OS(OS) {}
760b57cec5SDimitry Andric 
770b57cec5SDimitry Andric   // Entrypoint to generate the functions and structures for checking
780b57cec5SDimitry Andric   // whether a function is an OpenCL builtin function.
790b57cec5SDimitry Andric   void Emit();
800b57cec5SDimitry Andric 
810b57cec5SDimitry Andric private:
820b57cec5SDimitry Andric   // Contains OpenCL builtin functions and related information, stored as
830b57cec5SDimitry Andric   // Record instances. They are coming from the associated TableGen file.
840b57cec5SDimitry Andric   RecordKeeper &Records;
850b57cec5SDimitry Andric 
860b57cec5SDimitry Andric   // The output file.
870b57cec5SDimitry Andric   raw_ostream &OS;
880b57cec5SDimitry Andric 
89*a7dea167SDimitry Andric   // Helper function for BuiltinNameEmitter::EmitDeclarations.  Generate enum
90*a7dea167SDimitry Andric   // definitions in the Output string parameter, and save their Record instances
91*a7dea167SDimitry Andric   // in the List parameter.
92*a7dea167SDimitry Andric   // \param Types (in) List containing the Types to extract.
93*a7dea167SDimitry Andric   // \param TypesSeen (inout) List containing the Types already extracted.
94*a7dea167SDimitry Andric   // \param Output (out) String containing the enums to emit in the output file.
95*a7dea167SDimitry Andric   // \param List (out) List containing the extracted Types, except the Types in
96*a7dea167SDimitry Andric   //        TypesSeen.
97*a7dea167SDimitry Andric   void ExtractEnumTypes(std::vector<Record *> &Types,
98*a7dea167SDimitry Andric                         StringMap<bool> &TypesSeen, std::string &Output,
99*a7dea167SDimitry Andric                         std::vector<const Record *> &List);
100*a7dea167SDimitry Andric 
101*a7dea167SDimitry Andric   // Emit the enum or struct used in the generated file.
102*a7dea167SDimitry Andric   // Populate the TypeList at the same time.
1030b57cec5SDimitry Andric   void EmitDeclarations();
1040b57cec5SDimitry Andric 
105*a7dea167SDimitry Andric   // Parse the Records generated by TableGen to populate the SignaturesList,
106*a7dea167SDimitry Andric   // FctOverloadMap and TypeMap.
1070b57cec5SDimitry Andric   void GetOverloads();
1080b57cec5SDimitry Andric 
109*a7dea167SDimitry Andric   // Emit the TypeTable containing all types used by OpenCL builtins.
110*a7dea167SDimitry Andric   void EmitTypeTable();
111*a7dea167SDimitry Andric 
112*a7dea167SDimitry Andric   // Emit the SignatureTable. This table contains all the possible signatures.
113*a7dea167SDimitry Andric   // A signature is stored as a list of indexes of the TypeTable.
114*a7dea167SDimitry Andric   // The first index references the return type (mandatory), and the followings
115*a7dea167SDimitry Andric   // reference its arguments.
1160b57cec5SDimitry Andric   // E.g.:
117*a7dea167SDimitry Andric   // 15, 2, 15 can represent a function with the signature:
118*a7dea167SDimitry Andric   // int func(float, int)
119*a7dea167SDimitry Andric   // The "int" type being at the index 15 in the TypeTable.
1200b57cec5SDimitry Andric   void EmitSignatureTable();
1210b57cec5SDimitry Andric 
122*a7dea167SDimitry Andric   // Emit the BuiltinTable table. This table contains all the overloads of
1230b57cec5SDimitry Andric   // each function, and is a struct OpenCLBuiltinDecl.
1240b57cec5SDimitry Andric   // E.g.:
125*a7dea167SDimitry Andric   // // 891 convert_float2_rtn
126*a7dea167SDimitry Andric   //   { 58, 2, 100, 0 },
127*a7dea167SDimitry Andric   // This means that the signature of this convert_float2_rtn overload has
128*a7dea167SDimitry Andric   // 1 argument (+1 for the return type), stored at index 58 in
129*a7dea167SDimitry Andric   // the SignatureTable.  The last two values represent the minimum (1.0) and
130*a7dea167SDimitry Andric   // maximum (0, meaning no max version) OpenCL version in which this overload
131*a7dea167SDimitry Andric   // is supported.
1320b57cec5SDimitry Andric   void EmitBuiltinTable();
1330b57cec5SDimitry Andric 
1340b57cec5SDimitry Andric   // Emit a StringMatcher function to check whether a function name is an
1350b57cec5SDimitry Andric   // OpenCL builtin function name.
1360b57cec5SDimitry Andric   void EmitStringMatcher();
1370b57cec5SDimitry Andric 
1380b57cec5SDimitry Andric   // Emit a function returning the clang QualType instance associated with
1390b57cec5SDimitry Andric   // the TableGen Record Type.
1400b57cec5SDimitry Andric   void EmitQualTypeFinder();
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric   // Contains a list of the available signatures, without the name of the
1430b57cec5SDimitry Andric   // function. Each pair consists of a signature and a cumulative index.
1440b57cec5SDimitry Andric   // E.g.:  <<float, float>, 0>,
1450b57cec5SDimitry Andric   //        <<float, int, int, 2>>,
1460b57cec5SDimitry Andric   //        <<float>, 5>,
1470b57cec5SDimitry Andric   //        ...
1480b57cec5SDimitry Andric   //        <<double, double>, 35>.
149*a7dea167SDimitry Andric   std::vector<std::pair<std::vector<Record *>, unsigned>> SignaturesList;
1500b57cec5SDimitry Andric 
1510b57cec5SDimitry Andric   // Map the name of a builtin function to its prototypes (instances of the
1520b57cec5SDimitry Andric   // TableGen "Builtin" class).
1530b57cec5SDimitry Andric   // Each prototype is registered as a pair of:
1540b57cec5SDimitry Andric   //   <pointer to the "Builtin" instance,
155*a7dea167SDimitry Andric   //    cumulative index of the associated signature in the SignaturesList>
1560b57cec5SDimitry Andric   // E.g.:  The function cos: (float cos(float), double cos(double), ...)
1570b57cec5SDimitry Andric   //        <"cos", <<ptrToPrototype0, 5>,
158*a7dea167SDimitry Andric   //                 <ptrToPrototype1, 35>,
1590b57cec5SDimitry Andric   //                 <ptrToPrototype2, 79>>
1600b57cec5SDimitry Andric   // ptrToPrototype1 has the following signature: <double, double>
1610b57cec5SDimitry Andric   MapVector<StringRef, std::vector<std::pair<const Record *, unsigned>>>
162*a7dea167SDimitry Andric       FctOverloadMap;
163*a7dea167SDimitry Andric 
164*a7dea167SDimitry Andric   // Contains the map of OpenCL types to their index in the TypeTable.
165*a7dea167SDimitry Andric   MapVector<const Record *, unsigned> TypeMap;
166*a7dea167SDimitry Andric 
167*a7dea167SDimitry Andric   // List of OpenCL type names in the same order as in enum OpenCLTypeID.
168*a7dea167SDimitry Andric   // This list does not contain generic types.
169*a7dea167SDimitry Andric   std::vector<const Record *> TypeList;
170*a7dea167SDimitry Andric 
171*a7dea167SDimitry Andric   // Same as TypeList, but for generic types only.
172*a7dea167SDimitry Andric   std::vector<const Record *> GenTypeList;
1730b57cec5SDimitry Andric };
1740b57cec5SDimitry Andric } // namespace
1750b57cec5SDimitry Andric 
1760b57cec5SDimitry Andric void BuiltinNameEmitter::Emit() {
1770b57cec5SDimitry Andric   emitSourceFileHeader("OpenCL Builtin handling", OS);
1780b57cec5SDimitry Andric 
1790b57cec5SDimitry Andric   OS << "#include \"llvm/ADT/StringRef.h\"\n";
1800b57cec5SDimitry Andric   OS << "using namespace clang;\n\n";
1810b57cec5SDimitry Andric 
182*a7dea167SDimitry Andric   // Emit enums and structs.
1830b57cec5SDimitry Andric   EmitDeclarations();
1840b57cec5SDimitry Andric 
1850b57cec5SDimitry Andric   GetOverloads();
1860b57cec5SDimitry Andric 
187*a7dea167SDimitry Andric   // Emit tables.
188*a7dea167SDimitry Andric   EmitTypeTable();
1890b57cec5SDimitry Andric   EmitSignatureTable();
1900b57cec5SDimitry Andric   EmitBuiltinTable();
1910b57cec5SDimitry Andric 
1920b57cec5SDimitry Andric   EmitStringMatcher();
1930b57cec5SDimitry Andric 
1940b57cec5SDimitry Andric   EmitQualTypeFinder();
1950b57cec5SDimitry Andric }
1960b57cec5SDimitry Andric 
197*a7dea167SDimitry Andric void BuiltinNameEmitter::ExtractEnumTypes(std::vector<Record *> &Types,
198*a7dea167SDimitry Andric                                           StringMap<bool> &TypesSeen,
199*a7dea167SDimitry Andric                                           std::string &Output,
200*a7dea167SDimitry Andric                                           std::vector<const Record *> &List) {
201*a7dea167SDimitry Andric   raw_string_ostream SS(Output);
202*a7dea167SDimitry Andric 
2030b57cec5SDimitry Andric   for (const auto *T : Types) {
204*a7dea167SDimitry Andric     if (TypesSeen.find(T->getValueAsString("Name")) == TypesSeen.end()) {
205*a7dea167SDimitry Andric       SS << "  OCLT_" + T->getValueAsString("Name") << ",\n";
206*a7dea167SDimitry Andric       // Save the type names in the same order as their enum value. Note that
207*a7dea167SDimitry Andric       // the Record can be a VectorType or something else, only the name is
208*a7dea167SDimitry Andric       // important.
209*a7dea167SDimitry Andric       List.push_back(T);
2100b57cec5SDimitry Andric       TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true));
2110b57cec5SDimitry Andric     }
212*a7dea167SDimitry Andric   }
213*a7dea167SDimitry Andric   SS.flush();
214*a7dea167SDimitry Andric }
215*a7dea167SDimitry Andric 
216*a7dea167SDimitry Andric void BuiltinNameEmitter::EmitDeclarations() {
217*a7dea167SDimitry Andric   // Enum of scalar type names (float, int, ...) and generic type sets.
218*a7dea167SDimitry Andric   OS << "enum OpenCLTypeID {\n";
219*a7dea167SDimitry Andric 
220*a7dea167SDimitry Andric   StringMap<bool> TypesSeen;
221*a7dea167SDimitry Andric   std::string GenTypeEnums;
222*a7dea167SDimitry Andric   std::string TypeEnums;
223*a7dea167SDimitry Andric 
224*a7dea167SDimitry Andric   // Extract generic types and non-generic types separately, to keep
225*a7dea167SDimitry Andric   // gentypes at the end of the enum which simplifies the special handling
226*a7dea167SDimitry Andric   // for gentypes in SemaLookup.
227*a7dea167SDimitry Andric   std::vector<Record *> GenTypes =
228*a7dea167SDimitry Andric       Records.getAllDerivedDefinitions("GenericType");
229*a7dea167SDimitry Andric   ExtractEnumTypes(GenTypes, TypesSeen, GenTypeEnums, GenTypeList);
230*a7dea167SDimitry Andric 
231*a7dea167SDimitry Andric   std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
232*a7dea167SDimitry Andric   ExtractEnumTypes(Types, TypesSeen, TypeEnums, TypeList);
233*a7dea167SDimitry Andric 
234*a7dea167SDimitry Andric   OS << TypeEnums;
235*a7dea167SDimitry Andric   OS << GenTypeEnums;
2360b57cec5SDimitry Andric   OS << "};\n";
2370b57cec5SDimitry Andric 
238*a7dea167SDimitry Andric   // Structure definitions.
2390b57cec5SDimitry Andric   OS << R"(
240*a7dea167SDimitry Andric // Image access qualifier.
241*a7dea167SDimitry Andric enum OpenCLAccessQual : unsigned char {
242*a7dea167SDimitry Andric   OCLAQ_None,
243*a7dea167SDimitry Andric   OCLAQ_ReadOnly,
244*a7dea167SDimitry Andric   OCLAQ_WriteOnly,
245*a7dea167SDimitry Andric   OCLAQ_ReadWrite
246*a7dea167SDimitry Andric };
2470b57cec5SDimitry Andric 
248*a7dea167SDimitry Andric // Represents a return type or argument type.
249*a7dea167SDimitry Andric struct OpenCLTypeStruct {
250*a7dea167SDimitry Andric   // A type (e.g. float, int, ...).
251*a7dea167SDimitry Andric   const OpenCLTypeID ID;
252*a7dea167SDimitry Andric   // Vector size (if applicable; 0 for scalars and generic types).
253*a7dea167SDimitry Andric   const unsigned VectorWidth;
254*a7dea167SDimitry Andric   // 0 if the type is not a pointer.
255*a7dea167SDimitry Andric   const bool IsPointer;
256*a7dea167SDimitry Andric   // 0 if the type is not const.
257*a7dea167SDimitry Andric   const bool IsConst;
258*a7dea167SDimitry Andric   // 0 if the type is not volatile.
259*a7dea167SDimitry Andric   const bool IsVolatile;
260*a7dea167SDimitry Andric   // Access qualifier.
261*a7dea167SDimitry Andric   const OpenCLAccessQual AccessQualifier;
262*a7dea167SDimitry Andric   // Address space of the pointer (if applicable).
263*a7dea167SDimitry Andric   const LangAS AS;
2640b57cec5SDimitry Andric };
2650b57cec5SDimitry Andric 
2660b57cec5SDimitry Andric // One overload of an OpenCL builtin function.
267*a7dea167SDimitry Andric struct OpenCLBuiltinStruct {
268*a7dea167SDimitry Andric   // Index of the signature in the OpenCLTypeStruct table.
269*a7dea167SDimitry Andric   const unsigned SigTableIndex;
270*a7dea167SDimitry Andric   // Entries between index SigTableIndex and (SigTableIndex + NumTypes - 1) in
271*a7dea167SDimitry Andric   // the SignatureTable represent the complete signature.  The first type at
272*a7dea167SDimitry Andric   // index SigTableIndex is the return type.
273*a7dea167SDimitry Andric   const unsigned NumTypes;
274*a7dea167SDimitry Andric   // First OpenCL version in which this overload was introduced (e.g. CL20).
275*a7dea167SDimitry Andric   const unsigned short MinVersion;
276*a7dea167SDimitry Andric   // First OpenCL version in which this overload was removed (e.g. CL20).
277*a7dea167SDimitry Andric   const unsigned short MaxVersion;
2780b57cec5SDimitry Andric };
2790b57cec5SDimitry Andric 
2800b57cec5SDimitry Andric )";
2810b57cec5SDimitry Andric }
2820b57cec5SDimitry Andric 
283*a7dea167SDimitry Andric // Verify that the combination of GenTypes in a signature is supported.
284*a7dea167SDimitry Andric // To simplify the logic for creating overloads in SemaLookup, only allow
285*a7dea167SDimitry Andric // a signature to contain different GenTypes if these GenTypes represent
286*a7dea167SDimitry Andric // the same number of actual scalar or vector types.
287*a7dea167SDimitry Andric //
288*a7dea167SDimitry Andric // Exit with a fatal error if an unsupported construct is encountered.
289*a7dea167SDimitry Andric static void VerifySignature(const std::vector<Record *> &Signature,
290*a7dea167SDimitry Andric                             const Record *BuiltinRec) {
291*a7dea167SDimitry Andric   unsigned GenTypeVecSizes = 1;
292*a7dea167SDimitry Andric   unsigned GenTypeTypes = 1;
293*a7dea167SDimitry Andric 
294*a7dea167SDimitry Andric   for (const auto *T : Signature) {
295*a7dea167SDimitry Andric     // Check all GenericType arguments in this signature.
296*a7dea167SDimitry Andric     if (T->isSubClassOf("GenericType")) {
297*a7dea167SDimitry Andric       // Check number of vector sizes.
298*a7dea167SDimitry Andric       unsigned NVecSizes =
299*a7dea167SDimitry Andric           T->getValueAsDef("VectorList")->getValueAsListOfInts("List").size();
300*a7dea167SDimitry Andric       if (NVecSizes != GenTypeVecSizes && NVecSizes != 1) {
301*a7dea167SDimitry Andric         if (GenTypeVecSizes > 1) {
302*a7dea167SDimitry Andric           // We already saw a gentype with a different number of vector sizes.
303*a7dea167SDimitry Andric           PrintFatalError(BuiltinRec->getLoc(),
304*a7dea167SDimitry Andric               "number of vector sizes should be equal or 1 for all gentypes "
305*a7dea167SDimitry Andric               "in a declaration");
306*a7dea167SDimitry Andric         }
307*a7dea167SDimitry Andric         GenTypeVecSizes = NVecSizes;
308*a7dea167SDimitry Andric       }
309*a7dea167SDimitry Andric 
310*a7dea167SDimitry Andric       // Check number of data types.
311*a7dea167SDimitry Andric       unsigned NTypes =
312*a7dea167SDimitry Andric           T->getValueAsDef("TypeList")->getValueAsListOfDefs("List").size();
313*a7dea167SDimitry Andric       if (NTypes != GenTypeTypes && NTypes != 1) {
314*a7dea167SDimitry Andric         if (GenTypeTypes > 1) {
315*a7dea167SDimitry Andric           // We already saw a gentype with a different number of types.
316*a7dea167SDimitry Andric           PrintFatalError(BuiltinRec->getLoc(),
317*a7dea167SDimitry Andric               "number of types should be equal or 1 for all gentypes "
318*a7dea167SDimitry Andric               "in a declaration");
319*a7dea167SDimitry Andric         }
320*a7dea167SDimitry Andric         GenTypeTypes = NTypes;
321*a7dea167SDimitry Andric       }
322*a7dea167SDimitry Andric     }
323*a7dea167SDimitry Andric   }
324*a7dea167SDimitry Andric }
325*a7dea167SDimitry Andric 
3260b57cec5SDimitry Andric void BuiltinNameEmitter::GetOverloads() {
327*a7dea167SDimitry Andric   // Populate the TypeMap.
328*a7dea167SDimitry Andric   std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
329*a7dea167SDimitry Andric   unsigned I = 0;
330*a7dea167SDimitry Andric   for (const auto &T : Types) {
331*a7dea167SDimitry Andric     TypeMap.insert(std::make_pair(T, I++));
332*a7dea167SDimitry Andric   }
333*a7dea167SDimitry Andric 
334*a7dea167SDimitry Andric   // Populate the SignaturesList and the FctOverloadMap.
3350b57cec5SDimitry Andric   unsigned CumulativeSignIndex = 0;
3360b57cec5SDimitry Andric   std::vector<Record *> Builtins = Records.getAllDerivedDefinitions("Builtin");
3370b57cec5SDimitry Andric   for (const auto *B : Builtins) {
3380b57cec5SDimitry Andric     StringRef BName = B->getValueAsString("Name");
339*a7dea167SDimitry Andric     if (FctOverloadMap.find(BName) == FctOverloadMap.end()) {
340*a7dea167SDimitry Andric       FctOverloadMap.insert(std::make_pair(
3410b57cec5SDimitry Andric           BName, std::vector<std::pair<const Record *, unsigned>>{}));
3420b57cec5SDimitry Andric     }
3430b57cec5SDimitry Andric 
3440b57cec5SDimitry Andric     auto Signature = B->getValueAsListOfDefs("Signature");
345*a7dea167SDimitry Andric     // Reuse signatures to avoid unnecessary duplicates.
3460b57cec5SDimitry Andric     auto it =
347*a7dea167SDimitry Andric         std::find_if(SignaturesList.begin(), SignaturesList.end(),
3480b57cec5SDimitry Andric                      [&](const std::pair<std::vector<Record *>, unsigned> &a) {
3490b57cec5SDimitry Andric                        return a.first == Signature;
3500b57cec5SDimitry Andric                      });
3510b57cec5SDimitry Andric     unsigned SignIndex;
352*a7dea167SDimitry Andric     if (it == SignaturesList.end()) {
353*a7dea167SDimitry Andric       VerifySignature(Signature, B);
354*a7dea167SDimitry Andric       SignaturesList.push_back(std::make_pair(Signature, CumulativeSignIndex));
3550b57cec5SDimitry Andric       SignIndex = CumulativeSignIndex;
3560b57cec5SDimitry Andric       CumulativeSignIndex += Signature.size();
3570b57cec5SDimitry Andric     } else {
3580b57cec5SDimitry Andric       SignIndex = it->second;
3590b57cec5SDimitry Andric     }
360*a7dea167SDimitry Andric     FctOverloadMap[BName].push_back(std::make_pair(B, SignIndex));
3610b57cec5SDimitry Andric   }
3620b57cec5SDimitry Andric }
3630b57cec5SDimitry Andric 
364*a7dea167SDimitry Andric void BuiltinNameEmitter::EmitTypeTable() {
365*a7dea167SDimitry Andric   OS << "static const OpenCLTypeStruct TypeTable[] = {\n";
366*a7dea167SDimitry Andric   for (const auto &T : TypeMap) {
367*a7dea167SDimitry Andric     const char *AccessQual =
368*a7dea167SDimitry Andric         StringSwitch<const char *>(T.first->getValueAsString("AccessQualifier"))
369*a7dea167SDimitry Andric             .Case("RO", "OCLAQ_ReadOnly")
370*a7dea167SDimitry Andric             .Case("WO", "OCLAQ_WriteOnly")
371*a7dea167SDimitry Andric             .Case("RW", "OCLAQ_ReadWrite")
372*a7dea167SDimitry Andric             .Default("OCLAQ_None");
373*a7dea167SDimitry Andric 
374*a7dea167SDimitry Andric     OS << "  // " << T.second << "\n"
375*a7dea167SDimitry Andric        << "  {OCLT_" << T.first->getValueAsString("Name") << ", "
376*a7dea167SDimitry Andric        << T.first->getValueAsInt("VecWidth") << ", "
377*a7dea167SDimitry Andric        << T.first->getValueAsBit("IsPointer") << ", "
378*a7dea167SDimitry Andric        << T.first->getValueAsBit("IsConst") << ", "
379*a7dea167SDimitry Andric        << T.first->getValueAsBit("IsVolatile") << ", "
380*a7dea167SDimitry Andric        << AccessQual << ", "
381*a7dea167SDimitry Andric        << T.first->getValueAsString("AddrSpace") << "},\n";
3820b57cec5SDimitry Andric   }
383*a7dea167SDimitry Andric   OS << "};\n\n";
384*a7dea167SDimitry Andric }
385*a7dea167SDimitry Andric 
386*a7dea167SDimitry Andric void BuiltinNameEmitter::EmitSignatureTable() {
387*a7dea167SDimitry Andric   // Store a type (e.g. int, float, int2, ...). The type is stored as an index
388*a7dea167SDimitry Andric   // of a struct OpenCLType table. Multiple entries following each other form a
389*a7dea167SDimitry Andric   // signature.
390*a7dea167SDimitry Andric   OS << "static const unsigned SignatureTable[] = {\n";
391*a7dea167SDimitry Andric   for (const auto &P : SignaturesList) {
392*a7dea167SDimitry Andric     OS << "  // " << P.second << "\n  ";
393*a7dea167SDimitry Andric     for (const Record *R : P.first) {
394*a7dea167SDimitry Andric       OS << TypeMap.find(R)->second << ", ";
395*a7dea167SDimitry Andric     }
396*a7dea167SDimitry Andric     OS << "\n";
3970b57cec5SDimitry Andric   }
3980b57cec5SDimitry Andric   OS << "};\n\n";
3990b57cec5SDimitry Andric }
4000b57cec5SDimitry Andric 
4010b57cec5SDimitry Andric void BuiltinNameEmitter::EmitBuiltinTable() {
402*a7dea167SDimitry Andric   unsigned Index = 0;
403*a7dea167SDimitry Andric 
404*a7dea167SDimitry Andric   OS << "static const OpenCLBuiltinStruct BuiltinTable[] = {\n";
405*a7dea167SDimitry Andric   for (const auto &FOM : FctOverloadMap) {
406*a7dea167SDimitry Andric 
407*a7dea167SDimitry Andric     OS << "  // " << (Index + 1) << ": " << FOM.first << "\n";
408*a7dea167SDimitry Andric 
409*a7dea167SDimitry Andric     for (const auto &Overload : FOM.second) {
410*a7dea167SDimitry Andric       OS << "  { " << Overload.second << ", "
411*a7dea167SDimitry Andric          << Overload.first->getValueAsListOfDefs("Signature").size() << ", "
412*a7dea167SDimitry Andric          << Overload.first->getValueAsDef("MinVersion")->getValueAsInt("ID")
413*a7dea167SDimitry Andric          << ", "
414*a7dea167SDimitry Andric          << Overload.first->getValueAsDef("MaxVersion")->getValueAsInt("ID")
4150b57cec5SDimitry Andric          << " },\n";
416*a7dea167SDimitry Andric       Index++;
4170b57cec5SDimitry Andric     }
4180b57cec5SDimitry Andric   }
4190b57cec5SDimitry Andric   OS << "};\n\n";
4200b57cec5SDimitry Andric }
4210b57cec5SDimitry Andric 
4220b57cec5SDimitry Andric void BuiltinNameEmitter::EmitStringMatcher() {
4230b57cec5SDimitry Andric   std::vector<StringMatcher::StringPair> ValidBuiltins;
4240b57cec5SDimitry Andric   unsigned CumulativeIndex = 1;
425*a7dea167SDimitry Andric   for (auto &i : FctOverloadMap) {
4260b57cec5SDimitry Andric     auto &Ov = i.second;
4270b57cec5SDimitry Andric     std::string RetStmt;
4280b57cec5SDimitry Andric     raw_string_ostream SS(RetStmt);
4290b57cec5SDimitry Andric     SS << "return std::make_pair(" << CumulativeIndex << ", " << Ov.size()
4300b57cec5SDimitry Andric        << ");";
4310b57cec5SDimitry Andric     SS.flush();
4320b57cec5SDimitry Andric     CumulativeIndex += Ov.size();
4330b57cec5SDimitry Andric 
4340b57cec5SDimitry Andric     ValidBuiltins.push_back(StringMatcher::StringPair(i.first, RetStmt));
4350b57cec5SDimitry Andric   }
4360b57cec5SDimitry Andric 
4370b57cec5SDimitry Andric   OS << R"(
438*a7dea167SDimitry Andric // Find out whether a string matches an existing OpenCL builtin function name.
439*a7dea167SDimitry Andric // Returns: A pair <0, 0> if no name matches.
440*a7dea167SDimitry Andric //          A pair <Index, Len> indexing the BuiltinTable if the name is
441*a7dea167SDimitry Andric //          matching an OpenCL builtin function.
442*a7dea167SDimitry Andric static std::pair<unsigned, unsigned> isOpenCLBuiltin(llvm::StringRef Name) {
4430b57cec5SDimitry Andric 
4440b57cec5SDimitry Andric )";
4450b57cec5SDimitry Andric 
446*a7dea167SDimitry Andric   StringMatcher("Name", ValidBuiltins, OS).Emit(0, true);
4470b57cec5SDimitry Andric 
4480b57cec5SDimitry Andric   OS << "  return std::make_pair(0, 0);\n";
449*a7dea167SDimitry Andric   OS << "} // isOpenCLBuiltin\n";
4500b57cec5SDimitry Andric }
4510b57cec5SDimitry Andric 
4520b57cec5SDimitry Andric void BuiltinNameEmitter::EmitQualTypeFinder() {
4530b57cec5SDimitry Andric   OS << R"(
4540b57cec5SDimitry Andric 
455*a7dea167SDimitry Andric // Convert an OpenCLTypeStruct type to a list of QualTypes.
456*a7dea167SDimitry Andric // Generic types represent multiple types and vector sizes, thus a vector
457*a7dea167SDimitry Andric // is returned. The conversion is done in two steps:
458*a7dea167SDimitry Andric // Step 1: A switch statement fills a vector with scalar base types for the
459*a7dea167SDimitry Andric //         Cartesian product of (vector sizes) x (types) for generic types,
460*a7dea167SDimitry Andric //         or a single scalar type for non generic types.
461*a7dea167SDimitry Andric // Step 2: Qualifiers and other type properties such as vector size are
462*a7dea167SDimitry Andric //         applied.
463*a7dea167SDimitry Andric static void OCL2Qual(ASTContext &Context, const OpenCLTypeStruct &Ty,
464*a7dea167SDimitry Andric                      llvm::SmallVectorImpl<QualType> &QT) {
465*a7dea167SDimitry Andric   // Number of scalar types in the GenType.
466*a7dea167SDimitry Andric   unsigned GenTypeNumTypes;
467*a7dea167SDimitry Andric   // Pointer to the list of vector sizes for the GenType.
468*a7dea167SDimitry Andric   llvm::ArrayRef<unsigned> GenVectorSizes;
4690b57cec5SDimitry Andric )";
4700b57cec5SDimitry Andric 
471*a7dea167SDimitry Andric   // Generate list of vector sizes for each generic type.
472*a7dea167SDimitry Andric   for (const auto *VectList : Records.getAllDerivedDefinitions("IntList")) {
473*a7dea167SDimitry Andric     OS << "  constexpr unsigned List"
474*a7dea167SDimitry Andric        << VectList->getValueAsString("Name") << "[] = {";
475*a7dea167SDimitry Andric     for (const auto V : VectList->getValueAsListOfInts("List")) {
476*a7dea167SDimitry Andric       OS << V << ", ";
477*a7dea167SDimitry Andric     }
478*a7dea167SDimitry Andric     OS << "};\n";
479*a7dea167SDimitry Andric   }
480*a7dea167SDimitry Andric 
481*a7dea167SDimitry Andric   // Step 1.
482*a7dea167SDimitry Andric   // Start of switch statement over all types.
483*a7dea167SDimitry Andric   OS << "\n  switch (Ty.ID) {\n";
484*a7dea167SDimitry Andric 
485*a7dea167SDimitry Andric   // Switch cases for image types (Image2d, Image3d, ...)
486*a7dea167SDimitry Andric   std::vector<Record *> ImageTypes =
487*a7dea167SDimitry Andric       Records.getAllDerivedDefinitions("ImageType");
488*a7dea167SDimitry Andric 
489*a7dea167SDimitry Andric   // Map an image type name to its 3 access-qualified types (RO, WO, RW).
490*a7dea167SDimitry Andric   std::map<StringRef, SmallVector<Record *, 3>> ImageTypesMap;
491*a7dea167SDimitry Andric   for (auto *IT : ImageTypes) {
492*a7dea167SDimitry Andric     auto Entry = ImageTypesMap.find(IT->getValueAsString("Name"));
493*a7dea167SDimitry Andric     if (Entry == ImageTypesMap.end()) {
494*a7dea167SDimitry Andric       SmallVector<Record *, 3> ImageList;
495*a7dea167SDimitry Andric       ImageList.push_back(IT);
496*a7dea167SDimitry Andric       ImageTypesMap.insert(
497*a7dea167SDimitry Andric           std::make_pair(IT->getValueAsString("Name"), ImageList));
498*a7dea167SDimitry Andric     } else {
499*a7dea167SDimitry Andric       Entry->second.push_back(IT);
500*a7dea167SDimitry Andric     }
501*a7dea167SDimitry Andric   }
502*a7dea167SDimitry Andric 
503*a7dea167SDimitry Andric   // Emit the cases for the image types.  For an image type name, there are 3
504*a7dea167SDimitry Andric   // corresponding QualTypes ("RO", "WO", "RW").  The "AccessQualifier" field
505*a7dea167SDimitry Andric   // tells which one is needed.  Emit a switch statement that puts the
506*a7dea167SDimitry Andric   // corresponding QualType into "QT".
507*a7dea167SDimitry Andric   for (const auto &ITE : ImageTypesMap) {
508*a7dea167SDimitry Andric     OS << "    case OCLT_" << ITE.first.str() << ":\n"
509*a7dea167SDimitry Andric        << "      switch (Ty.AccessQualifier) {\n"
510*a7dea167SDimitry Andric        << "        case OCLAQ_None:\n"
511*a7dea167SDimitry Andric        << "          llvm_unreachable(\"Image without access qualifier\");\n";
512*a7dea167SDimitry Andric     for (const auto &Image : ITE.second) {
513*a7dea167SDimitry Andric       OS << StringSwitch<const char *>(
514*a7dea167SDimitry Andric                 Image->getValueAsString("AccessQualifier"))
515*a7dea167SDimitry Andric                 .Case("RO", "        case OCLAQ_ReadOnly:\n")
516*a7dea167SDimitry Andric                 .Case("WO", "        case OCLAQ_WriteOnly:\n")
517*a7dea167SDimitry Andric                 .Case("RW", "        case OCLAQ_ReadWrite:\n")
518*a7dea167SDimitry Andric          << "          QT.push_back(Context."
519*a7dea167SDimitry Andric          << Image->getValueAsDef("QTName")->getValueAsString("Name") << ");\n"
520*a7dea167SDimitry Andric          << "          break;\n";
521*a7dea167SDimitry Andric     }
522*a7dea167SDimitry Andric     OS << "      }\n"
523*a7dea167SDimitry Andric        << "      break;\n";
524*a7dea167SDimitry Andric   }
525*a7dea167SDimitry Andric 
526*a7dea167SDimitry Andric   // Switch cases for generic types.
527*a7dea167SDimitry Andric   for (const auto *GenType : Records.getAllDerivedDefinitions("GenericType")) {
528*a7dea167SDimitry Andric     OS << "    case OCLT_" << GenType->getValueAsString("Name") << ":\n";
529*a7dea167SDimitry Andric     OS << "      QT.append({";
530*a7dea167SDimitry Andric 
531*a7dea167SDimitry Andric     // Build the Cartesian product of (vector sizes) x (types).  Only insert
532*a7dea167SDimitry Andric     // the plain scalar types for now; other type information such as vector
533*a7dea167SDimitry Andric     // size and type qualifiers will be added after the switch statement.
534*a7dea167SDimitry Andric     for (unsigned I = 0; I < GenType->getValueAsDef("VectorList")
535*a7dea167SDimitry Andric                                  ->getValueAsListOfInts("List")
536*a7dea167SDimitry Andric                                  .size();
537*a7dea167SDimitry Andric          I++) {
538*a7dea167SDimitry Andric       for (const auto *T :
539*a7dea167SDimitry Andric            GenType->getValueAsDef("TypeList")->getValueAsListOfDefs("List")) {
540*a7dea167SDimitry Andric         OS << "Context."
541*a7dea167SDimitry Andric            << T->getValueAsDef("QTName")->getValueAsString("Name") << ", ";
542*a7dea167SDimitry Andric       }
543*a7dea167SDimitry Andric     }
544*a7dea167SDimitry Andric     OS << "});\n";
545*a7dea167SDimitry Andric     // GenTypeNumTypes is the number of types in the GenType
546*a7dea167SDimitry Andric     // (e.g. float/double/half).
547*a7dea167SDimitry Andric     OS << "      GenTypeNumTypes = "
548*a7dea167SDimitry Andric        << GenType->getValueAsDef("TypeList")->getValueAsListOfDefs("List")
549*a7dea167SDimitry Andric               .size()
550*a7dea167SDimitry Andric        << ";\n";
551*a7dea167SDimitry Andric     // GenVectorSizes is the list of vector sizes for this GenType.
552*a7dea167SDimitry Andric     // QT contains GenTypeNumTypes * #GenVectorSizes elements.
553*a7dea167SDimitry Andric     OS << "      GenVectorSizes = List"
554*a7dea167SDimitry Andric        << GenType->getValueAsDef("VectorList")->getValueAsString("Name")
555*a7dea167SDimitry Andric        << ";\n";
556*a7dea167SDimitry Andric     OS << "      break;\n";
557*a7dea167SDimitry Andric   }
558*a7dea167SDimitry Andric 
559*a7dea167SDimitry Andric   // Switch cases for non generic, non image types (int, int4, float, ...).
560*a7dea167SDimitry Andric   // Only insert the plain scalar type; vector information and type qualifiers
561*a7dea167SDimitry Andric   // are added in step 2.
5620b57cec5SDimitry Andric   std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
5630b57cec5SDimitry Andric   StringMap<bool> TypesSeen;
5640b57cec5SDimitry Andric 
5650b57cec5SDimitry Andric   for (const auto *T : Types) {
566*a7dea167SDimitry Andric     // Check this is not an image type
567*a7dea167SDimitry Andric     if (ImageTypesMap.find(T->getValueAsString("Name")) != ImageTypesMap.end())
568*a7dea167SDimitry Andric       continue;
5690b57cec5SDimitry Andric     // Check we have not seen this Type
5700b57cec5SDimitry Andric     if (TypesSeen.find(T->getValueAsString("Name")) != TypesSeen.end())
5710b57cec5SDimitry Andric       continue;
5720b57cec5SDimitry Andric     TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true));
5730b57cec5SDimitry Andric 
5740b57cec5SDimitry Andric     // Check the Type does not have an "abstract" QualType
5750b57cec5SDimitry Andric     auto QT = T->getValueAsDef("QTName");
576*a7dea167SDimitry Andric     if (QT->getValueAsBit("IsAbstract") == 1)
5770b57cec5SDimitry Andric       continue;
578*a7dea167SDimitry Andric     // Emit the cases for non generic, non image types.
5790b57cec5SDimitry Andric     OS << "    case OCLT_" << T->getValueAsString("Name") << ":\n";
580*a7dea167SDimitry Andric     OS << "      QT.push_back(Context." << QT->getValueAsString("Name")
581*a7dea167SDimitry Andric        << ");\n";
5820b57cec5SDimitry Andric     OS << "      break;\n";
5830b57cec5SDimitry Andric   }
5840b57cec5SDimitry Andric 
585*a7dea167SDimitry Andric   // End of switch statement.
586*a7dea167SDimitry Andric   OS << "    default:\n"
587*a7dea167SDimitry Andric      << "      llvm_unreachable(\"OpenCL builtin type not handled yet\");\n"
588*a7dea167SDimitry Andric      << "  } // end of switch (Ty.ID)\n\n";
589*a7dea167SDimitry Andric 
590*a7dea167SDimitry Andric   // Step 2.
591*a7dea167SDimitry Andric   // Add ExtVector types if this was a generic type, as the switch statement
592*a7dea167SDimitry Andric   // above only populated the list with scalar types.  This completes the
593*a7dea167SDimitry Andric   // construction of the Cartesian product of (vector sizes) x (types).
594*a7dea167SDimitry Andric   OS << "  // Construct the different vector types for each generic type.\n";
595*a7dea167SDimitry Andric   OS << "  if (Ty.ID >= " << TypeList.size() << ") {";
5960b57cec5SDimitry Andric   OS << R"(
597*a7dea167SDimitry Andric     for (unsigned I = 0; I < QT.size(); I++) {
598*a7dea167SDimitry Andric       // For scalars, size is 1.
599*a7dea167SDimitry Andric       if (GenVectorSizes[I / GenTypeNumTypes] != 1) {
600*a7dea167SDimitry Andric         QT[I] = Context.getExtVectorType(QT[I],
601*a7dea167SDimitry Andric                           GenVectorSizes[I / GenTypeNumTypes]);
6020b57cec5SDimitry Andric       }
603*a7dea167SDimitry Andric     }
6040b57cec5SDimitry Andric   }
6050b57cec5SDimitry Andric )";
606*a7dea167SDimitry Andric 
607*a7dea167SDimitry Andric   // Assign the right attributes to the types (e.g. vector size).
608*a7dea167SDimitry Andric   OS << R"(
609*a7dea167SDimitry Andric   // Set vector size for non-generic vector types.
610*a7dea167SDimitry Andric   if (Ty.VectorWidth > 1) {
611*a7dea167SDimitry Andric     for (unsigned Index = 0; Index < QT.size(); Index++) {
612*a7dea167SDimitry Andric       QT[Index] = Context.getExtVectorType(QT[Index], Ty.VectorWidth);
613*a7dea167SDimitry Andric     }
6140b57cec5SDimitry Andric   }
6150b57cec5SDimitry Andric 
616*a7dea167SDimitry Andric   if (Ty.IsVolatile != 0) {
617*a7dea167SDimitry Andric     for (unsigned Index = 0; Index < QT.size(); Index++) {
618*a7dea167SDimitry Andric       QT[Index] = Context.getVolatileType(QT[Index]);
619*a7dea167SDimitry Andric     }
620*a7dea167SDimitry Andric   }
6210b57cec5SDimitry Andric 
622*a7dea167SDimitry Andric   if (Ty.IsConst != 0) {
623*a7dea167SDimitry Andric     for (unsigned Index = 0; Index < QT.size(); Index++) {
624*a7dea167SDimitry Andric       QT[Index] = Context.getConstType(QT[Index]);
625*a7dea167SDimitry Andric     }
626*a7dea167SDimitry Andric   }
627*a7dea167SDimitry Andric 
628*a7dea167SDimitry Andric   // Transform the type to a pointer as the last step, if necessary.
629*a7dea167SDimitry Andric   // Builtin functions only have pointers on [const|volatile], no
630*a7dea167SDimitry Andric   // [const|volatile] pointers, so this is ok to do it as a last step.
631*a7dea167SDimitry Andric   if (Ty.IsPointer != 0) {
632*a7dea167SDimitry Andric     for (unsigned Index = 0; Index < QT.size(); Index++) {
633*a7dea167SDimitry Andric       QT[Index] = Context.getAddrSpaceQualType(QT[Index], Ty.AS);
634*a7dea167SDimitry Andric       QT[Index] = Context.getPointerType(QT[Index]);
635*a7dea167SDimitry Andric     }
636*a7dea167SDimitry Andric   }
637*a7dea167SDimitry Andric )";
638*a7dea167SDimitry Andric 
639*a7dea167SDimitry Andric   // End of the "OCL2Qual" function.
640*a7dea167SDimitry Andric   OS << "\n} // OCL2Qual\n";
641*a7dea167SDimitry Andric }
642*a7dea167SDimitry Andric 
643*a7dea167SDimitry Andric void clang::EmitClangOpenCLBuiltins(RecordKeeper &Records, raw_ostream &OS) {
6440b57cec5SDimitry Andric   BuiltinNameEmitter NameChecker(Records, OS);
6450b57cec5SDimitry Andric   NameChecker.Emit();
6460b57cec5SDimitry Andric }
647