xref: /freebsd/contrib/llvm-project/clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp (revision fe6060f10f634930ff71b7c50291ddc610da2475)
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 //
11*fe6060f1SDimitry Andric // These backends consume the definitions of OpenCL builtin functions in
12*fe6060f1SDimitry Andric // clang/lib/Sema/OpenCLBuiltins.td and produce builtin handling code for
13*fe6060f1SDimitry Andric // inclusion in SemaLookup.cpp, or a test file that calls all declared builtins.
14*fe6060f1SDimitry Andric //
15*fe6060f1SDimitry Andric //===----------------------------------------------------------------------===//
16*fe6060f1SDimitry Andric 
17*fe6060f1SDimitry Andric #include "TableGenBackends.h"
18*fe6060f1SDimitry Andric #include "llvm/ADT/MapVector.h"
19*fe6060f1SDimitry Andric #include "llvm/ADT/STLExtras.h"
20*fe6060f1SDimitry Andric #include "llvm/ADT/SmallString.h"
21*fe6060f1SDimitry Andric #include "llvm/ADT/StringExtras.h"
22*fe6060f1SDimitry Andric #include "llvm/ADT/StringMap.h"
23*fe6060f1SDimitry Andric #include "llvm/ADT/StringRef.h"
24*fe6060f1SDimitry Andric #include "llvm/ADT/StringSwitch.h"
25*fe6060f1SDimitry Andric #include "llvm/Support/ErrorHandling.h"
26*fe6060f1SDimitry Andric #include "llvm/Support/raw_ostream.h"
27*fe6060f1SDimitry Andric #include "llvm/TableGen/Error.h"
28*fe6060f1SDimitry Andric #include "llvm/TableGen/Record.h"
29*fe6060f1SDimitry Andric #include "llvm/TableGen/StringMatcher.h"
30*fe6060f1SDimitry Andric #include "llvm/TableGen/TableGenBackend.h"
31*fe6060f1SDimitry Andric 
32*fe6060f1SDimitry Andric using namespace llvm;
33*fe6060f1SDimitry Andric 
34*fe6060f1SDimitry Andric namespace {
35*fe6060f1SDimitry Andric 
36*fe6060f1SDimitry Andric // A list of signatures that are shared by one or more builtin functions.
37*fe6060f1SDimitry Andric struct BuiltinTableEntries {
38*fe6060f1SDimitry Andric   SmallVector<StringRef, 4> Names;
39*fe6060f1SDimitry Andric   std::vector<std::pair<const Record *, unsigned>> Signatures;
40*fe6060f1SDimitry Andric };
41*fe6060f1SDimitry Andric 
420b57cec5SDimitry Andric // This tablegen backend emits code for checking whether a function is an
430b57cec5SDimitry Andric // OpenCL builtin function. If so, all overloads of this function are
440b57cec5SDimitry Andric // added to the LookupResult. The generated include file is used by
450b57cec5SDimitry Andric // SemaLookup.cpp
460b57cec5SDimitry Andric //
470b57cec5SDimitry Andric // For a successful lookup of e.g. the "cos" builtin, isOpenCLBuiltin("cos")
480b57cec5SDimitry Andric // returns a pair <Index, Len>.
49a7dea167SDimitry Andric // BuiltinTable[Index] to BuiltinTable[Index + Len] contains the pairs
500b57cec5SDimitry Andric // <SigIndex, SigLen> of the overloads of "cos".
51a7dea167SDimitry Andric // SignatureTable[SigIndex] to SignatureTable[SigIndex + SigLen] contains
52a7dea167SDimitry Andric // one of the signatures of "cos". The SignatureTable entry can be
53a7dea167SDimitry Andric // referenced by other functions, e.g. "sin", to exploit the fact that
54a7dea167SDimitry Andric // many OpenCL builtins share the same signature.
55a7dea167SDimitry Andric //
56a7dea167SDimitry Andric // The file generated by this TableGen emitter contains the following:
57a7dea167SDimitry Andric //
58a7dea167SDimitry Andric //  * Structs and enums to represent types and function signatures.
59a7dea167SDimitry Andric //
60480093f4SDimitry Andric //  * const char *FunctionExtensionTable[]
61480093f4SDimitry Andric //    List of space-separated OpenCL extensions.  A builtin references an
62480093f4SDimitry Andric //    entry in this table when the builtin requires a particular (set of)
63480093f4SDimitry Andric //    extension(s) to be enabled.
64480093f4SDimitry Andric //
65a7dea167SDimitry Andric //  * OpenCLTypeStruct TypeTable[]
66a7dea167SDimitry Andric //    Type information for return types and arguments.
67a7dea167SDimitry Andric //
68a7dea167SDimitry Andric //  * unsigned SignatureTable[]
69a7dea167SDimitry Andric //    A list of types representing function signatures.  Each entry is an index
70a7dea167SDimitry Andric //    into the above TypeTable.  Multiple entries following each other form a
71a7dea167SDimitry Andric //    signature, where the first entry is the return type and subsequent
72a7dea167SDimitry Andric //    entries are the argument types.
73a7dea167SDimitry Andric //
74a7dea167SDimitry Andric //  * OpenCLBuiltinStruct BuiltinTable[]
75a7dea167SDimitry Andric //    Each entry represents one overload of an OpenCL builtin function and
76a7dea167SDimitry Andric //    consists of an index into the SignatureTable and the number of arguments.
77a7dea167SDimitry Andric //
78a7dea167SDimitry Andric //  * std::pair<unsigned, unsigned> isOpenCLBuiltin(llvm::StringRef Name)
79a7dea167SDimitry Andric //    Find out whether a string matches an existing OpenCL builtin function
80a7dea167SDimitry Andric //    name and return an index into BuiltinTable and the number of overloads.
81a7dea167SDimitry Andric //
82*fe6060f1SDimitry Andric //  * void OCL2Qual(Sema&, OpenCLTypeStruct, std::vector<QualType>&)
83a7dea167SDimitry Andric //    Convert an OpenCLTypeStruct type to a list of QualType instances.
84a7dea167SDimitry Andric //    One OpenCLTypeStruct can represent multiple types, primarily when using
85a7dea167SDimitry Andric //    GenTypes.
86a7dea167SDimitry Andric //
870b57cec5SDimitry Andric class BuiltinNameEmitter {
880b57cec5SDimitry Andric public:
890b57cec5SDimitry Andric   BuiltinNameEmitter(RecordKeeper &Records, raw_ostream &OS)
900b57cec5SDimitry Andric       : Records(Records), OS(OS) {}
910b57cec5SDimitry Andric 
920b57cec5SDimitry Andric   // Entrypoint to generate the functions and structures for checking
930b57cec5SDimitry Andric   // whether a function is an OpenCL builtin function.
940b57cec5SDimitry Andric   void Emit();
950b57cec5SDimitry Andric 
960b57cec5SDimitry Andric private:
97480093f4SDimitry Andric   // A list of indices into the builtin function table.
98480093f4SDimitry Andric   using BuiltinIndexListTy = SmallVector<unsigned, 11>;
99480093f4SDimitry Andric 
1000b57cec5SDimitry Andric   // Contains OpenCL builtin functions and related information, stored as
1010b57cec5SDimitry Andric   // Record instances. They are coming from the associated TableGen file.
1020b57cec5SDimitry Andric   RecordKeeper &Records;
1030b57cec5SDimitry Andric 
1040b57cec5SDimitry Andric   // The output file.
1050b57cec5SDimitry Andric   raw_ostream &OS;
1060b57cec5SDimitry Andric 
107a7dea167SDimitry Andric   // Helper function for BuiltinNameEmitter::EmitDeclarations.  Generate enum
108a7dea167SDimitry Andric   // definitions in the Output string parameter, and save their Record instances
109a7dea167SDimitry Andric   // in the List parameter.
110a7dea167SDimitry Andric   // \param Types (in) List containing the Types to extract.
111a7dea167SDimitry Andric   // \param TypesSeen (inout) List containing the Types already extracted.
112a7dea167SDimitry Andric   // \param Output (out) String containing the enums to emit in the output file.
113a7dea167SDimitry Andric   // \param List (out) List containing the extracted Types, except the Types in
114a7dea167SDimitry Andric   //        TypesSeen.
115a7dea167SDimitry Andric   void ExtractEnumTypes(std::vector<Record *> &Types,
116a7dea167SDimitry Andric                         StringMap<bool> &TypesSeen, std::string &Output,
117a7dea167SDimitry Andric                         std::vector<const Record *> &List);
118a7dea167SDimitry Andric 
119a7dea167SDimitry Andric   // Emit the enum or struct used in the generated file.
120a7dea167SDimitry Andric   // Populate the TypeList at the same time.
1210b57cec5SDimitry Andric   void EmitDeclarations();
1220b57cec5SDimitry Andric 
123a7dea167SDimitry Andric   // Parse the Records generated by TableGen to populate the SignaturesList,
124a7dea167SDimitry Andric   // FctOverloadMap and TypeMap.
1250b57cec5SDimitry Andric   void GetOverloads();
1260b57cec5SDimitry Andric 
127480093f4SDimitry Andric   // Compare two lists of signatures and check that e.g. the OpenCL version,
128480093f4SDimitry Andric   // function attributes, and extension are equal for each signature.
129480093f4SDimitry Andric   // \param Candidate (in) Entry in the SignatureListMap to check.
130480093f4SDimitry Andric   // \param SignatureList (in) List of signatures of the considered function.
131480093f4SDimitry Andric   // \returns true if the two lists of signatures are identical.
132480093f4SDimitry Andric   bool CanReuseSignature(
133480093f4SDimitry Andric       BuiltinIndexListTy *Candidate,
134480093f4SDimitry Andric       std::vector<std::pair<const Record *, unsigned>> &SignatureList);
135480093f4SDimitry Andric 
136480093f4SDimitry Andric   // Group functions with the same list of signatures by populating the
137480093f4SDimitry Andric   // SignatureListMap.
138480093f4SDimitry Andric   // Some builtin functions have the same list of signatures, for example the
139480093f4SDimitry Andric   // "sin" and "cos" functions. To save space in the BuiltinTable, the
140480093f4SDimitry Andric   // "isOpenCLBuiltin" function will have the same output for these two
141480093f4SDimitry Andric   // function names.
142480093f4SDimitry Andric   void GroupBySignature();
143480093f4SDimitry Andric 
144480093f4SDimitry Andric   // Emit the FunctionExtensionTable that lists all function extensions.
145480093f4SDimitry Andric   void EmitExtensionTable();
146480093f4SDimitry Andric 
147a7dea167SDimitry Andric   // Emit the TypeTable containing all types used by OpenCL builtins.
148a7dea167SDimitry Andric   void EmitTypeTable();
149a7dea167SDimitry Andric 
150a7dea167SDimitry Andric   // Emit the SignatureTable. This table contains all the possible signatures.
151a7dea167SDimitry Andric   // A signature is stored as a list of indexes of the TypeTable.
152a7dea167SDimitry Andric   // The first index references the return type (mandatory), and the followings
153a7dea167SDimitry Andric   // reference its arguments.
1540b57cec5SDimitry Andric   // E.g.:
155a7dea167SDimitry Andric   // 15, 2, 15 can represent a function with the signature:
156a7dea167SDimitry Andric   // int func(float, int)
157a7dea167SDimitry Andric   // The "int" type being at the index 15 in the TypeTable.
1580b57cec5SDimitry Andric   void EmitSignatureTable();
1590b57cec5SDimitry Andric 
160a7dea167SDimitry Andric   // Emit the BuiltinTable table. This table contains all the overloads of
1610b57cec5SDimitry Andric   // each function, and is a struct OpenCLBuiltinDecl.
1620b57cec5SDimitry Andric   // E.g.:
163a7dea167SDimitry Andric   // // 891 convert_float2_rtn
164480093f4SDimitry Andric   //   { 58, 2, 3, 100, 0 },
165a7dea167SDimitry Andric   // This means that the signature of this convert_float2_rtn overload has
166a7dea167SDimitry Andric   // 1 argument (+1 for the return type), stored at index 58 in
167480093f4SDimitry Andric   // the SignatureTable.  This prototype requires extension "3" in the
168480093f4SDimitry Andric   // FunctionExtensionTable.  The last two values represent the minimum (1.0)
169480093f4SDimitry Andric   // and maximum (0, meaning no max version) OpenCL version in which this
170480093f4SDimitry Andric   // overload is supported.
1710b57cec5SDimitry Andric   void EmitBuiltinTable();
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric   // Emit a StringMatcher function to check whether a function name is an
1740b57cec5SDimitry Andric   // OpenCL builtin function name.
1750b57cec5SDimitry Andric   void EmitStringMatcher();
1760b57cec5SDimitry Andric 
1770b57cec5SDimitry Andric   // Emit a function returning the clang QualType instance associated with
1780b57cec5SDimitry Andric   // the TableGen Record Type.
1790b57cec5SDimitry Andric   void EmitQualTypeFinder();
1800b57cec5SDimitry Andric 
1810b57cec5SDimitry Andric   // Contains a list of the available signatures, without the name of the
1820b57cec5SDimitry Andric   // function. Each pair consists of a signature and a cumulative index.
1830b57cec5SDimitry Andric   // E.g.:  <<float, float>, 0>,
1840b57cec5SDimitry Andric   //        <<float, int, int, 2>>,
1850b57cec5SDimitry Andric   //        <<float>, 5>,
1860b57cec5SDimitry Andric   //        ...
1870b57cec5SDimitry Andric   //        <<double, double>, 35>.
188a7dea167SDimitry Andric   std::vector<std::pair<std::vector<Record *>, unsigned>> SignaturesList;
1890b57cec5SDimitry Andric 
1900b57cec5SDimitry Andric   // Map the name of a builtin function to its prototypes (instances of the
1910b57cec5SDimitry Andric   // TableGen "Builtin" class).
1920b57cec5SDimitry Andric   // Each prototype is registered as a pair of:
1930b57cec5SDimitry Andric   //   <pointer to the "Builtin" instance,
194a7dea167SDimitry Andric   //    cumulative index of the associated signature in the SignaturesList>
1950b57cec5SDimitry Andric   // E.g.:  The function cos: (float cos(float), double cos(double), ...)
1960b57cec5SDimitry Andric   //        <"cos", <<ptrToPrototype0, 5>,
197a7dea167SDimitry Andric   //                 <ptrToPrototype1, 35>,
1980b57cec5SDimitry Andric   //                 <ptrToPrototype2, 79>>
1990b57cec5SDimitry Andric   // ptrToPrototype1 has the following signature: <double, double>
2000b57cec5SDimitry Andric   MapVector<StringRef, std::vector<std::pair<const Record *, unsigned>>>
201a7dea167SDimitry Andric       FctOverloadMap;
202a7dea167SDimitry Andric 
203a7dea167SDimitry Andric   // Contains the map of OpenCL types to their index in the TypeTable.
204a7dea167SDimitry Andric   MapVector<const Record *, unsigned> TypeMap;
205a7dea167SDimitry Andric 
206480093f4SDimitry Andric   // List of OpenCL function extensions mapping extension strings to
207480093f4SDimitry Andric   // an index into the FunctionExtensionTable.
208480093f4SDimitry Andric   StringMap<unsigned> FunctionExtensionIndex;
209480093f4SDimitry Andric 
210a7dea167SDimitry Andric   // List of OpenCL type names in the same order as in enum OpenCLTypeID.
211a7dea167SDimitry Andric   // This list does not contain generic types.
212a7dea167SDimitry Andric   std::vector<const Record *> TypeList;
213a7dea167SDimitry Andric 
214a7dea167SDimitry Andric   // Same as TypeList, but for generic types only.
215a7dea167SDimitry Andric   std::vector<const Record *> GenTypeList;
216480093f4SDimitry Andric 
217480093f4SDimitry Andric   // Map an ordered vector of signatures to their original Record instances,
218480093f4SDimitry Andric   // and to a list of function names that share these signatures.
219480093f4SDimitry Andric   //
220480093f4SDimitry Andric   // For example, suppose the "cos" and "sin" functions have only three
221480093f4SDimitry Andric   // signatures, and these signatures are at index Ix in the SignatureTable:
222480093f4SDimitry Andric   //          cos         |         sin         |  Signature    | Index
223480093f4SDimitry Andric   //  float   cos(float)  | float   sin(float)  |  Signature1   | I1
224480093f4SDimitry Andric   //  double  cos(double) | double  sin(double) |  Signature2   | I2
225480093f4SDimitry Andric   //  half    cos(half)   | half    sin(half)   |  Signature3   | I3
226480093f4SDimitry Andric   //
227480093f4SDimitry Andric   // Then we will create a mapping of the vector of signatures:
228480093f4SDimitry Andric   // SignatureListMap[<I1, I2, I3>] = <
229480093f4SDimitry Andric   //                  <"cos", "sin">,
230480093f4SDimitry Andric   //                  <Signature1, Signature2, Signature3>>
231480093f4SDimitry Andric   // The function "tan", having the same signatures, would be mapped to the
232480093f4SDimitry Andric   // same entry (<I1, I2, I3>).
233480093f4SDimitry Andric   MapVector<BuiltinIndexListTy *, BuiltinTableEntries> SignatureListMap;
2340b57cec5SDimitry Andric };
235*fe6060f1SDimitry Andric 
236*fe6060f1SDimitry Andric // OpenCL builtin test generator.  This class processes the same TableGen input
237*fe6060f1SDimitry Andric // as BuiltinNameEmitter, but generates a .cl file that contains a call to each
238*fe6060f1SDimitry Andric // builtin function described in the .td input.
239*fe6060f1SDimitry Andric class OpenCLBuiltinTestEmitter {
240*fe6060f1SDimitry Andric public:
241*fe6060f1SDimitry Andric   OpenCLBuiltinTestEmitter(RecordKeeper &Records, raw_ostream &OS)
242*fe6060f1SDimitry Andric       : Records(Records), OS(OS) {}
243*fe6060f1SDimitry Andric 
244*fe6060f1SDimitry Andric   // Entrypoint to generate the functions for testing all OpenCL builtin
245*fe6060f1SDimitry Andric   // functions.
246*fe6060f1SDimitry Andric   void emit();
247*fe6060f1SDimitry Andric 
248*fe6060f1SDimitry Andric private:
249*fe6060f1SDimitry Andric   struct TypeFlags {
250*fe6060f1SDimitry Andric     TypeFlags() : IsConst(false), IsVolatile(false), IsPointer(false) {}
251*fe6060f1SDimitry Andric     bool IsConst : 1;
252*fe6060f1SDimitry Andric     bool IsVolatile : 1;
253*fe6060f1SDimitry Andric     bool IsPointer : 1;
254*fe6060f1SDimitry Andric     StringRef AddrSpace;
255*fe6060f1SDimitry Andric   };
256*fe6060f1SDimitry Andric 
257*fe6060f1SDimitry Andric   // Return a string representation of the given type, such that it can be
258*fe6060f1SDimitry Andric   // used as a type in OpenCL C code.
259*fe6060f1SDimitry Andric   std::string getTypeString(const Record *Type, TypeFlags Flags,
260*fe6060f1SDimitry Andric                             int VectorSize) const;
261*fe6060f1SDimitry Andric 
262*fe6060f1SDimitry Andric   // Return the type(s) and vector size(s) for the given type.  For
263*fe6060f1SDimitry Andric   // non-GenericTypes, the resulting vectors will contain 1 element.  For
264*fe6060f1SDimitry Andric   // GenericTypes, the resulting vectors typically contain multiple elements.
265*fe6060f1SDimitry Andric   void getTypeLists(Record *Type, TypeFlags &Flags,
266*fe6060f1SDimitry Andric                     std::vector<Record *> &TypeList,
267*fe6060f1SDimitry Andric                     std::vector<int64_t> &VectorList) const;
268*fe6060f1SDimitry Andric 
269*fe6060f1SDimitry Andric   // Expand the TableGen Records representing a builtin function signature into
270*fe6060f1SDimitry Andric   // one or more function signatures.  Return them as a vector of a vector of
271*fe6060f1SDimitry Andric   // strings, with each string containing an OpenCL C type and optional
272*fe6060f1SDimitry Andric   // qualifiers.
273*fe6060f1SDimitry Andric   //
274*fe6060f1SDimitry Andric   // The Records may contain GenericTypes, which expand into multiple
275*fe6060f1SDimitry Andric   // signatures.  Repeated occurrences of GenericType in a signature expand to
276*fe6060f1SDimitry Andric   // the same types.  For example [char, FGenType, FGenType] expands to:
277*fe6060f1SDimitry Andric   //   [char, float, float]
278*fe6060f1SDimitry Andric   //   [char, float2, float2]
279*fe6060f1SDimitry Andric   //   [char, float3, float3]
280*fe6060f1SDimitry Andric   //   ...
281*fe6060f1SDimitry Andric   void
282*fe6060f1SDimitry Andric   expandTypesInSignature(const std::vector<Record *> &Signature,
283*fe6060f1SDimitry Andric                          SmallVectorImpl<SmallVector<std::string, 2>> &Types);
284*fe6060f1SDimitry Andric 
285*fe6060f1SDimitry Andric   // Contains OpenCL builtin functions and related information, stored as
286*fe6060f1SDimitry Andric   // Record instances. They are coming from the associated TableGen file.
287*fe6060f1SDimitry Andric   RecordKeeper &Records;
288*fe6060f1SDimitry Andric 
289*fe6060f1SDimitry Andric   // The output file.
290*fe6060f1SDimitry Andric   raw_ostream &OS;
291*fe6060f1SDimitry Andric };
292*fe6060f1SDimitry Andric 
2930b57cec5SDimitry Andric } // namespace
2940b57cec5SDimitry Andric 
2950b57cec5SDimitry Andric void BuiltinNameEmitter::Emit() {
2960b57cec5SDimitry Andric   emitSourceFileHeader("OpenCL Builtin handling", OS);
2970b57cec5SDimitry Andric 
2980b57cec5SDimitry Andric   OS << "#include \"llvm/ADT/StringRef.h\"\n";
2990b57cec5SDimitry Andric   OS << "using namespace clang;\n\n";
3000b57cec5SDimitry Andric 
301a7dea167SDimitry Andric   // Emit enums and structs.
3020b57cec5SDimitry Andric   EmitDeclarations();
3030b57cec5SDimitry Andric 
304480093f4SDimitry Andric   // Parse the Records to populate the internal lists.
3050b57cec5SDimitry Andric   GetOverloads();
306480093f4SDimitry Andric   GroupBySignature();
3070b57cec5SDimitry Andric 
308a7dea167SDimitry Andric   // Emit tables.
309480093f4SDimitry Andric   EmitExtensionTable();
310a7dea167SDimitry Andric   EmitTypeTable();
3110b57cec5SDimitry Andric   EmitSignatureTable();
3120b57cec5SDimitry Andric   EmitBuiltinTable();
3130b57cec5SDimitry Andric 
314480093f4SDimitry Andric   // Emit functions.
3150b57cec5SDimitry Andric   EmitStringMatcher();
3160b57cec5SDimitry Andric   EmitQualTypeFinder();
3170b57cec5SDimitry Andric }
3180b57cec5SDimitry Andric 
319a7dea167SDimitry Andric void BuiltinNameEmitter::ExtractEnumTypes(std::vector<Record *> &Types,
320a7dea167SDimitry Andric                                           StringMap<bool> &TypesSeen,
321a7dea167SDimitry Andric                                           std::string &Output,
322a7dea167SDimitry Andric                                           std::vector<const Record *> &List) {
323a7dea167SDimitry Andric   raw_string_ostream SS(Output);
324a7dea167SDimitry Andric 
3250b57cec5SDimitry Andric   for (const auto *T : Types) {
326a7dea167SDimitry Andric     if (TypesSeen.find(T->getValueAsString("Name")) == TypesSeen.end()) {
327a7dea167SDimitry Andric       SS << "  OCLT_" + T->getValueAsString("Name") << ",\n";
328a7dea167SDimitry Andric       // Save the type names in the same order as their enum value. Note that
329a7dea167SDimitry Andric       // the Record can be a VectorType or something else, only the name is
330a7dea167SDimitry Andric       // important.
331a7dea167SDimitry Andric       List.push_back(T);
3320b57cec5SDimitry Andric       TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true));
3330b57cec5SDimitry Andric     }
334a7dea167SDimitry Andric   }
335a7dea167SDimitry Andric   SS.flush();
336a7dea167SDimitry Andric }
337a7dea167SDimitry Andric 
338a7dea167SDimitry Andric void BuiltinNameEmitter::EmitDeclarations() {
339a7dea167SDimitry Andric   // Enum of scalar type names (float, int, ...) and generic type sets.
340a7dea167SDimitry Andric   OS << "enum OpenCLTypeID {\n";
341a7dea167SDimitry Andric 
342a7dea167SDimitry Andric   StringMap<bool> TypesSeen;
343a7dea167SDimitry Andric   std::string GenTypeEnums;
344a7dea167SDimitry Andric   std::string TypeEnums;
345a7dea167SDimitry Andric 
346a7dea167SDimitry Andric   // Extract generic types and non-generic types separately, to keep
347a7dea167SDimitry Andric   // gentypes at the end of the enum which simplifies the special handling
348a7dea167SDimitry Andric   // for gentypes in SemaLookup.
349a7dea167SDimitry Andric   std::vector<Record *> GenTypes =
350a7dea167SDimitry Andric       Records.getAllDerivedDefinitions("GenericType");
351a7dea167SDimitry Andric   ExtractEnumTypes(GenTypes, TypesSeen, GenTypeEnums, GenTypeList);
352a7dea167SDimitry Andric 
353a7dea167SDimitry Andric   std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
354a7dea167SDimitry Andric   ExtractEnumTypes(Types, TypesSeen, TypeEnums, TypeList);
355a7dea167SDimitry Andric 
356a7dea167SDimitry Andric   OS << TypeEnums;
357a7dea167SDimitry Andric   OS << GenTypeEnums;
3580b57cec5SDimitry Andric   OS << "};\n";
3590b57cec5SDimitry Andric 
360a7dea167SDimitry Andric   // Structure definitions.
3610b57cec5SDimitry Andric   OS << R"(
362a7dea167SDimitry Andric // Image access qualifier.
363a7dea167SDimitry Andric enum OpenCLAccessQual : unsigned char {
364a7dea167SDimitry Andric   OCLAQ_None,
365a7dea167SDimitry Andric   OCLAQ_ReadOnly,
366a7dea167SDimitry Andric   OCLAQ_WriteOnly,
367a7dea167SDimitry Andric   OCLAQ_ReadWrite
368a7dea167SDimitry Andric };
3690b57cec5SDimitry Andric 
370a7dea167SDimitry Andric // Represents a return type or argument type.
371a7dea167SDimitry Andric struct OpenCLTypeStruct {
372a7dea167SDimitry Andric   // A type (e.g. float, int, ...).
373a7dea167SDimitry Andric   const OpenCLTypeID ID;
374a7dea167SDimitry Andric   // Vector size (if applicable; 0 for scalars and generic types).
375a7dea167SDimitry Andric   const unsigned VectorWidth;
376a7dea167SDimitry Andric   // 0 if the type is not a pointer.
3775ffd83dbSDimitry Andric   const bool IsPointer : 1;
378a7dea167SDimitry Andric   // 0 if the type is not const.
3795ffd83dbSDimitry Andric   const bool IsConst : 1;
380a7dea167SDimitry Andric   // 0 if the type is not volatile.
3815ffd83dbSDimitry Andric   const bool IsVolatile : 1;
382a7dea167SDimitry Andric   // Access qualifier.
383a7dea167SDimitry Andric   const OpenCLAccessQual AccessQualifier;
384a7dea167SDimitry Andric   // Address space of the pointer (if applicable).
385a7dea167SDimitry Andric   const LangAS AS;
3860b57cec5SDimitry Andric };
3870b57cec5SDimitry Andric 
3880b57cec5SDimitry Andric // One overload of an OpenCL builtin function.
389a7dea167SDimitry Andric struct OpenCLBuiltinStruct {
390a7dea167SDimitry Andric   // Index of the signature in the OpenCLTypeStruct table.
391a7dea167SDimitry Andric   const unsigned SigTableIndex;
392a7dea167SDimitry Andric   // Entries between index SigTableIndex and (SigTableIndex + NumTypes - 1) in
393a7dea167SDimitry Andric   // the SignatureTable represent the complete signature.  The first type at
394a7dea167SDimitry Andric   // index SigTableIndex is the return type.
395a7dea167SDimitry Andric   const unsigned NumTypes;
396480093f4SDimitry Andric   // Function attribute __attribute__((pure))
3975ffd83dbSDimitry Andric   const bool IsPure : 1;
398480093f4SDimitry Andric   // Function attribute __attribute__((const))
3995ffd83dbSDimitry Andric   const bool IsConst : 1;
400480093f4SDimitry Andric   // Function attribute __attribute__((convergent))
4015ffd83dbSDimitry Andric   const bool IsConv : 1;
402480093f4SDimitry Andric   // OpenCL extension(s) required for this overload.
403480093f4SDimitry Andric   const unsigned short Extension;
404*fe6060f1SDimitry Andric   // OpenCL versions in which this overload is available.
405*fe6060f1SDimitry Andric   const unsigned short Versions;
4060b57cec5SDimitry Andric };
4070b57cec5SDimitry Andric 
4080b57cec5SDimitry Andric )";
4090b57cec5SDimitry Andric }
4100b57cec5SDimitry Andric 
411a7dea167SDimitry Andric // Verify that the combination of GenTypes in a signature is supported.
412a7dea167SDimitry Andric // To simplify the logic for creating overloads in SemaLookup, only allow
413a7dea167SDimitry Andric // a signature to contain different GenTypes if these GenTypes represent
414a7dea167SDimitry Andric // the same number of actual scalar or vector types.
415a7dea167SDimitry Andric //
416a7dea167SDimitry Andric // Exit with a fatal error if an unsupported construct is encountered.
417a7dea167SDimitry Andric static void VerifySignature(const std::vector<Record *> &Signature,
418a7dea167SDimitry Andric                             const Record *BuiltinRec) {
419a7dea167SDimitry Andric   unsigned GenTypeVecSizes = 1;
420a7dea167SDimitry Andric   unsigned GenTypeTypes = 1;
421a7dea167SDimitry Andric 
422a7dea167SDimitry Andric   for (const auto *T : Signature) {
423a7dea167SDimitry Andric     // Check all GenericType arguments in this signature.
424a7dea167SDimitry Andric     if (T->isSubClassOf("GenericType")) {
425a7dea167SDimitry Andric       // Check number of vector sizes.
426a7dea167SDimitry Andric       unsigned NVecSizes =
427a7dea167SDimitry Andric           T->getValueAsDef("VectorList")->getValueAsListOfInts("List").size();
428a7dea167SDimitry Andric       if (NVecSizes != GenTypeVecSizes && NVecSizes != 1) {
429a7dea167SDimitry Andric         if (GenTypeVecSizes > 1) {
430a7dea167SDimitry Andric           // We already saw a gentype with a different number of vector sizes.
431a7dea167SDimitry Andric           PrintFatalError(BuiltinRec->getLoc(),
432a7dea167SDimitry Andric               "number of vector sizes should be equal or 1 for all gentypes "
433a7dea167SDimitry Andric               "in a declaration");
434a7dea167SDimitry Andric         }
435a7dea167SDimitry Andric         GenTypeVecSizes = NVecSizes;
436a7dea167SDimitry Andric       }
437a7dea167SDimitry Andric 
438a7dea167SDimitry Andric       // Check number of data types.
439a7dea167SDimitry Andric       unsigned NTypes =
440a7dea167SDimitry Andric           T->getValueAsDef("TypeList")->getValueAsListOfDefs("List").size();
441a7dea167SDimitry Andric       if (NTypes != GenTypeTypes && NTypes != 1) {
442a7dea167SDimitry Andric         if (GenTypeTypes > 1) {
443a7dea167SDimitry Andric           // We already saw a gentype with a different number of types.
444a7dea167SDimitry Andric           PrintFatalError(BuiltinRec->getLoc(),
445a7dea167SDimitry Andric               "number of types should be equal or 1 for all gentypes "
446a7dea167SDimitry Andric               "in a declaration");
447a7dea167SDimitry Andric         }
448a7dea167SDimitry Andric         GenTypeTypes = NTypes;
449a7dea167SDimitry Andric       }
450a7dea167SDimitry Andric     }
451a7dea167SDimitry Andric   }
452a7dea167SDimitry Andric }
453a7dea167SDimitry Andric 
4540b57cec5SDimitry Andric void BuiltinNameEmitter::GetOverloads() {
455a7dea167SDimitry Andric   // Populate the TypeMap.
456a7dea167SDimitry Andric   std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
457a7dea167SDimitry Andric   unsigned I = 0;
458a7dea167SDimitry Andric   for (const auto &T : Types) {
459a7dea167SDimitry Andric     TypeMap.insert(std::make_pair(T, I++));
460a7dea167SDimitry Andric   }
461a7dea167SDimitry Andric 
462a7dea167SDimitry Andric   // Populate the SignaturesList and the FctOverloadMap.
4630b57cec5SDimitry Andric   unsigned CumulativeSignIndex = 0;
4640b57cec5SDimitry Andric   std::vector<Record *> Builtins = Records.getAllDerivedDefinitions("Builtin");
4650b57cec5SDimitry Andric   for (const auto *B : Builtins) {
4660b57cec5SDimitry Andric     StringRef BName = B->getValueAsString("Name");
467a7dea167SDimitry Andric     if (FctOverloadMap.find(BName) == FctOverloadMap.end()) {
468a7dea167SDimitry Andric       FctOverloadMap.insert(std::make_pair(
4690b57cec5SDimitry Andric           BName, std::vector<std::pair<const Record *, unsigned>>{}));
4700b57cec5SDimitry Andric     }
4710b57cec5SDimitry Andric 
4720b57cec5SDimitry Andric     auto Signature = B->getValueAsListOfDefs("Signature");
473a7dea167SDimitry Andric     // Reuse signatures to avoid unnecessary duplicates.
4740b57cec5SDimitry Andric     auto it =
475a7dea167SDimitry Andric         std::find_if(SignaturesList.begin(), SignaturesList.end(),
4760b57cec5SDimitry Andric                      [&](const std::pair<std::vector<Record *>, unsigned> &a) {
4770b57cec5SDimitry Andric                        return a.first == Signature;
4780b57cec5SDimitry Andric                      });
4790b57cec5SDimitry Andric     unsigned SignIndex;
480a7dea167SDimitry Andric     if (it == SignaturesList.end()) {
481a7dea167SDimitry Andric       VerifySignature(Signature, B);
482a7dea167SDimitry Andric       SignaturesList.push_back(std::make_pair(Signature, CumulativeSignIndex));
4830b57cec5SDimitry Andric       SignIndex = CumulativeSignIndex;
4840b57cec5SDimitry Andric       CumulativeSignIndex += Signature.size();
4850b57cec5SDimitry Andric     } else {
4860b57cec5SDimitry Andric       SignIndex = it->second;
4870b57cec5SDimitry Andric     }
488a7dea167SDimitry Andric     FctOverloadMap[BName].push_back(std::make_pair(B, SignIndex));
4890b57cec5SDimitry Andric   }
4900b57cec5SDimitry Andric }
4910b57cec5SDimitry Andric 
492480093f4SDimitry Andric void BuiltinNameEmitter::EmitExtensionTable() {
493480093f4SDimitry Andric   OS << "static const char *FunctionExtensionTable[] = {\n";
494480093f4SDimitry Andric   unsigned Index = 0;
495480093f4SDimitry Andric   std::vector<Record *> FuncExtensions =
496480093f4SDimitry Andric       Records.getAllDerivedDefinitions("FunctionExtension");
497480093f4SDimitry Andric 
498480093f4SDimitry Andric   for (const auto &FE : FuncExtensions) {
499480093f4SDimitry Andric     // Emit OpenCL extension table entry.
500480093f4SDimitry Andric     OS << "  // " << Index << ": " << FE->getName() << "\n"
501480093f4SDimitry Andric        << "  \"" << FE->getValueAsString("ExtName") << "\",\n";
502480093f4SDimitry Andric 
503480093f4SDimitry Andric     // Record index of this extension.
504480093f4SDimitry Andric     FunctionExtensionIndex[FE->getName()] = Index++;
505480093f4SDimitry Andric   }
506480093f4SDimitry Andric   OS << "};\n\n";
507480093f4SDimitry Andric }
508480093f4SDimitry Andric 
509a7dea167SDimitry Andric void BuiltinNameEmitter::EmitTypeTable() {
510a7dea167SDimitry Andric   OS << "static const OpenCLTypeStruct TypeTable[] = {\n";
511a7dea167SDimitry Andric   for (const auto &T : TypeMap) {
512a7dea167SDimitry Andric     const char *AccessQual =
513a7dea167SDimitry Andric         StringSwitch<const char *>(T.first->getValueAsString("AccessQualifier"))
514a7dea167SDimitry Andric             .Case("RO", "OCLAQ_ReadOnly")
515a7dea167SDimitry Andric             .Case("WO", "OCLAQ_WriteOnly")
516a7dea167SDimitry Andric             .Case("RW", "OCLAQ_ReadWrite")
517a7dea167SDimitry Andric             .Default("OCLAQ_None");
518a7dea167SDimitry Andric 
519a7dea167SDimitry Andric     OS << "  // " << T.second << "\n"
520a7dea167SDimitry Andric        << "  {OCLT_" << T.first->getValueAsString("Name") << ", "
521a7dea167SDimitry Andric        << T.first->getValueAsInt("VecWidth") << ", "
522a7dea167SDimitry Andric        << T.first->getValueAsBit("IsPointer") << ", "
523a7dea167SDimitry Andric        << T.first->getValueAsBit("IsConst") << ", "
524a7dea167SDimitry Andric        << T.first->getValueAsBit("IsVolatile") << ", "
525a7dea167SDimitry Andric        << AccessQual << ", "
526a7dea167SDimitry Andric        << T.first->getValueAsString("AddrSpace") << "},\n";
5270b57cec5SDimitry Andric   }
528a7dea167SDimitry Andric   OS << "};\n\n";
529a7dea167SDimitry Andric }
530a7dea167SDimitry Andric 
531a7dea167SDimitry Andric void BuiltinNameEmitter::EmitSignatureTable() {
532a7dea167SDimitry Andric   // Store a type (e.g. int, float, int2, ...). The type is stored as an index
533a7dea167SDimitry Andric   // of a struct OpenCLType table. Multiple entries following each other form a
534a7dea167SDimitry Andric   // signature.
5355ffd83dbSDimitry Andric   OS << "static const unsigned short SignatureTable[] = {\n";
536a7dea167SDimitry Andric   for (const auto &P : SignaturesList) {
537a7dea167SDimitry Andric     OS << "  // " << P.second << "\n  ";
538a7dea167SDimitry Andric     for (const Record *R : P.first) {
5395ffd83dbSDimitry Andric       unsigned Entry = TypeMap.find(R)->second;
5405ffd83dbSDimitry Andric       if (Entry > USHRT_MAX) {
5415ffd83dbSDimitry Andric         // Report an error when seeing an entry that is too large for the
5425ffd83dbSDimitry Andric         // current index type (unsigned short).  When hitting this, the type
5435ffd83dbSDimitry Andric         // of SignatureTable will need to be changed.
5445ffd83dbSDimitry Andric         PrintFatalError("Entry in SignatureTable exceeds limit.");
5455ffd83dbSDimitry Andric       }
5465ffd83dbSDimitry Andric       OS << Entry << ", ";
547a7dea167SDimitry Andric     }
548a7dea167SDimitry Andric     OS << "\n";
5490b57cec5SDimitry Andric   }
5500b57cec5SDimitry Andric   OS << "};\n\n";
5510b57cec5SDimitry Andric }
5520b57cec5SDimitry Andric 
553*fe6060f1SDimitry Andric // Encode a range MinVersion..MaxVersion into a single bit mask that can be
554*fe6060f1SDimitry Andric // checked against LangOpts using isOpenCLVersionContainedInMask().
555*fe6060f1SDimitry Andric // This must be kept in sync with OpenCLVersionID in OpenCLOptions.h.
556*fe6060f1SDimitry Andric // (Including OpenCLOptions.h here would be a layering violation.)
557*fe6060f1SDimitry Andric static unsigned short EncodeVersions(unsigned int MinVersion,
558*fe6060f1SDimitry Andric                                      unsigned int MaxVersion) {
559*fe6060f1SDimitry Andric   unsigned short Encoded = 0;
560*fe6060f1SDimitry Andric 
561*fe6060f1SDimitry Andric   // A maximum version of 0 means available in all later versions.
562*fe6060f1SDimitry Andric   if (MaxVersion == 0) {
563*fe6060f1SDimitry Andric     MaxVersion = UINT_MAX;
564*fe6060f1SDimitry Andric   }
565*fe6060f1SDimitry Andric 
566*fe6060f1SDimitry Andric   unsigned VersionIDs[] = {100, 110, 120, 200, 300};
567*fe6060f1SDimitry Andric   for (unsigned I = 0; I < sizeof(VersionIDs) / sizeof(VersionIDs[0]); I++) {
568*fe6060f1SDimitry Andric     if (VersionIDs[I] >= MinVersion && VersionIDs[I] < MaxVersion) {
569*fe6060f1SDimitry Andric       Encoded |= 1 << I;
570*fe6060f1SDimitry Andric     }
571*fe6060f1SDimitry Andric   }
572*fe6060f1SDimitry Andric 
573*fe6060f1SDimitry Andric   return Encoded;
574*fe6060f1SDimitry Andric }
575*fe6060f1SDimitry Andric 
5760b57cec5SDimitry Andric void BuiltinNameEmitter::EmitBuiltinTable() {
577a7dea167SDimitry Andric   unsigned Index = 0;
578a7dea167SDimitry Andric 
579a7dea167SDimitry Andric   OS << "static const OpenCLBuiltinStruct BuiltinTable[] = {\n";
580480093f4SDimitry Andric   for (const auto &SLM : SignatureListMap) {
581a7dea167SDimitry Andric 
582480093f4SDimitry Andric     OS << "  // " << (Index + 1) << ": ";
583480093f4SDimitry Andric     for (const auto &Name : SLM.second.Names) {
584480093f4SDimitry Andric       OS << Name << ", ";
585480093f4SDimitry Andric     }
586480093f4SDimitry Andric     OS << "\n";
587a7dea167SDimitry Andric 
588480093f4SDimitry Andric     for (const auto &Overload : SLM.second.Signatures) {
589480093f4SDimitry Andric       StringRef ExtName = Overload.first->getValueAsDef("Extension")->getName();
590*fe6060f1SDimitry Andric       unsigned int MinVersion =
591*fe6060f1SDimitry Andric           Overload.first->getValueAsDef("MinVersion")->getValueAsInt("ID");
592*fe6060f1SDimitry Andric       unsigned int MaxVersion =
593*fe6060f1SDimitry Andric           Overload.first->getValueAsDef("MaxVersion")->getValueAsInt("ID");
594*fe6060f1SDimitry Andric 
595a7dea167SDimitry Andric       OS << "  { " << Overload.second << ", "
596a7dea167SDimitry Andric          << Overload.first->getValueAsListOfDefs("Signature").size() << ", "
597480093f4SDimitry Andric          << (Overload.first->getValueAsBit("IsPure")) << ", "
598480093f4SDimitry Andric          << (Overload.first->getValueAsBit("IsConst")) << ", "
599480093f4SDimitry Andric          << (Overload.first->getValueAsBit("IsConv")) << ", "
600480093f4SDimitry Andric          << FunctionExtensionIndex[ExtName] << ", "
601*fe6060f1SDimitry Andric          << EncodeVersions(MinVersion, MaxVersion) << " },\n";
602a7dea167SDimitry Andric       Index++;
6030b57cec5SDimitry Andric     }
6040b57cec5SDimitry Andric   }
6050b57cec5SDimitry Andric   OS << "};\n\n";
6060b57cec5SDimitry Andric }
6070b57cec5SDimitry Andric 
608480093f4SDimitry Andric bool BuiltinNameEmitter::CanReuseSignature(
609480093f4SDimitry Andric     BuiltinIndexListTy *Candidate,
610480093f4SDimitry Andric     std::vector<std::pair<const Record *, unsigned>> &SignatureList) {
611480093f4SDimitry Andric   assert(Candidate->size() == SignatureList.size() &&
612480093f4SDimitry Andric          "signature lists should have the same size");
613480093f4SDimitry Andric 
614480093f4SDimitry Andric   auto &CandidateSigs =
615480093f4SDimitry Andric       SignatureListMap.find(Candidate)->second.Signatures;
616480093f4SDimitry Andric   for (unsigned Index = 0; Index < Candidate->size(); Index++) {
617480093f4SDimitry Andric     const Record *Rec = SignatureList[Index].first;
618480093f4SDimitry Andric     const Record *Rec2 = CandidateSigs[Index].first;
619480093f4SDimitry Andric     if (Rec->getValueAsBit("IsPure") == Rec2->getValueAsBit("IsPure") &&
620480093f4SDimitry Andric         Rec->getValueAsBit("IsConst") == Rec2->getValueAsBit("IsConst") &&
621480093f4SDimitry Andric         Rec->getValueAsBit("IsConv") == Rec2->getValueAsBit("IsConv") &&
622480093f4SDimitry Andric         Rec->getValueAsDef("MinVersion")->getValueAsInt("ID") ==
623480093f4SDimitry Andric             Rec2->getValueAsDef("MinVersion")->getValueAsInt("ID") &&
624480093f4SDimitry Andric         Rec->getValueAsDef("MaxVersion")->getValueAsInt("ID") ==
625480093f4SDimitry Andric             Rec2->getValueAsDef("MaxVersion")->getValueAsInt("ID") &&
626480093f4SDimitry Andric         Rec->getValueAsDef("Extension")->getName() ==
627480093f4SDimitry Andric             Rec2->getValueAsDef("Extension")->getName()) {
628480093f4SDimitry Andric       return true;
629480093f4SDimitry Andric     }
630480093f4SDimitry Andric   }
631480093f4SDimitry Andric   return false;
632480093f4SDimitry Andric }
633480093f4SDimitry Andric 
634480093f4SDimitry Andric void BuiltinNameEmitter::GroupBySignature() {
635480093f4SDimitry Andric   // List of signatures known to be emitted.
636480093f4SDimitry Andric   std::vector<BuiltinIndexListTy *> KnownSignatures;
637480093f4SDimitry Andric 
638480093f4SDimitry Andric   for (auto &Fct : FctOverloadMap) {
639480093f4SDimitry Andric     bool FoundReusableSig = false;
640480093f4SDimitry Andric 
641480093f4SDimitry Andric     // Gather all signatures for the current function.
642480093f4SDimitry Andric     auto *CurSignatureList = new BuiltinIndexListTy();
643480093f4SDimitry Andric     for (const auto &Signature : Fct.second) {
644480093f4SDimitry Andric       CurSignatureList->push_back(Signature.second);
645480093f4SDimitry Andric     }
646480093f4SDimitry Andric     // Sort the list to facilitate future comparisons.
6475ffd83dbSDimitry Andric     llvm::sort(*CurSignatureList);
648480093f4SDimitry Andric 
649480093f4SDimitry Andric     // Check if we have already seen another function with the same list of
650480093f4SDimitry Andric     // signatures.  If so, just add the name of the function.
651480093f4SDimitry Andric     for (auto *Candidate : KnownSignatures) {
652480093f4SDimitry Andric       if (Candidate->size() == CurSignatureList->size() &&
653480093f4SDimitry Andric           *Candidate == *CurSignatureList) {
654480093f4SDimitry Andric         if (CanReuseSignature(Candidate, Fct.second)) {
655480093f4SDimitry Andric           SignatureListMap.find(Candidate)->second.Names.push_back(Fct.first);
656480093f4SDimitry Andric           FoundReusableSig = true;
657480093f4SDimitry Andric         }
658480093f4SDimitry Andric       }
659480093f4SDimitry Andric     }
660480093f4SDimitry Andric 
661480093f4SDimitry Andric     if (FoundReusableSig) {
662480093f4SDimitry Andric       delete CurSignatureList;
663480093f4SDimitry Andric     } else {
664480093f4SDimitry Andric       // Add a new entry.
665480093f4SDimitry Andric       SignatureListMap[CurSignatureList] = {
666480093f4SDimitry Andric           SmallVector<StringRef, 4>(1, Fct.first), Fct.second};
667480093f4SDimitry Andric       KnownSignatures.push_back(CurSignatureList);
668480093f4SDimitry Andric     }
669480093f4SDimitry Andric   }
670480093f4SDimitry Andric 
671480093f4SDimitry Andric   for (auto *I : KnownSignatures) {
672480093f4SDimitry Andric     delete I;
673480093f4SDimitry Andric   }
674480093f4SDimitry Andric }
675480093f4SDimitry Andric 
6760b57cec5SDimitry Andric void BuiltinNameEmitter::EmitStringMatcher() {
6770b57cec5SDimitry Andric   std::vector<StringMatcher::StringPair> ValidBuiltins;
6780b57cec5SDimitry Andric   unsigned CumulativeIndex = 1;
679480093f4SDimitry Andric 
680480093f4SDimitry Andric   for (const auto &SLM : SignatureListMap) {
681480093f4SDimitry Andric     const auto &Ovl = SLM.second.Signatures;
682480093f4SDimitry Andric 
683480093f4SDimitry Andric     // A single signature list may be used by different builtins.  Return the
684480093f4SDimitry Andric     // same <index, length> pair for each of those builtins.
685480093f4SDimitry Andric     for (const auto &FctName : SLM.second.Names) {
6860b57cec5SDimitry Andric       std::string RetStmt;
6870b57cec5SDimitry Andric       raw_string_ostream SS(RetStmt);
688480093f4SDimitry Andric       SS << "return std::make_pair(" << CumulativeIndex << ", " << Ovl.size()
6890b57cec5SDimitry Andric          << ");";
6900b57cec5SDimitry Andric       SS.flush();
6915ffd83dbSDimitry Andric       ValidBuiltins.push_back(
6925ffd83dbSDimitry Andric           StringMatcher::StringPair(std::string(FctName), RetStmt));
693480093f4SDimitry Andric     }
694480093f4SDimitry Andric     CumulativeIndex += Ovl.size();
6950b57cec5SDimitry Andric   }
6960b57cec5SDimitry Andric 
6970b57cec5SDimitry Andric   OS << R"(
698a7dea167SDimitry Andric // Find out whether a string matches an existing OpenCL builtin function name.
699a7dea167SDimitry Andric // Returns: A pair <0, 0> if no name matches.
700a7dea167SDimitry Andric //          A pair <Index, Len> indexing the BuiltinTable if the name is
701a7dea167SDimitry Andric //          matching an OpenCL builtin function.
702a7dea167SDimitry Andric static std::pair<unsigned, unsigned> isOpenCLBuiltin(llvm::StringRef Name) {
7030b57cec5SDimitry Andric 
7040b57cec5SDimitry Andric )";
7050b57cec5SDimitry Andric 
706a7dea167SDimitry Andric   StringMatcher("Name", ValidBuiltins, OS).Emit(0, true);
7070b57cec5SDimitry Andric 
7080b57cec5SDimitry Andric   OS << "  return std::make_pair(0, 0);\n";
709a7dea167SDimitry Andric   OS << "} // isOpenCLBuiltin\n";
7100b57cec5SDimitry Andric }
7110b57cec5SDimitry Andric 
7120b57cec5SDimitry Andric void BuiltinNameEmitter::EmitQualTypeFinder() {
7130b57cec5SDimitry Andric   OS << R"(
7140b57cec5SDimitry Andric 
715*fe6060f1SDimitry Andric static QualType getOpenCLEnumType(Sema &S, llvm::StringRef Name);
716*fe6060f1SDimitry Andric static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name);
717*fe6060f1SDimitry Andric 
718a7dea167SDimitry Andric // Convert an OpenCLTypeStruct type to a list of QualTypes.
719a7dea167SDimitry Andric // Generic types represent multiple types and vector sizes, thus a vector
720a7dea167SDimitry Andric // is returned. The conversion is done in two steps:
721a7dea167SDimitry Andric // Step 1: A switch statement fills a vector with scalar base types for the
722a7dea167SDimitry Andric //         Cartesian product of (vector sizes) x (types) for generic types,
723a7dea167SDimitry Andric //         or a single scalar type for non generic types.
724a7dea167SDimitry Andric // Step 2: Qualifiers and other type properties such as vector size are
725a7dea167SDimitry Andric //         applied.
726*fe6060f1SDimitry Andric static void OCL2Qual(Sema &S, const OpenCLTypeStruct &Ty,
727a7dea167SDimitry Andric                      llvm::SmallVectorImpl<QualType> &QT) {
728*fe6060f1SDimitry Andric   ASTContext &Context = S.Context;
729a7dea167SDimitry Andric   // Number of scalar types in the GenType.
730a7dea167SDimitry Andric   unsigned GenTypeNumTypes;
731a7dea167SDimitry Andric   // Pointer to the list of vector sizes for the GenType.
732a7dea167SDimitry Andric   llvm::ArrayRef<unsigned> GenVectorSizes;
7330b57cec5SDimitry Andric )";
7340b57cec5SDimitry Andric 
735a7dea167SDimitry Andric   // Generate list of vector sizes for each generic type.
736a7dea167SDimitry Andric   for (const auto *VectList : Records.getAllDerivedDefinitions("IntList")) {
737a7dea167SDimitry Andric     OS << "  constexpr unsigned List"
738a7dea167SDimitry Andric        << VectList->getValueAsString("Name") << "[] = {";
739a7dea167SDimitry Andric     for (const auto V : VectList->getValueAsListOfInts("List")) {
740a7dea167SDimitry Andric       OS << V << ", ";
741a7dea167SDimitry Andric     }
742a7dea167SDimitry Andric     OS << "};\n";
743a7dea167SDimitry Andric   }
744a7dea167SDimitry Andric 
745a7dea167SDimitry Andric   // Step 1.
746a7dea167SDimitry Andric   // Start of switch statement over all types.
747a7dea167SDimitry Andric   OS << "\n  switch (Ty.ID) {\n";
748a7dea167SDimitry Andric 
749a7dea167SDimitry Andric   // Switch cases for image types (Image2d, Image3d, ...)
750a7dea167SDimitry Andric   std::vector<Record *> ImageTypes =
751a7dea167SDimitry Andric       Records.getAllDerivedDefinitions("ImageType");
752a7dea167SDimitry Andric 
753a7dea167SDimitry Andric   // Map an image type name to its 3 access-qualified types (RO, WO, RW).
754*fe6060f1SDimitry Andric   StringMap<SmallVector<Record *, 3>> ImageTypesMap;
755a7dea167SDimitry Andric   for (auto *IT : ImageTypes) {
756a7dea167SDimitry Andric     auto Entry = ImageTypesMap.find(IT->getValueAsString("Name"));
757a7dea167SDimitry Andric     if (Entry == ImageTypesMap.end()) {
758a7dea167SDimitry Andric       SmallVector<Record *, 3> ImageList;
759a7dea167SDimitry Andric       ImageList.push_back(IT);
760a7dea167SDimitry Andric       ImageTypesMap.insert(
761a7dea167SDimitry Andric           std::make_pair(IT->getValueAsString("Name"), ImageList));
762a7dea167SDimitry Andric     } else {
763a7dea167SDimitry Andric       Entry->second.push_back(IT);
764a7dea167SDimitry Andric     }
765a7dea167SDimitry Andric   }
766a7dea167SDimitry Andric 
767a7dea167SDimitry Andric   // Emit the cases for the image types.  For an image type name, there are 3
768a7dea167SDimitry Andric   // corresponding QualTypes ("RO", "WO", "RW").  The "AccessQualifier" field
769a7dea167SDimitry Andric   // tells which one is needed.  Emit a switch statement that puts the
770a7dea167SDimitry Andric   // corresponding QualType into "QT".
771a7dea167SDimitry Andric   for (const auto &ITE : ImageTypesMap) {
772*fe6060f1SDimitry Andric     OS << "    case OCLT_" << ITE.getKey() << ":\n"
773a7dea167SDimitry Andric        << "      switch (Ty.AccessQualifier) {\n"
774a7dea167SDimitry Andric        << "        case OCLAQ_None:\n"
775a7dea167SDimitry Andric        << "          llvm_unreachable(\"Image without access qualifier\");\n";
776*fe6060f1SDimitry Andric     for (const auto &Image : ITE.getValue()) {
777a7dea167SDimitry Andric       OS << StringSwitch<const char *>(
778a7dea167SDimitry Andric                 Image->getValueAsString("AccessQualifier"))
779a7dea167SDimitry Andric                 .Case("RO", "        case OCLAQ_ReadOnly:\n")
780a7dea167SDimitry Andric                 .Case("WO", "        case OCLAQ_WriteOnly:\n")
781a7dea167SDimitry Andric                 .Case("RW", "        case OCLAQ_ReadWrite:\n")
782*fe6060f1SDimitry Andric          << "          QT.push_back("
783*fe6060f1SDimitry Andric          << Image->getValueAsDef("QTExpr")->getValueAsString("TypeExpr")
784*fe6060f1SDimitry Andric          << ");\n"
785a7dea167SDimitry Andric          << "          break;\n";
786a7dea167SDimitry Andric     }
787a7dea167SDimitry Andric     OS << "      }\n"
788a7dea167SDimitry Andric        << "      break;\n";
789a7dea167SDimitry Andric   }
790a7dea167SDimitry Andric 
791a7dea167SDimitry Andric   // Switch cases for generic types.
792a7dea167SDimitry Andric   for (const auto *GenType : Records.getAllDerivedDefinitions("GenericType")) {
793*fe6060f1SDimitry Andric     OS << "    case OCLT_" << GenType->getValueAsString("Name") << ": {\n";
794a7dea167SDimitry Andric 
795a7dea167SDimitry Andric     // Build the Cartesian product of (vector sizes) x (types).  Only insert
796a7dea167SDimitry Andric     // the plain scalar types for now; other type information such as vector
797a7dea167SDimitry Andric     // size and type qualifiers will be added after the switch statement.
798*fe6060f1SDimitry Andric     std::vector<Record *> BaseTypes =
799*fe6060f1SDimitry Andric         GenType->getValueAsDef("TypeList")->getValueAsListOfDefs("List");
800*fe6060f1SDimitry Andric 
801*fe6060f1SDimitry Andric     // Collect all QualTypes for a single vector size into TypeList.
802*fe6060f1SDimitry Andric     OS << "      SmallVector<QualType, " << BaseTypes.size() << "> TypeList;\n";
803*fe6060f1SDimitry Andric     for (const auto *T : BaseTypes) {
804*fe6060f1SDimitry Andric       StringRef Ext =
805*fe6060f1SDimitry Andric           T->getValueAsDef("Extension")->getValueAsString("ExtName");
806*fe6060f1SDimitry Andric       if (!Ext.empty()) {
807*fe6060f1SDimitry Andric         OS << "      if (S.getPreprocessor().isMacroDefined(\"" << Ext
808*fe6060f1SDimitry Andric            << "\")) {\n  ";
809*fe6060f1SDimitry Andric       }
810*fe6060f1SDimitry Andric       OS << "      TypeList.push_back("
811*fe6060f1SDimitry Andric          << T->getValueAsDef("QTExpr")->getValueAsString("TypeExpr") << ");\n";
812*fe6060f1SDimitry Andric       if (!Ext.empty()) {
813*fe6060f1SDimitry Andric         OS << "      }\n";
814a7dea167SDimitry Andric       }
815a7dea167SDimitry Andric     }
816*fe6060f1SDimitry Andric     OS << "      GenTypeNumTypes = TypeList.size();\n";
817*fe6060f1SDimitry Andric 
818*fe6060f1SDimitry Andric     // Duplicate the TypeList for every vector size.
819*fe6060f1SDimitry Andric     std::vector<int64_t> VectorList =
820*fe6060f1SDimitry Andric         GenType->getValueAsDef("VectorList")->getValueAsListOfInts("List");
821*fe6060f1SDimitry Andric     OS << "      QT.reserve(" << VectorList.size() * BaseTypes.size() << ");\n"
822*fe6060f1SDimitry Andric        << "      for (unsigned I = 0; I < " << VectorList.size() << "; I++) {\n"
823*fe6060f1SDimitry Andric        << "        QT.append(TypeList);\n"
824*fe6060f1SDimitry Andric        << "      }\n";
825*fe6060f1SDimitry Andric 
826a7dea167SDimitry Andric     // GenVectorSizes is the list of vector sizes for this GenType.
827a7dea167SDimitry Andric     OS << "      GenVectorSizes = List"
828a7dea167SDimitry Andric        << GenType->getValueAsDef("VectorList")->getValueAsString("Name")
829*fe6060f1SDimitry Andric        << ";\n"
830*fe6060f1SDimitry Andric        << "      break;\n"
831*fe6060f1SDimitry Andric        << "    }\n";
832a7dea167SDimitry Andric   }
833a7dea167SDimitry Andric 
834a7dea167SDimitry Andric   // Switch cases for non generic, non image types (int, int4, float, ...).
835a7dea167SDimitry Andric   // Only insert the plain scalar type; vector information and type qualifiers
836a7dea167SDimitry Andric   // are added in step 2.
8370b57cec5SDimitry Andric   std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
8380b57cec5SDimitry Andric   StringMap<bool> TypesSeen;
8390b57cec5SDimitry Andric 
8400b57cec5SDimitry Andric   for (const auto *T : Types) {
841a7dea167SDimitry Andric     // Check this is not an image type
842a7dea167SDimitry Andric     if (ImageTypesMap.find(T->getValueAsString("Name")) != ImageTypesMap.end())
843a7dea167SDimitry Andric       continue;
8440b57cec5SDimitry Andric     // Check we have not seen this Type
8450b57cec5SDimitry Andric     if (TypesSeen.find(T->getValueAsString("Name")) != TypesSeen.end())
8460b57cec5SDimitry Andric       continue;
8470b57cec5SDimitry Andric     TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true));
8480b57cec5SDimitry Andric 
8490b57cec5SDimitry Andric     // Check the Type does not have an "abstract" QualType
850*fe6060f1SDimitry Andric     auto QT = T->getValueAsDef("QTExpr");
851a7dea167SDimitry Andric     if (QT->getValueAsBit("IsAbstract") == 1)
8520b57cec5SDimitry Andric       continue;
853a7dea167SDimitry Andric     // Emit the cases for non generic, non image types.
8540b57cec5SDimitry Andric     OS << "    case OCLT_" << T->getValueAsString("Name") << ":\n";
855*fe6060f1SDimitry Andric 
856*fe6060f1SDimitry Andric     StringRef Ext = T->getValueAsDef("Extension")->getValueAsString("ExtName");
857*fe6060f1SDimitry Andric     // If this type depends on an extension, ensure the extension macro is
858*fe6060f1SDimitry Andric     // defined.
859*fe6060f1SDimitry Andric     if (!Ext.empty()) {
860*fe6060f1SDimitry Andric       OS << "      if (S.getPreprocessor().isMacroDefined(\"" << Ext
861*fe6060f1SDimitry Andric          << "\")) {\n  ";
862*fe6060f1SDimitry Andric     }
863*fe6060f1SDimitry Andric     OS << "      QT.push_back(" << QT->getValueAsString("TypeExpr") << ");\n";
864*fe6060f1SDimitry Andric     if (!Ext.empty()) {
865*fe6060f1SDimitry Andric       OS << "      }\n";
866*fe6060f1SDimitry Andric     }
8670b57cec5SDimitry Andric     OS << "      break;\n";
8680b57cec5SDimitry Andric   }
8690b57cec5SDimitry Andric 
870a7dea167SDimitry Andric   // End of switch statement.
871480093f4SDimitry Andric   OS << "  } // end of switch (Ty.ID)\n\n";
872a7dea167SDimitry Andric 
873a7dea167SDimitry Andric   // Step 2.
874a7dea167SDimitry Andric   // Add ExtVector types if this was a generic type, as the switch statement
875a7dea167SDimitry Andric   // above only populated the list with scalar types.  This completes the
876a7dea167SDimitry Andric   // construction of the Cartesian product of (vector sizes) x (types).
877a7dea167SDimitry Andric   OS << "  // Construct the different vector types for each generic type.\n";
878a7dea167SDimitry Andric   OS << "  if (Ty.ID >= " << TypeList.size() << ") {";
8790b57cec5SDimitry Andric   OS << R"(
880a7dea167SDimitry Andric     for (unsigned I = 0; I < QT.size(); I++) {
881a7dea167SDimitry Andric       // For scalars, size is 1.
882a7dea167SDimitry Andric       if (GenVectorSizes[I / GenTypeNumTypes] != 1) {
883a7dea167SDimitry Andric         QT[I] = Context.getExtVectorType(QT[I],
884a7dea167SDimitry Andric                           GenVectorSizes[I / GenTypeNumTypes]);
8850b57cec5SDimitry Andric       }
886a7dea167SDimitry Andric     }
8870b57cec5SDimitry Andric   }
8880b57cec5SDimitry Andric )";
889a7dea167SDimitry Andric 
890a7dea167SDimitry Andric   // Assign the right attributes to the types (e.g. vector size).
891a7dea167SDimitry Andric   OS << R"(
892a7dea167SDimitry Andric   // Set vector size for non-generic vector types.
893a7dea167SDimitry Andric   if (Ty.VectorWidth > 1) {
894a7dea167SDimitry Andric     for (unsigned Index = 0; Index < QT.size(); Index++) {
895a7dea167SDimitry Andric       QT[Index] = Context.getExtVectorType(QT[Index], Ty.VectorWidth);
896a7dea167SDimitry Andric     }
8970b57cec5SDimitry Andric   }
8980b57cec5SDimitry Andric 
899a7dea167SDimitry Andric   if (Ty.IsVolatile != 0) {
900a7dea167SDimitry Andric     for (unsigned Index = 0; Index < QT.size(); Index++) {
901a7dea167SDimitry Andric       QT[Index] = Context.getVolatileType(QT[Index]);
902a7dea167SDimitry Andric     }
903a7dea167SDimitry Andric   }
9040b57cec5SDimitry Andric 
905a7dea167SDimitry Andric   if (Ty.IsConst != 0) {
906a7dea167SDimitry Andric     for (unsigned Index = 0; Index < QT.size(); Index++) {
907a7dea167SDimitry Andric       QT[Index] = Context.getConstType(QT[Index]);
908a7dea167SDimitry Andric     }
909a7dea167SDimitry Andric   }
910a7dea167SDimitry Andric 
911a7dea167SDimitry Andric   // Transform the type to a pointer as the last step, if necessary.
912a7dea167SDimitry Andric   // Builtin functions only have pointers on [const|volatile], no
913a7dea167SDimitry Andric   // [const|volatile] pointers, so this is ok to do it as a last step.
914a7dea167SDimitry Andric   if (Ty.IsPointer != 0) {
915a7dea167SDimitry Andric     for (unsigned Index = 0; Index < QT.size(); Index++) {
916a7dea167SDimitry Andric       QT[Index] = Context.getAddrSpaceQualType(QT[Index], Ty.AS);
917a7dea167SDimitry Andric       QT[Index] = Context.getPointerType(QT[Index]);
918a7dea167SDimitry Andric     }
919a7dea167SDimitry Andric   }
920a7dea167SDimitry Andric )";
921a7dea167SDimitry Andric 
922a7dea167SDimitry Andric   // End of the "OCL2Qual" function.
923a7dea167SDimitry Andric   OS << "\n} // OCL2Qual\n";
924a7dea167SDimitry Andric }
925a7dea167SDimitry Andric 
926*fe6060f1SDimitry Andric std::string OpenCLBuiltinTestEmitter::getTypeString(const Record *Type,
927*fe6060f1SDimitry Andric                                                     TypeFlags Flags,
928*fe6060f1SDimitry Andric                                                     int VectorSize) const {
929*fe6060f1SDimitry Andric   std::string S;
930*fe6060f1SDimitry Andric   if (Type->getValueAsBit("IsConst") || Flags.IsConst) {
931*fe6060f1SDimitry Andric     S += "const ";
932*fe6060f1SDimitry Andric   }
933*fe6060f1SDimitry Andric   if (Type->getValueAsBit("IsVolatile") || Flags.IsVolatile) {
934*fe6060f1SDimitry Andric     S += "volatile ";
935*fe6060f1SDimitry Andric   }
936*fe6060f1SDimitry Andric 
937*fe6060f1SDimitry Andric   auto PrintAddrSpace = [&S](StringRef AddrSpace) {
938*fe6060f1SDimitry Andric     S += StringSwitch<const char *>(AddrSpace)
939*fe6060f1SDimitry Andric              .Case("clang::LangAS::opencl_private", "__private")
940*fe6060f1SDimitry Andric              .Case("clang::LangAS::opencl_global", "__global")
941*fe6060f1SDimitry Andric              .Case("clang::LangAS::opencl_constant", "__constant")
942*fe6060f1SDimitry Andric              .Case("clang::LangAS::opencl_local", "__local")
943*fe6060f1SDimitry Andric              .Case("clang::LangAS::opencl_generic", "__generic")
944*fe6060f1SDimitry Andric              .Default("__private");
945*fe6060f1SDimitry Andric     S += " ";
946*fe6060f1SDimitry Andric   };
947*fe6060f1SDimitry Andric   if (Flags.IsPointer) {
948*fe6060f1SDimitry Andric     PrintAddrSpace(Flags.AddrSpace);
949*fe6060f1SDimitry Andric   } else if (Type->getValueAsBit("IsPointer")) {
950*fe6060f1SDimitry Andric     PrintAddrSpace(Type->getValueAsString("AddrSpace"));
951*fe6060f1SDimitry Andric   }
952*fe6060f1SDimitry Andric 
953*fe6060f1SDimitry Andric   StringRef Acc = Type->getValueAsString("AccessQualifier");
954*fe6060f1SDimitry Andric   if (Acc != "") {
955*fe6060f1SDimitry Andric     S += StringSwitch<const char *>(Acc)
956*fe6060f1SDimitry Andric              .Case("RO", "__read_only ")
957*fe6060f1SDimitry Andric              .Case("WO", "__write_only ")
958*fe6060f1SDimitry Andric              .Case("RW", "__read_write ");
959*fe6060f1SDimitry Andric   }
960*fe6060f1SDimitry Andric 
961*fe6060f1SDimitry Andric   S += Type->getValueAsString("Name").str();
962*fe6060f1SDimitry Andric   if (VectorSize > 1) {
963*fe6060f1SDimitry Andric     S += std::to_string(VectorSize);
964*fe6060f1SDimitry Andric   }
965*fe6060f1SDimitry Andric 
966*fe6060f1SDimitry Andric   if (Type->getValueAsBit("IsPointer") || Flags.IsPointer) {
967*fe6060f1SDimitry Andric     S += " *";
968*fe6060f1SDimitry Andric   }
969*fe6060f1SDimitry Andric 
970*fe6060f1SDimitry Andric   return S;
971*fe6060f1SDimitry Andric }
972*fe6060f1SDimitry Andric 
973*fe6060f1SDimitry Andric void OpenCLBuiltinTestEmitter::getTypeLists(
974*fe6060f1SDimitry Andric     Record *Type, TypeFlags &Flags, std::vector<Record *> &TypeList,
975*fe6060f1SDimitry Andric     std::vector<int64_t> &VectorList) const {
976*fe6060f1SDimitry Andric   bool isGenType = Type->isSubClassOf("GenericType");
977*fe6060f1SDimitry Andric   if (isGenType) {
978*fe6060f1SDimitry Andric     TypeList = Type->getValueAsDef("TypeList")->getValueAsListOfDefs("List");
979*fe6060f1SDimitry Andric     VectorList =
980*fe6060f1SDimitry Andric         Type->getValueAsDef("VectorList")->getValueAsListOfInts("List");
981*fe6060f1SDimitry Andric     return;
982*fe6060f1SDimitry Andric   }
983*fe6060f1SDimitry Andric 
984*fe6060f1SDimitry Andric   if (Type->isSubClassOf("PointerType") || Type->isSubClassOf("ConstType") ||
985*fe6060f1SDimitry Andric       Type->isSubClassOf("VolatileType")) {
986*fe6060f1SDimitry Andric     StringRef SubTypeName = Type->getValueAsString("Name");
987*fe6060f1SDimitry Andric     Record *PossibleGenType = Records.getDef(SubTypeName);
988*fe6060f1SDimitry Andric     if (PossibleGenType && PossibleGenType->isSubClassOf("GenericType")) {
989*fe6060f1SDimitry Andric       // When PointerType, ConstType, or VolatileType is applied to a
990*fe6060f1SDimitry Andric       // GenericType, the flags need to be taken from the subtype, not from the
991*fe6060f1SDimitry Andric       // GenericType.
992*fe6060f1SDimitry Andric       Flags.IsPointer = Type->getValueAsBit("IsPointer");
993*fe6060f1SDimitry Andric       Flags.IsConst = Type->getValueAsBit("IsConst");
994*fe6060f1SDimitry Andric       Flags.IsVolatile = Type->getValueAsBit("IsVolatile");
995*fe6060f1SDimitry Andric       Flags.AddrSpace = Type->getValueAsString("AddrSpace");
996*fe6060f1SDimitry Andric       getTypeLists(PossibleGenType, Flags, TypeList, VectorList);
997*fe6060f1SDimitry Andric       return;
998*fe6060f1SDimitry Andric     }
999*fe6060f1SDimitry Andric   }
1000*fe6060f1SDimitry Andric 
1001*fe6060f1SDimitry Andric   // Not a GenericType, so just insert the single type.
1002*fe6060f1SDimitry Andric   TypeList.push_back(Type);
1003*fe6060f1SDimitry Andric   VectorList.push_back(Type->getValueAsInt("VecWidth"));
1004*fe6060f1SDimitry Andric }
1005*fe6060f1SDimitry Andric 
1006*fe6060f1SDimitry Andric void OpenCLBuiltinTestEmitter::expandTypesInSignature(
1007*fe6060f1SDimitry Andric     const std::vector<Record *> &Signature,
1008*fe6060f1SDimitry Andric     SmallVectorImpl<SmallVector<std::string, 2>> &Types) {
1009*fe6060f1SDimitry Andric   // Find out if there are any GenTypes in this signature, and if so, calculate
1010*fe6060f1SDimitry Andric   // into how many signatures they will expand.
1011*fe6060f1SDimitry Andric   unsigned NumSignatures = 1;
1012*fe6060f1SDimitry Andric   SmallVector<SmallVector<std::string, 4>, 4> ExpandedGenTypes;
1013*fe6060f1SDimitry Andric   for (const auto &Arg : Signature) {
1014*fe6060f1SDimitry Andric     SmallVector<std::string, 4> ExpandedArg;
1015*fe6060f1SDimitry Andric     std::vector<Record *> TypeList;
1016*fe6060f1SDimitry Andric     std::vector<int64_t> VectorList;
1017*fe6060f1SDimitry Andric     TypeFlags Flags;
1018*fe6060f1SDimitry Andric 
1019*fe6060f1SDimitry Andric     getTypeLists(Arg, Flags, TypeList, VectorList);
1020*fe6060f1SDimitry Andric 
1021*fe6060f1SDimitry Andric     // Insert the Cartesian product of the types and vector sizes.
1022*fe6060f1SDimitry Andric     for (const auto &Vector : VectorList) {
1023*fe6060f1SDimitry Andric       for (const auto &Type : TypeList) {
1024*fe6060f1SDimitry Andric         ExpandedArg.push_back(getTypeString(Type, Flags, Vector));
1025*fe6060f1SDimitry Andric       }
1026*fe6060f1SDimitry Andric     }
1027*fe6060f1SDimitry Andric     NumSignatures = std::max<unsigned>(NumSignatures, ExpandedArg.size());
1028*fe6060f1SDimitry Andric     ExpandedGenTypes.push_back(ExpandedArg);
1029*fe6060f1SDimitry Andric   }
1030*fe6060f1SDimitry Andric 
1031*fe6060f1SDimitry Andric   // Now the total number of signatures is known.  Populate the return list with
1032*fe6060f1SDimitry Andric   // all signatures.
1033*fe6060f1SDimitry Andric   for (unsigned I = 0; I < NumSignatures; I++) {
1034*fe6060f1SDimitry Andric     SmallVector<std::string, 2> Args;
1035*fe6060f1SDimitry Andric 
1036*fe6060f1SDimitry Andric     // Process a single signature.
1037*fe6060f1SDimitry Andric     for (unsigned ArgNum = 0; ArgNum < Signature.size(); ArgNum++) {
1038*fe6060f1SDimitry Andric       // For differently-sized GenTypes in a parameter list, the smaller
1039*fe6060f1SDimitry Andric       // GenTypes just repeat, so index modulo the number of expanded types.
1040*fe6060f1SDimitry Andric       size_t TypeIndex = I % ExpandedGenTypes[ArgNum].size();
1041*fe6060f1SDimitry Andric       Args.push_back(ExpandedGenTypes[ArgNum][TypeIndex]);
1042*fe6060f1SDimitry Andric     }
1043*fe6060f1SDimitry Andric     Types.push_back(Args);
1044*fe6060f1SDimitry Andric   }
1045*fe6060f1SDimitry Andric }
1046*fe6060f1SDimitry Andric 
1047*fe6060f1SDimitry Andric void OpenCLBuiltinTestEmitter::emit() {
1048*fe6060f1SDimitry Andric   emitSourceFileHeader("OpenCL Builtin exhaustive testing", OS);
1049*fe6060f1SDimitry Andric 
1050*fe6060f1SDimitry Andric   // Enable some extensions for testing.
1051*fe6060f1SDimitry Andric   OS << R"(
1052*fe6060f1SDimitry Andric #pragma OPENCL EXTENSION cl_khr_fp16 : enable
1053*fe6060f1SDimitry Andric #pragma OPENCL EXTENSION cl_khr_fp64 : enable
1054*fe6060f1SDimitry Andric #pragma OPENCL EXTENSION cl_khr_int64_base_atomics : enable
1055*fe6060f1SDimitry Andric #pragma OPENCL EXTENSION cl_khr_int64_extended_atomics : enable
1056*fe6060f1SDimitry Andric #pragma OPENCL EXTENSION cl_khr_gl_msaa_sharing : enable
1057*fe6060f1SDimitry Andric #pragma OPENCL EXTENSION cl_khr_mipmap_image_writes : enable
1058*fe6060f1SDimitry Andric #pragma OPENCL EXTENSION cl_khr_3d_image_writes : enable
1059*fe6060f1SDimitry Andric 
1060*fe6060f1SDimitry Andric )";
1061*fe6060f1SDimitry Andric 
1062*fe6060f1SDimitry Andric   // Ensure each test has a unique name by numbering them.
1063*fe6060f1SDimitry Andric   unsigned TestID = 0;
1064*fe6060f1SDimitry Andric 
1065*fe6060f1SDimitry Andric   // Iterate over all builtins.
1066*fe6060f1SDimitry Andric   std::vector<Record *> Builtins = Records.getAllDerivedDefinitions("Builtin");
1067*fe6060f1SDimitry Andric   for (const auto *B : Builtins) {
1068*fe6060f1SDimitry Andric     StringRef Name = B->getValueAsString("Name");
1069*fe6060f1SDimitry Andric 
1070*fe6060f1SDimitry Andric     SmallVector<SmallVector<std::string, 2>, 4> FTypes;
1071*fe6060f1SDimitry Andric     expandTypesInSignature(B->getValueAsListOfDefs("Signature"), FTypes);
1072*fe6060f1SDimitry Andric 
1073*fe6060f1SDimitry Andric     OS << "// Test " << Name << "\n";
1074*fe6060f1SDimitry Andric     std::string OptionalEndif;
1075*fe6060f1SDimitry Andric     StringRef Extensions =
1076*fe6060f1SDimitry Andric         B->getValueAsDef("Extension")->getValueAsString("ExtName");
1077*fe6060f1SDimitry Andric     if (!Extensions.empty()) {
1078*fe6060f1SDimitry Andric       OS << "#if";
1079*fe6060f1SDimitry Andric       OptionalEndif = "#endif // Extension\n";
1080*fe6060f1SDimitry Andric 
1081*fe6060f1SDimitry Andric       SmallVector<StringRef, 2> ExtVec;
1082*fe6060f1SDimitry Andric       Extensions.split(ExtVec, " ");
1083*fe6060f1SDimitry Andric       bool isFirst = true;
1084*fe6060f1SDimitry Andric       for (StringRef Ext : ExtVec) {
1085*fe6060f1SDimitry Andric         if (!isFirst) {
1086*fe6060f1SDimitry Andric           OS << " &&";
1087*fe6060f1SDimitry Andric         }
1088*fe6060f1SDimitry Andric         OS << " defined(" << Ext << ")";
1089*fe6060f1SDimitry Andric         isFirst = false;
1090*fe6060f1SDimitry Andric       }
1091*fe6060f1SDimitry Andric       OS << "\n";
1092*fe6060f1SDimitry Andric     }
1093*fe6060f1SDimitry Andric     auto PrintOpenCLVersion = [this](int Version) {
1094*fe6060f1SDimitry Andric       OS << "CL_VERSION_" << (Version / 100) << "_" << ((Version % 100) / 10);
1095*fe6060f1SDimitry Andric     };
1096*fe6060f1SDimitry Andric     int MinVersion = B->getValueAsDef("MinVersion")->getValueAsInt("ID");
1097*fe6060f1SDimitry Andric     if (MinVersion != 100) {
1098*fe6060f1SDimitry Andric       // OpenCL 1.0 is the default minimum version.
1099*fe6060f1SDimitry Andric       OS << "#if __OPENCL_C_VERSION__ >= ";
1100*fe6060f1SDimitry Andric       PrintOpenCLVersion(MinVersion);
1101*fe6060f1SDimitry Andric       OS << "\n";
1102*fe6060f1SDimitry Andric       OptionalEndif = "#endif // MinVersion\n" + OptionalEndif;
1103*fe6060f1SDimitry Andric     }
1104*fe6060f1SDimitry Andric     int MaxVersion = B->getValueAsDef("MaxVersion")->getValueAsInt("ID");
1105*fe6060f1SDimitry Andric     if (MaxVersion) {
1106*fe6060f1SDimitry Andric       OS << "#if __OPENCL_C_VERSION__ < ";
1107*fe6060f1SDimitry Andric       PrintOpenCLVersion(MaxVersion);
1108*fe6060f1SDimitry Andric       OS << "\n";
1109*fe6060f1SDimitry Andric       OptionalEndif = "#endif // MaxVersion\n" + OptionalEndif;
1110*fe6060f1SDimitry Andric     }
1111*fe6060f1SDimitry Andric     for (const auto &Signature : FTypes) {
1112*fe6060f1SDimitry Andric       // Emit function declaration.
1113*fe6060f1SDimitry Andric       OS << Signature[0] << " test" << TestID++ << "_" << Name << "(";
1114*fe6060f1SDimitry Andric       if (Signature.size() > 1) {
1115*fe6060f1SDimitry Andric         for (unsigned I = 1; I < Signature.size(); I++) {
1116*fe6060f1SDimitry Andric           if (I != 1)
1117*fe6060f1SDimitry Andric             OS << ", ";
1118*fe6060f1SDimitry Andric           OS << Signature[I] << " arg" << I;
1119*fe6060f1SDimitry Andric         }
1120*fe6060f1SDimitry Andric       }
1121*fe6060f1SDimitry Andric       OS << ") {\n";
1122*fe6060f1SDimitry Andric 
1123*fe6060f1SDimitry Andric       // Emit function body.
1124*fe6060f1SDimitry Andric       OS << "  ";
1125*fe6060f1SDimitry Andric       if (Signature[0] != "void") {
1126*fe6060f1SDimitry Andric         OS << "return ";
1127*fe6060f1SDimitry Andric       }
1128*fe6060f1SDimitry Andric       OS << Name << "(";
1129*fe6060f1SDimitry Andric       for (unsigned I = 1; I < Signature.size(); I++) {
1130*fe6060f1SDimitry Andric         if (I != 1)
1131*fe6060f1SDimitry Andric           OS << ", ";
1132*fe6060f1SDimitry Andric         OS << "arg" << I;
1133*fe6060f1SDimitry Andric       }
1134*fe6060f1SDimitry Andric       OS << ");\n";
1135*fe6060f1SDimitry Andric 
1136*fe6060f1SDimitry Andric       // End of function body.
1137*fe6060f1SDimitry Andric       OS << "}\n";
1138*fe6060f1SDimitry Andric     }
1139*fe6060f1SDimitry Andric     OS << OptionalEndif << "\n";
1140*fe6060f1SDimitry Andric   }
1141*fe6060f1SDimitry Andric }
1142*fe6060f1SDimitry Andric 
1143a7dea167SDimitry Andric void clang::EmitClangOpenCLBuiltins(RecordKeeper &Records, raw_ostream &OS) {
11440b57cec5SDimitry Andric   BuiltinNameEmitter NameChecker(Records, OS);
11450b57cec5SDimitry Andric   NameChecker.Emit();
11460b57cec5SDimitry Andric }
1147*fe6060f1SDimitry Andric 
1148*fe6060f1SDimitry Andric void clang::EmitClangOpenCLBuiltinTests(RecordKeeper &Records,
1149*fe6060f1SDimitry Andric                                         raw_ostream &OS) {
1150*fe6060f1SDimitry Andric   OpenCLBuiltinTestEmitter TestFileGenerator(Records, OS);
1151*fe6060f1SDimitry Andric   TestFileGenerator.emit();
1152*fe6060f1SDimitry Andric }
1153