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