1 //===- ClangOpenCLBuiltinEmitter.cpp - Generate Clang OpenCL Builtin handling
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
6 // See https://llvm.org/LICENSE.txt for license information.
7 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
8 //
9 //===----------------------------------------------------------------------===//
10 //
11 // This tablegen backend emits code for checking whether a function is an
12 // OpenCL builtin function. If so, all overloads of this function are
13 // added to the LookupResult. The generated include file is used by
14 // SemaLookup.cpp
15 //
16 // For a successful lookup of e.g. the "cos" builtin, isOpenCLBuiltin("cos")
17 // returns a pair <Index, Len>.
18 // BuiltinTable[Index] to BuiltinTable[Index + Len] contains the pairs
19 // <SigIndex, SigLen> of the overloads of "cos".
20 // SignatureTable[SigIndex] to SignatureTable[SigIndex + SigLen] contains
21 // one of the signatures of "cos". The SignatureTable entry can be
22 // referenced by other functions, e.g. "sin", to exploit the fact that
23 // many OpenCL builtins share the same signature.
24 //
25 // The file generated by this TableGen emitter contains the following:
26 //
27 //  * Structs and enums to represent types and function signatures.
28 //
29 //  * const char *FunctionExtensionTable[]
30 //    List of space-separated OpenCL extensions.  A builtin references an
31 //    entry in this table when the builtin requires a particular (set of)
32 //    extension(s) to be enabled.
33 //
34 //  * OpenCLTypeStruct TypeTable[]
35 //    Type information for return types and arguments.
36 //
37 //  * unsigned SignatureTable[]
38 //    A list of types representing function signatures.  Each entry is an index
39 //    into the above TypeTable.  Multiple entries following each other form a
40 //    signature, where the first entry is the return type and subsequent
41 //    entries are the argument types.
42 //
43 //  * OpenCLBuiltinStruct BuiltinTable[]
44 //    Each entry represents one overload of an OpenCL builtin function and
45 //    consists of an index into the SignatureTable and the number of arguments.
46 //
47 //  * std::pair<unsigned, unsigned> isOpenCLBuiltin(llvm::StringRef Name)
48 //    Find out whether a string matches an existing OpenCL builtin function
49 //    name and return an index into BuiltinTable and the number of overloads.
50 //
51 //  * void OCL2Qual(Sema&, OpenCLTypeStruct, std::vector<QualType>&)
52 //    Convert an OpenCLTypeStruct type to a list of QualType instances.
53 //    One OpenCLTypeStruct can represent multiple types, primarily when using
54 //    GenTypes.
55 //
56 //===----------------------------------------------------------------------===//
57 
58 #include "TableGenBackends.h"
59 #include "llvm/ADT/MapVector.h"
60 #include "llvm/ADT/STLExtras.h"
61 #include "llvm/ADT/SmallString.h"
62 #include "llvm/ADT/StringExtras.h"
63 #include "llvm/ADT/StringMap.h"
64 #include "llvm/ADT/StringRef.h"
65 #include "llvm/ADT/StringSwitch.h"
66 #include "llvm/Support/ErrorHandling.h"
67 #include "llvm/Support/raw_ostream.h"
68 #include "llvm/TableGen/Error.h"
69 #include "llvm/TableGen/Record.h"
70 #include "llvm/TableGen/StringMatcher.h"
71 #include "llvm/TableGen/TableGenBackend.h"
72 
73 using namespace llvm;
74 
75 namespace {
76 
77 // A list of signatures that are shared by one or more builtin functions.
78 struct BuiltinTableEntries {
79   SmallVector<StringRef, 4> Names;
80   std::vector<std::pair<const Record *, unsigned>> Signatures;
81 };
82 
83 class BuiltinNameEmitter {
84 public:
85   BuiltinNameEmitter(RecordKeeper &Records, raw_ostream &OS)
86       : Records(Records), OS(OS) {}
87 
88   // Entrypoint to generate the functions and structures for checking
89   // whether a function is an OpenCL builtin function.
90   void Emit();
91 
92 private:
93   // A list of indices into the builtin function table.
94   using BuiltinIndexListTy = SmallVector<unsigned, 11>;
95 
96   // Contains OpenCL builtin functions and related information, stored as
97   // Record instances. They are coming from the associated TableGen file.
98   RecordKeeper &Records;
99 
100   // The output file.
101   raw_ostream &OS;
102 
103   // Helper function for BuiltinNameEmitter::EmitDeclarations.  Generate enum
104   // definitions in the Output string parameter, and save their Record instances
105   // in the List parameter.
106   // \param Types (in) List containing the Types to extract.
107   // \param TypesSeen (inout) List containing the Types already extracted.
108   // \param Output (out) String containing the enums to emit in the output file.
109   // \param List (out) List containing the extracted Types, except the Types in
110   //        TypesSeen.
111   void ExtractEnumTypes(std::vector<Record *> &Types,
112                         StringMap<bool> &TypesSeen, std::string &Output,
113                         std::vector<const Record *> &List);
114 
115   // Emit the enum or struct used in the generated file.
116   // Populate the TypeList at the same time.
117   void EmitDeclarations();
118 
119   // Parse the Records generated by TableGen to populate the SignaturesList,
120   // FctOverloadMap and TypeMap.
121   void GetOverloads();
122 
123   // Compare two lists of signatures and check that e.g. the OpenCL version,
124   // function attributes, and extension are equal for each signature.
125   // \param Candidate (in) Entry in the SignatureListMap to check.
126   // \param SignatureList (in) List of signatures of the considered function.
127   // \returns true if the two lists of signatures are identical.
128   bool CanReuseSignature(
129       BuiltinIndexListTy *Candidate,
130       std::vector<std::pair<const Record *, unsigned>> &SignatureList);
131 
132   // Group functions with the same list of signatures by populating the
133   // SignatureListMap.
134   // Some builtin functions have the same list of signatures, for example the
135   // "sin" and "cos" functions. To save space in the BuiltinTable, the
136   // "isOpenCLBuiltin" function will have the same output for these two
137   // function names.
138   void GroupBySignature();
139 
140   // Emit the FunctionExtensionTable that lists all function extensions.
141   void EmitExtensionTable();
142 
143   // Emit the TypeTable containing all types used by OpenCL builtins.
144   void EmitTypeTable();
145 
146   // Emit the SignatureTable. This table contains all the possible signatures.
147   // A signature is stored as a list of indexes of the TypeTable.
148   // The first index references the return type (mandatory), and the followings
149   // reference its arguments.
150   // E.g.:
151   // 15, 2, 15 can represent a function with the signature:
152   // int func(float, int)
153   // The "int" type being at the index 15 in the TypeTable.
154   void EmitSignatureTable();
155 
156   // Emit the BuiltinTable table. This table contains all the overloads of
157   // each function, and is a struct OpenCLBuiltinDecl.
158   // E.g.:
159   // // 891 convert_float2_rtn
160   //   { 58, 2, 3, 100, 0 },
161   // This means that the signature of this convert_float2_rtn overload has
162   // 1 argument (+1 for the return type), stored at index 58 in
163   // the SignatureTable.  This prototype requires extension "3" in the
164   // FunctionExtensionTable.  The last two values represent the minimum (1.0)
165   // and maximum (0, meaning no max version) OpenCL version in which this
166   // overload is supported.
167   void EmitBuiltinTable();
168 
169   // Emit a StringMatcher function to check whether a function name is an
170   // OpenCL builtin function name.
171   void EmitStringMatcher();
172 
173   // Emit a function returning the clang QualType instance associated with
174   // the TableGen Record Type.
175   void EmitQualTypeFinder();
176 
177   // Contains a list of the available signatures, without the name of the
178   // function. Each pair consists of a signature and a cumulative index.
179   // E.g.:  <<float, float>, 0>,
180   //        <<float, int, int, 2>>,
181   //        <<float>, 5>,
182   //        ...
183   //        <<double, double>, 35>.
184   std::vector<std::pair<std::vector<Record *>, unsigned>> SignaturesList;
185 
186   // Map the name of a builtin function to its prototypes (instances of the
187   // TableGen "Builtin" class).
188   // Each prototype is registered as a pair of:
189   //   <pointer to the "Builtin" instance,
190   //    cumulative index of the associated signature in the SignaturesList>
191   // E.g.:  The function cos: (float cos(float), double cos(double), ...)
192   //        <"cos", <<ptrToPrototype0, 5>,
193   //                 <ptrToPrototype1, 35>,
194   //                 <ptrToPrototype2, 79>>
195   // ptrToPrototype1 has the following signature: <double, double>
196   MapVector<StringRef, std::vector<std::pair<const Record *, unsigned>>>
197       FctOverloadMap;
198 
199   // Contains the map of OpenCL types to their index in the TypeTable.
200   MapVector<const Record *, unsigned> TypeMap;
201 
202   // List of OpenCL function extensions mapping extension strings to
203   // an index into the FunctionExtensionTable.
204   StringMap<unsigned> FunctionExtensionIndex;
205 
206   // List of OpenCL type names in the same order as in enum OpenCLTypeID.
207   // This list does not contain generic types.
208   std::vector<const Record *> TypeList;
209 
210   // Same as TypeList, but for generic types only.
211   std::vector<const Record *> GenTypeList;
212 
213   // Map an ordered vector of signatures to their original Record instances,
214   // and to a list of function names that share these signatures.
215   //
216   // For example, suppose the "cos" and "sin" functions have only three
217   // signatures, and these signatures are at index Ix in the SignatureTable:
218   //          cos         |         sin         |  Signature    | Index
219   //  float   cos(float)  | float   sin(float)  |  Signature1   | I1
220   //  double  cos(double) | double  sin(double) |  Signature2   | I2
221   //  half    cos(half)   | half    sin(half)   |  Signature3   | I3
222   //
223   // Then we will create a mapping of the vector of signatures:
224   // SignatureListMap[<I1, I2, I3>] = <
225   //                  <"cos", "sin">,
226   //                  <Signature1, Signature2, Signature3>>
227   // The function "tan", having the same signatures, would be mapped to the
228   // same entry (<I1, I2, I3>).
229   MapVector<BuiltinIndexListTy *, BuiltinTableEntries> SignatureListMap;
230 };
231 } // namespace
232 
233 void BuiltinNameEmitter::Emit() {
234   emitSourceFileHeader("OpenCL Builtin handling", OS);
235 
236   OS << "#include \"llvm/ADT/StringRef.h\"\n";
237   OS << "using namespace clang;\n\n";
238 
239   // Emit enums and structs.
240   EmitDeclarations();
241 
242   // Parse the Records to populate the internal lists.
243   GetOverloads();
244   GroupBySignature();
245 
246   // Emit tables.
247   EmitExtensionTable();
248   EmitTypeTable();
249   EmitSignatureTable();
250   EmitBuiltinTable();
251 
252   // Emit functions.
253   EmitStringMatcher();
254   EmitQualTypeFinder();
255 }
256 
257 void BuiltinNameEmitter::ExtractEnumTypes(std::vector<Record *> &Types,
258                                           StringMap<bool> &TypesSeen,
259                                           std::string &Output,
260                                           std::vector<const Record *> &List) {
261   raw_string_ostream SS(Output);
262 
263   for (const auto *T : Types) {
264     if (TypesSeen.find(T->getValueAsString("Name")) == TypesSeen.end()) {
265       SS << "  OCLT_" + T->getValueAsString("Name") << ",\n";
266       // Save the type names in the same order as their enum value. Note that
267       // the Record can be a VectorType or something else, only the name is
268       // important.
269       List.push_back(T);
270       TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true));
271     }
272   }
273   SS.flush();
274 }
275 
276 void BuiltinNameEmitter::EmitDeclarations() {
277   // Enum of scalar type names (float, int, ...) and generic type sets.
278   OS << "enum OpenCLTypeID {\n";
279 
280   StringMap<bool> TypesSeen;
281   std::string GenTypeEnums;
282   std::string TypeEnums;
283 
284   // Extract generic types and non-generic types separately, to keep
285   // gentypes at the end of the enum which simplifies the special handling
286   // for gentypes in SemaLookup.
287   std::vector<Record *> GenTypes =
288       Records.getAllDerivedDefinitions("GenericType");
289   ExtractEnumTypes(GenTypes, TypesSeen, GenTypeEnums, GenTypeList);
290 
291   std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
292   ExtractEnumTypes(Types, TypesSeen, TypeEnums, TypeList);
293 
294   OS << TypeEnums;
295   OS << GenTypeEnums;
296   OS << "};\n";
297 
298   // Structure definitions.
299   OS << R"(
300 // Image access qualifier.
301 enum OpenCLAccessQual : unsigned char {
302   OCLAQ_None,
303   OCLAQ_ReadOnly,
304   OCLAQ_WriteOnly,
305   OCLAQ_ReadWrite
306 };
307 
308 // Represents a return type or argument type.
309 struct OpenCLTypeStruct {
310   // A type (e.g. float, int, ...).
311   const OpenCLTypeID ID;
312   // Vector size (if applicable; 0 for scalars and generic types).
313   const unsigned VectorWidth;
314   // 0 if the type is not a pointer.
315   const bool IsPointer : 1;
316   // 0 if the type is not const.
317   const bool IsConst : 1;
318   // 0 if the type is not volatile.
319   const bool IsVolatile : 1;
320   // Access qualifier.
321   const OpenCLAccessQual AccessQualifier;
322   // Address space of the pointer (if applicable).
323   const LangAS AS;
324 };
325 
326 // One overload of an OpenCL builtin function.
327 struct OpenCLBuiltinStruct {
328   // Index of the signature in the OpenCLTypeStruct table.
329   const unsigned SigTableIndex;
330   // Entries between index SigTableIndex and (SigTableIndex + NumTypes - 1) in
331   // the SignatureTable represent the complete signature.  The first type at
332   // index SigTableIndex is the return type.
333   const unsigned NumTypes;
334   // Function attribute __attribute__((pure))
335   const bool IsPure : 1;
336   // Function attribute __attribute__((const))
337   const bool IsConst : 1;
338   // Function attribute __attribute__((convergent))
339   const bool IsConv : 1;
340   // OpenCL extension(s) required for this overload.
341   const unsigned short Extension;
342   // First OpenCL version in which this overload was introduced (e.g. CL20).
343   const unsigned short MinVersion;
344   // First OpenCL version in which this overload was removed (e.g. CL20).
345   const unsigned short MaxVersion;
346 };
347 
348 )";
349 }
350 
351 // Verify that the combination of GenTypes in a signature is supported.
352 // To simplify the logic for creating overloads in SemaLookup, only allow
353 // a signature to contain different GenTypes if these GenTypes represent
354 // the same number of actual scalar or vector types.
355 //
356 // Exit with a fatal error if an unsupported construct is encountered.
357 static void VerifySignature(const std::vector<Record *> &Signature,
358                             const Record *BuiltinRec) {
359   unsigned GenTypeVecSizes = 1;
360   unsigned GenTypeTypes = 1;
361 
362   for (const auto *T : Signature) {
363     // Check all GenericType arguments in this signature.
364     if (T->isSubClassOf("GenericType")) {
365       // Check number of vector sizes.
366       unsigned NVecSizes =
367           T->getValueAsDef("VectorList")->getValueAsListOfInts("List").size();
368       if (NVecSizes != GenTypeVecSizes && NVecSizes != 1) {
369         if (GenTypeVecSizes > 1) {
370           // We already saw a gentype with a different number of vector sizes.
371           PrintFatalError(BuiltinRec->getLoc(),
372               "number of vector sizes should be equal or 1 for all gentypes "
373               "in a declaration");
374         }
375         GenTypeVecSizes = NVecSizes;
376       }
377 
378       // Check number of data types.
379       unsigned NTypes =
380           T->getValueAsDef("TypeList")->getValueAsListOfDefs("List").size();
381       if (NTypes != GenTypeTypes && NTypes != 1) {
382         if (GenTypeTypes > 1) {
383           // We already saw a gentype with a different number of types.
384           PrintFatalError(BuiltinRec->getLoc(),
385               "number of types should be equal or 1 for all gentypes "
386               "in a declaration");
387         }
388         GenTypeTypes = NTypes;
389       }
390     }
391   }
392 }
393 
394 void BuiltinNameEmitter::GetOverloads() {
395   // Populate the TypeMap.
396   std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
397   unsigned I = 0;
398   for (const auto &T : Types) {
399     TypeMap.insert(std::make_pair(T, I++));
400   }
401 
402   // Populate the SignaturesList and the FctOverloadMap.
403   unsigned CumulativeSignIndex = 0;
404   std::vector<Record *> Builtins = Records.getAllDerivedDefinitions("Builtin");
405   for (const auto *B : Builtins) {
406     StringRef BName = B->getValueAsString("Name");
407     if (FctOverloadMap.find(BName) == FctOverloadMap.end()) {
408       FctOverloadMap.insert(std::make_pair(
409           BName, std::vector<std::pair<const Record *, unsigned>>{}));
410     }
411 
412     auto Signature = B->getValueAsListOfDefs("Signature");
413     // Reuse signatures to avoid unnecessary duplicates.
414     auto it =
415         std::find_if(SignaturesList.begin(), SignaturesList.end(),
416                      [&](const std::pair<std::vector<Record *>, unsigned> &a) {
417                        return a.first == Signature;
418                      });
419     unsigned SignIndex;
420     if (it == SignaturesList.end()) {
421       VerifySignature(Signature, B);
422       SignaturesList.push_back(std::make_pair(Signature, CumulativeSignIndex));
423       SignIndex = CumulativeSignIndex;
424       CumulativeSignIndex += Signature.size();
425     } else {
426       SignIndex = it->second;
427     }
428     FctOverloadMap[BName].push_back(std::make_pair(B, SignIndex));
429   }
430 }
431 
432 void BuiltinNameEmitter::EmitExtensionTable() {
433   OS << "static const char *FunctionExtensionTable[] = {\n";
434   unsigned Index = 0;
435   std::vector<Record *> FuncExtensions =
436       Records.getAllDerivedDefinitions("FunctionExtension");
437 
438   for (const auto &FE : FuncExtensions) {
439     // Emit OpenCL extension table entry.
440     OS << "  // " << Index << ": " << FE->getName() << "\n"
441        << "  \"" << FE->getValueAsString("ExtName") << "\",\n";
442 
443     // Record index of this extension.
444     FunctionExtensionIndex[FE->getName()] = Index++;
445   }
446   OS << "};\n\n";
447 }
448 
449 void BuiltinNameEmitter::EmitTypeTable() {
450   OS << "static const OpenCLTypeStruct TypeTable[] = {\n";
451   for (const auto &T : TypeMap) {
452     const char *AccessQual =
453         StringSwitch<const char *>(T.first->getValueAsString("AccessQualifier"))
454             .Case("RO", "OCLAQ_ReadOnly")
455             .Case("WO", "OCLAQ_WriteOnly")
456             .Case("RW", "OCLAQ_ReadWrite")
457             .Default("OCLAQ_None");
458 
459     OS << "  // " << T.second << "\n"
460        << "  {OCLT_" << T.first->getValueAsString("Name") << ", "
461        << T.first->getValueAsInt("VecWidth") << ", "
462        << T.first->getValueAsBit("IsPointer") << ", "
463        << T.first->getValueAsBit("IsConst") << ", "
464        << T.first->getValueAsBit("IsVolatile") << ", "
465        << AccessQual << ", "
466        << T.first->getValueAsString("AddrSpace") << "},\n";
467   }
468   OS << "};\n\n";
469 }
470 
471 void BuiltinNameEmitter::EmitSignatureTable() {
472   // Store a type (e.g. int, float, int2, ...). The type is stored as an index
473   // of a struct OpenCLType table. Multiple entries following each other form a
474   // signature.
475   OS << "static const unsigned short SignatureTable[] = {\n";
476   for (const auto &P : SignaturesList) {
477     OS << "  // " << P.second << "\n  ";
478     for (const Record *R : P.first) {
479       unsigned Entry = TypeMap.find(R)->second;
480       if (Entry > USHRT_MAX) {
481         // Report an error when seeing an entry that is too large for the
482         // current index type (unsigned short).  When hitting this, the type
483         // of SignatureTable will need to be changed.
484         PrintFatalError("Entry in SignatureTable exceeds limit.");
485       }
486       OS << Entry << ", ";
487     }
488     OS << "\n";
489   }
490   OS << "};\n\n";
491 }
492 
493 void BuiltinNameEmitter::EmitBuiltinTable() {
494   unsigned Index = 0;
495 
496   OS << "static const OpenCLBuiltinStruct BuiltinTable[] = {\n";
497   for (const auto &SLM : SignatureListMap) {
498 
499     OS << "  // " << (Index + 1) << ": ";
500     for (const auto &Name : SLM.second.Names) {
501       OS << Name << ", ";
502     }
503     OS << "\n";
504 
505     for (const auto &Overload : SLM.second.Signatures) {
506       StringRef ExtName = Overload.first->getValueAsDef("Extension")->getName();
507       OS << "  { " << Overload.second << ", "
508          << Overload.first->getValueAsListOfDefs("Signature").size() << ", "
509          << (Overload.first->getValueAsBit("IsPure")) << ", "
510          << (Overload.first->getValueAsBit("IsConst")) << ", "
511          << (Overload.first->getValueAsBit("IsConv")) << ", "
512          << FunctionExtensionIndex[ExtName] << ", "
513          << Overload.first->getValueAsDef("MinVersion")->getValueAsInt("ID")
514          << ", "
515          << Overload.first->getValueAsDef("MaxVersion")->getValueAsInt("ID")
516          << " },\n";
517       Index++;
518     }
519   }
520   OS << "};\n\n";
521 }
522 
523 bool BuiltinNameEmitter::CanReuseSignature(
524     BuiltinIndexListTy *Candidate,
525     std::vector<std::pair<const Record *, unsigned>> &SignatureList) {
526   assert(Candidate->size() == SignatureList.size() &&
527          "signature lists should have the same size");
528 
529   auto &CandidateSigs =
530       SignatureListMap.find(Candidate)->second.Signatures;
531   for (unsigned Index = 0; Index < Candidate->size(); Index++) {
532     const Record *Rec = SignatureList[Index].first;
533     const Record *Rec2 = CandidateSigs[Index].first;
534     if (Rec->getValueAsBit("IsPure") == Rec2->getValueAsBit("IsPure") &&
535         Rec->getValueAsBit("IsConst") == Rec2->getValueAsBit("IsConst") &&
536         Rec->getValueAsBit("IsConv") == Rec2->getValueAsBit("IsConv") &&
537         Rec->getValueAsDef("MinVersion")->getValueAsInt("ID") ==
538             Rec2->getValueAsDef("MinVersion")->getValueAsInt("ID") &&
539         Rec->getValueAsDef("MaxVersion")->getValueAsInt("ID") ==
540             Rec2->getValueAsDef("MaxVersion")->getValueAsInt("ID") &&
541         Rec->getValueAsDef("Extension")->getName() ==
542             Rec2->getValueAsDef("Extension")->getName()) {
543       return true;
544     }
545   }
546   return false;
547 }
548 
549 void BuiltinNameEmitter::GroupBySignature() {
550   // List of signatures known to be emitted.
551   std::vector<BuiltinIndexListTy *> KnownSignatures;
552 
553   for (auto &Fct : FctOverloadMap) {
554     bool FoundReusableSig = false;
555 
556     // Gather all signatures for the current function.
557     auto *CurSignatureList = new BuiltinIndexListTy();
558     for (const auto &Signature : Fct.second) {
559       CurSignatureList->push_back(Signature.second);
560     }
561     // Sort the list to facilitate future comparisons.
562     llvm::sort(*CurSignatureList);
563 
564     // Check if we have already seen another function with the same list of
565     // signatures.  If so, just add the name of the function.
566     for (auto *Candidate : KnownSignatures) {
567       if (Candidate->size() == CurSignatureList->size() &&
568           *Candidate == *CurSignatureList) {
569         if (CanReuseSignature(Candidate, Fct.second)) {
570           SignatureListMap.find(Candidate)->second.Names.push_back(Fct.first);
571           FoundReusableSig = true;
572         }
573       }
574     }
575 
576     if (FoundReusableSig) {
577       delete CurSignatureList;
578     } else {
579       // Add a new entry.
580       SignatureListMap[CurSignatureList] = {
581           SmallVector<StringRef, 4>(1, Fct.first), Fct.second};
582       KnownSignatures.push_back(CurSignatureList);
583     }
584   }
585 
586   for (auto *I : KnownSignatures) {
587     delete I;
588   }
589 }
590 
591 void BuiltinNameEmitter::EmitStringMatcher() {
592   std::vector<StringMatcher::StringPair> ValidBuiltins;
593   unsigned CumulativeIndex = 1;
594 
595   for (const auto &SLM : SignatureListMap) {
596     const auto &Ovl = SLM.second.Signatures;
597 
598     // A single signature list may be used by different builtins.  Return the
599     // same <index, length> pair for each of those builtins.
600     for (const auto &FctName : SLM.second.Names) {
601       std::string RetStmt;
602       raw_string_ostream SS(RetStmt);
603       SS << "return std::make_pair(" << CumulativeIndex << ", " << Ovl.size()
604          << ");";
605       SS.flush();
606       ValidBuiltins.push_back(
607           StringMatcher::StringPair(std::string(FctName), RetStmt));
608     }
609     CumulativeIndex += Ovl.size();
610   }
611 
612   OS << R"(
613 // Find out whether a string matches an existing OpenCL builtin function name.
614 // Returns: A pair <0, 0> if no name matches.
615 //          A pair <Index, Len> indexing the BuiltinTable if the name is
616 //          matching an OpenCL builtin function.
617 static std::pair<unsigned, unsigned> isOpenCLBuiltin(llvm::StringRef Name) {
618 
619 )";
620 
621   StringMatcher("Name", ValidBuiltins, OS).Emit(0, true);
622 
623   OS << "  return std::make_pair(0, 0);\n";
624   OS << "} // isOpenCLBuiltin\n";
625 }
626 
627 void BuiltinNameEmitter::EmitQualTypeFinder() {
628   OS << R"(
629 
630 static QualType getOpenCLEnumType(Sema &S, llvm::StringRef Name);
631 static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name);
632 
633 // Convert an OpenCLTypeStruct type to a list of QualTypes.
634 // Generic types represent multiple types and vector sizes, thus a vector
635 // is returned. The conversion is done in two steps:
636 // Step 1: A switch statement fills a vector with scalar base types for the
637 //         Cartesian product of (vector sizes) x (types) for generic types,
638 //         or a single scalar type for non generic types.
639 // Step 2: Qualifiers and other type properties such as vector size are
640 //         applied.
641 static void OCL2Qual(Sema &S, const OpenCLTypeStruct &Ty,
642                      llvm::SmallVectorImpl<QualType> &QT) {
643   ASTContext &Context = S.Context;
644   // Number of scalar types in the GenType.
645   unsigned GenTypeNumTypes;
646   // Pointer to the list of vector sizes for the GenType.
647   llvm::ArrayRef<unsigned> GenVectorSizes;
648 )";
649 
650   // Generate list of vector sizes for each generic type.
651   for (const auto *VectList : Records.getAllDerivedDefinitions("IntList")) {
652     OS << "  constexpr unsigned List"
653        << VectList->getValueAsString("Name") << "[] = {";
654     for (const auto V : VectList->getValueAsListOfInts("List")) {
655       OS << V << ", ";
656     }
657     OS << "};\n";
658   }
659 
660   // Step 1.
661   // Start of switch statement over all types.
662   OS << "\n  switch (Ty.ID) {\n";
663 
664   // Switch cases for image types (Image2d, Image3d, ...)
665   std::vector<Record *> ImageTypes =
666       Records.getAllDerivedDefinitions("ImageType");
667 
668   // Map an image type name to its 3 access-qualified types (RO, WO, RW).
669   StringMap<SmallVector<Record *, 3>> ImageTypesMap;
670   for (auto *IT : ImageTypes) {
671     auto Entry = ImageTypesMap.find(IT->getValueAsString("Name"));
672     if (Entry == ImageTypesMap.end()) {
673       SmallVector<Record *, 3> ImageList;
674       ImageList.push_back(IT);
675       ImageTypesMap.insert(
676           std::make_pair(IT->getValueAsString("Name"), ImageList));
677     } else {
678       Entry->second.push_back(IT);
679     }
680   }
681 
682   // Emit the cases for the image types.  For an image type name, there are 3
683   // corresponding QualTypes ("RO", "WO", "RW").  The "AccessQualifier" field
684   // tells which one is needed.  Emit a switch statement that puts the
685   // corresponding QualType into "QT".
686   for (const auto &ITE : ImageTypesMap) {
687     OS << "    case OCLT_" << ITE.getKey() << ":\n"
688        << "      switch (Ty.AccessQualifier) {\n"
689        << "        case OCLAQ_None:\n"
690        << "          llvm_unreachable(\"Image without access qualifier\");\n";
691     for (const auto &Image : ITE.getValue()) {
692       OS << StringSwitch<const char *>(
693                 Image->getValueAsString("AccessQualifier"))
694                 .Case("RO", "        case OCLAQ_ReadOnly:\n")
695                 .Case("WO", "        case OCLAQ_WriteOnly:\n")
696                 .Case("RW", "        case OCLAQ_ReadWrite:\n")
697          << "          QT.push_back("
698          << Image->getValueAsDef("QTExpr")->getValueAsString("TypeExpr")
699          << ");\n"
700          << "          break;\n";
701     }
702     OS << "      }\n"
703        << "      break;\n";
704   }
705 
706   // Switch cases for generic types.
707   for (const auto *GenType : Records.getAllDerivedDefinitions("GenericType")) {
708     OS << "    case OCLT_" << GenType->getValueAsString("Name") << ":\n";
709     OS << "      QT.append({";
710 
711     // Build the Cartesian product of (vector sizes) x (types).  Only insert
712     // the plain scalar types for now; other type information such as vector
713     // size and type qualifiers will be added after the switch statement.
714     for (unsigned I = 0; I < GenType->getValueAsDef("VectorList")
715                                  ->getValueAsListOfInts("List")
716                                  .size();
717          I++) {
718       for (const auto *T :
719            GenType->getValueAsDef("TypeList")->getValueAsListOfDefs("List")) {
720         OS << T->getValueAsDef("QTExpr")->getValueAsString("TypeExpr") << ", ";
721       }
722     }
723     OS << "});\n";
724     // GenTypeNumTypes is the number of types in the GenType
725     // (e.g. float/double/half).
726     OS << "      GenTypeNumTypes = "
727        << GenType->getValueAsDef("TypeList")->getValueAsListOfDefs("List")
728               .size()
729        << ";\n";
730     // GenVectorSizes is the list of vector sizes for this GenType.
731     // QT contains GenTypeNumTypes * #GenVectorSizes elements.
732     OS << "      GenVectorSizes = List"
733        << GenType->getValueAsDef("VectorList")->getValueAsString("Name")
734        << ";\n";
735     OS << "      break;\n";
736   }
737 
738   // Switch cases for non generic, non image types (int, int4, float, ...).
739   // Only insert the plain scalar type; vector information and type qualifiers
740   // are added in step 2.
741   std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
742   StringMap<bool> TypesSeen;
743 
744   for (const auto *T : Types) {
745     // Check this is not an image type
746     if (ImageTypesMap.find(T->getValueAsString("Name")) != ImageTypesMap.end())
747       continue;
748     // Check we have not seen this Type
749     if (TypesSeen.find(T->getValueAsString("Name")) != TypesSeen.end())
750       continue;
751     TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true));
752 
753     // Check the Type does not have an "abstract" QualType
754     auto QT = T->getValueAsDef("QTExpr");
755     if (QT->getValueAsBit("IsAbstract") == 1)
756       continue;
757     // Emit the cases for non generic, non image types.
758     OS << "    case OCLT_" << T->getValueAsString("Name") << ":\n"
759        << "      QT.push_back(" << QT->getValueAsString("TypeExpr") << ");\n"
760        << "      break;\n";
761   }
762 
763   // End of switch statement.
764   OS << "  } // end of switch (Ty.ID)\n\n";
765 
766   // Step 2.
767   // Add ExtVector types if this was a generic type, as the switch statement
768   // above only populated the list with scalar types.  This completes the
769   // construction of the Cartesian product of (vector sizes) x (types).
770   OS << "  // Construct the different vector types for each generic type.\n";
771   OS << "  if (Ty.ID >= " << TypeList.size() << ") {";
772   OS << R"(
773     for (unsigned I = 0; I < QT.size(); I++) {
774       // For scalars, size is 1.
775       if (GenVectorSizes[I / GenTypeNumTypes] != 1) {
776         QT[I] = Context.getExtVectorType(QT[I],
777                           GenVectorSizes[I / GenTypeNumTypes]);
778       }
779     }
780   }
781 )";
782 
783   // Assign the right attributes to the types (e.g. vector size).
784   OS << R"(
785   // Set vector size for non-generic vector types.
786   if (Ty.VectorWidth > 1) {
787     for (unsigned Index = 0; Index < QT.size(); Index++) {
788       QT[Index] = Context.getExtVectorType(QT[Index], Ty.VectorWidth);
789     }
790   }
791 
792   if (Ty.IsVolatile != 0) {
793     for (unsigned Index = 0; Index < QT.size(); Index++) {
794       QT[Index] = Context.getVolatileType(QT[Index]);
795     }
796   }
797 
798   if (Ty.IsConst != 0) {
799     for (unsigned Index = 0; Index < QT.size(); Index++) {
800       QT[Index] = Context.getConstType(QT[Index]);
801     }
802   }
803 
804   // Transform the type to a pointer as the last step, if necessary.
805   // Builtin functions only have pointers on [const|volatile], no
806   // [const|volatile] pointers, so this is ok to do it as a last step.
807   if (Ty.IsPointer != 0) {
808     for (unsigned Index = 0; Index < QT.size(); Index++) {
809       QT[Index] = Context.getAddrSpaceQualType(QT[Index], Ty.AS);
810       QT[Index] = Context.getPointerType(QT[Index]);
811     }
812   }
813 )";
814 
815   // End of the "OCL2Qual" function.
816   OS << "\n} // OCL2Qual\n";
817 }
818 
819 void clang::EmitClangOpenCLBuiltins(RecordKeeper &Records, raw_ostream &OS) {
820   BuiltinNameEmitter NameChecker(Records, OS);
821   NameChecker.Emit();
822 }
823