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:
BuiltinNameEmitter(RecordKeeper & Records,raw_ostream & OS)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
Emit()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
ExtractEnumTypes(std::vector<Record * > & Types,StringMap<bool> & TypesSeen,std::string & Output,std::vector<const Record * > & List)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
EmitDeclarations()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 // OpenCL versions in which this overload is available.
343 const unsigned short Versions;
344 };
345
346 )";
347 }
348
349 // Verify that the combination of GenTypes in a signature is supported.
350 // To simplify the logic for creating overloads in SemaLookup, only allow
351 // a signature to contain different GenTypes if these GenTypes represent
352 // the same number of actual scalar or vector types.
353 //
354 // Exit with a fatal error if an unsupported construct is encountered.
VerifySignature(const std::vector<Record * > & Signature,const Record * BuiltinRec)355 static void VerifySignature(const std::vector<Record *> &Signature,
356 const Record *BuiltinRec) {
357 unsigned GenTypeVecSizes = 1;
358 unsigned GenTypeTypes = 1;
359
360 for (const auto *T : Signature) {
361 // Check all GenericType arguments in this signature.
362 if (T->isSubClassOf("GenericType")) {
363 // Check number of vector sizes.
364 unsigned NVecSizes =
365 T->getValueAsDef("VectorList")->getValueAsListOfInts("List").size();
366 if (NVecSizes != GenTypeVecSizes && NVecSizes != 1) {
367 if (GenTypeVecSizes > 1) {
368 // We already saw a gentype with a different number of vector sizes.
369 PrintFatalError(BuiltinRec->getLoc(),
370 "number of vector sizes should be equal or 1 for all gentypes "
371 "in a declaration");
372 }
373 GenTypeVecSizes = NVecSizes;
374 }
375
376 // Check number of data types.
377 unsigned NTypes =
378 T->getValueAsDef("TypeList")->getValueAsListOfDefs("List").size();
379 if (NTypes != GenTypeTypes && NTypes != 1) {
380 if (GenTypeTypes > 1) {
381 // We already saw a gentype with a different number of types.
382 PrintFatalError(BuiltinRec->getLoc(),
383 "number of types should be equal or 1 for all gentypes "
384 "in a declaration");
385 }
386 GenTypeTypes = NTypes;
387 }
388 }
389 }
390 }
391
GetOverloads()392 void BuiltinNameEmitter::GetOverloads() {
393 // Populate the TypeMap.
394 std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
395 unsigned I = 0;
396 for (const auto &T : Types) {
397 TypeMap.insert(std::make_pair(T, I++));
398 }
399
400 // Populate the SignaturesList and the FctOverloadMap.
401 unsigned CumulativeSignIndex = 0;
402 std::vector<Record *> Builtins = Records.getAllDerivedDefinitions("Builtin");
403 for (const auto *B : Builtins) {
404 StringRef BName = B->getValueAsString("Name");
405 if (FctOverloadMap.find(BName) == FctOverloadMap.end()) {
406 FctOverloadMap.insert(std::make_pair(
407 BName, std::vector<std::pair<const Record *, unsigned>>{}));
408 }
409
410 auto Signature = B->getValueAsListOfDefs("Signature");
411 // Reuse signatures to avoid unnecessary duplicates.
412 auto it =
413 std::find_if(SignaturesList.begin(), SignaturesList.end(),
414 [&](const std::pair<std::vector<Record *>, unsigned> &a) {
415 return a.first == Signature;
416 });
417 unsigned SignIndex;
418 if (it == SignaturesList.end()) {
419 VerifySignature(Signature, B);
420 SignaturesList.push_back(std::make_pair(Signature, CumulativeSignIndex));
421 SignIndex = CumulativeSignIndex;
422 CumulativeSignIndex += Signature.size();
423 } else {
424 SignIndex = it->second;
425 }
426 FctOverloadMap[BName].push_back(std::make_pair(B, SignIndex));
427 }
428 }
429
EmitExtensionTable()430 void BuiltinNameEmitter::EmitExtensionTable() {
431 OS << "static const char *FunctionExtensionTable[] = {\n";
432 unsigned Index = 0;
433 std::vector<Record *> FuncExtensions =
434 Records.getAllDerivedDefinitions("FunctionExtension");
435
436 for (const auto &FE : FuncExtensions) {
437 // Emit OpenCL extension table entry.
438 OS << " // " << Index << ": " << FE->getName() << "\n"
439 << " \"" << FE->getValueAsString("ExtName") << "\",\n";
440
441 // Record index of this extension.
442 FunctionExtensionIndex[FE->getName()] = Index++;
443 }
444 OS << "};\n\n";
445 }
446
EmitTypeTable()447 void BuiltinNameEmitter::EmitTypeTable() {
448 OS << "static const OpenCLTypeStruct TypeTable[] = {\n";
449 for (const auto &T : TypeMap) {
450 const char *AccessQual =
451 StringSwitch<const char *>(T.first->getValueAsString("AccessQualifier"))
452 .Case("RO", "OCLAQ_ReadOnly")
453 .Case("WO", "OCLAQ_WriteOnly")
454 .Case("RW", "OCLAQ_ReadWrite")
455 .Default("OCLAQ_None");
456
457 OS << " // " << T.second << "\n"
458 << " {OCLT_" << T.first->getValueAsString("Name") << ", "
459 << T.first->getValueAsInt("VecWidth") << ", "
460 << T.first->getValueAsBit("IsPointer") << ", "
461 << T.first->getValueAsBit("IsConst") << ", "
462 << T.first->getValueAsBit("IsVolatile") << ", "
463 << AccessQual << ", "
464 << T.first->getValueAsString("AddrSpace") << "},\n";
465 }
466 OS << "};\n\n";
467 }
468
EmitSignatureTable()469 void BuiltinNameEmitter::EmitSignatureTable() {
470 // Store a type (e.g. int, float, int2, ...). The type is stored as an index
471 // of a struct OpenCLType table. Multiple entries following each other form a
472 // signature.
473 OS << "static const unsigned short SignatureTable[] = {\n";
474 for (const auto &P : SignaturesList) {
475 OS << " // " << P.second << "\n ";
476 for (const Record *R : P.first) {
477 unsigned Entry = TypeMap.find(R)->second;
478 if (Entry > USHRT_MAX) {
479 // Report an error when seeing an entry that is too large for the
480 // current index type (unsigned short). When hitting this, the type
481 // of SignatureTable will need to be changed.
482 PrintFatalError("Entry in SignatureTable exceeds limit.");
483 }
484 OS << Entry << ", ";
485 }
486 OS << "\n";
487 }
488 OS << "};\n\n";
489 }
490
491 // Encode a range MinVersion..MaxVersion into a single bit mask that can be
492 // checked against LangOpts using isOpenCLVersionContainedInMask().
493 // This must be kept in sync with OpenCLVersionID in OpenCLOptions.h.
494 // (Including OpenCLOptions.h here would be a layering violation.)
EncodeVersions(unsigned int MinVersion,unsigned int MaxVersion)495 static unsigned short EncodeVersions(unsigned int MinVersion,
496 unsigned int MaxVersion) {
497 unsigned short Encoded = 0;
498
499 // A maximum version of 0 means available in all later versions.
500 if (MaxVersion == 0) {
501 MaxVersion = UINT_MAX;
502 }
503
504 unsigned VersionIDs[] = {100, 110, 120, 200, 300};
505 for (unsigned I = 0; I < sizeof(VersionIDs) / sizeof(VersionIDs[0]); I++) {
506 if (VersionIDs[I] >= MinVersion && VersionIDs[I] < MaxVersion) {
507 Encoded |= 1 << I;
508 }
509 }
510
511 return Encoded;
512 }
513
EmitBuiltinTable()514 void BuiltinNameEmitter::EmitBuiltinTable() {
515 unsigned Index = 0;
516
517 OS << "static const OpenCLBuiltinStruct BuiltinTable[] = {\n";
518 for (const auto &SLM : SignatureListMap) {
519
520 OS << " // " << (Index + 1) << ": ";
521 for (const auto &Name : SLM.second.Names) {
522 OS << Name << ", ";
523 }
524 OS << "\n";
525
526 for (const auto &Overload : SLM.second.Signatures) {
527 StringRef ExtName = Overload.first->getValueAsDef("Extension")->getName();
528 unsigned int MinVersion =
529 Overload.first->getValueAsDef("MinVersion")->getValueAsInt("ID");
530 unsigned int MaxVersion =
531 Overload.first->getValueAsDef("MaxVersion")->getValueAsInt("ID");
532
533 OS << " { " << Overload.second << ", "
534 << Overload.first->getValueAsListOfDefs("Signature").size() << ", "
535 << (Overload.first->getValueAsBit("IsPure")) << ", "
536 << (Overload.first->getValueAsBit("IsConst")) << ", "
537 << (Overload.first->getValueAsBit("IsConv")) << ", "
538 << FunctionExtensionIndex[ExtName] << ", "
539 << EncodeVersions(MinVersion, MaxVersion) << " },\n";
540 Index++;
541 }
542 }
543 OS << "};\n\n";
544 }
545
CanReuseSignature(BuiltinIndexListTy * Candidate,std::vector<std::pair<const Record *,unsigned>> & SignatureList)546 bool BuiltinNameEmitter::CanReuseSignature(
547 BuiltinIndexListTy *Candidate,
548 std::vector<std::pair<const Record *, unsigned>> &SignatureList) {
549 assert(Candidate->size() == SignatureList.size() &&
550 "signature lists should have the same size");
551
552 auto &CandidateSigs =
553 SignatureListMap.find(Candidate)->second.Signatures;
554 for (unsigned Index = 0; Index < Candidate->size(); Index++) {
555 const Record *Rec = SignatureList[Index].first;
556 const Record *Rec2 = CandidateSigs[Index].first;
557 if (Rec->getValueAsBit("IsPure") == Rec2->getValueAsBit("IsPure") &&
558 Rec->getValueAsBit("IsConst") == Rec2->getValueAsBit("IsConst") &&
559 Rec->getValueAsBit("IsConv") == Rec2->getValueAsBit("IsConv") &&
560 Rec->getValueAsDef("MinVersion")->getValueAsInt("ID") ==
561 Rec2->getValueAsDef("MinVersion")->getValueAsInt("ID") &&
562 Rec->getValueAsDef("MaxVersion")->getValueAsInt("ID") ==
563 Rec2->getValueAsDef("MaxVersion")->getValueAsInt("ID") &&
564 Rec->getValueAsDef("Extension")->getName() ==
565 Rec2->getValueAsDef("Extension")->getName()) {
566 return true;
567 }
568 }
569 return false;
570 }
571
GroupBySignature()572 void BuiltinNameEmitter::GroupBySignature() {
573 // List of signatures known to be emitted.
574 std::vector<BuiltinIndexListTy *> KnownSignatures;
575
576 for (auto &Fct : FctOverloadMap) {
577 bool FoundReusableSig = false;
578
579 // Gather all signatures for the current function.
580 auto *CurSignatureList = new BuiltinIndexListTy();
581 for (const auto &Signature : Fct.second) {
582 CurSignatureList->push_back(Signature.second);
583 }
584 // Sort the list to facilitate future comparisons.
585 llvm::sort(*CurSignatureList);
586
587 // Check if we have already seen another function with the same list of
588 // signatures. If so, just add the name of the function.
589 for (auto *Candidate : KnownSignatures) {
590 if (Candidate->size() == CurSignatureList->size() &&
591 *Candidate == *CurSignatureList) {
592 if (CanReuseSignature(Candidate, Fct.second)) {
593 SignatureListMap.find(Candidate)->second.Names.push_back(Fct.first);
594 FoundReusableSig = true;
595 }
596 }
597 }
598
599 if (FoundReusableSig) {
600 delete CurSignatureList;
601 } else {
602 // Add a new entry.
603 SignatureListMap[CurSignatureList] = {
604 SmallVector<StringRef, 4>(1, Fct.first), Fct.second};
605 KnownSignatures.push_back(CurSignatureList);
606 }
607 }
608
609 for (auto *I : KnownSignatures) {
610 delete I;
611 }
612 }
613
EmitStringMatcher()614 void BuiltinNameEmitter::EmitStringMatcher() {
615 std::vector<StringMatcher::StringPair> ValidBuiltins;
616 unsigned CumulativeIndex = 1;
617
618 for (const auto &SLM : SignatureListMap) {
619 const auto &Ovl = SLM.second.Signatures;
620
621 // A single signature list may be used by different builtins. Return the
622 // same <index, length> pair for each of those builtins.
623 for (const auto &FctName : SLM.second.Names) {
624 std::string RetStmt;
625 raw_string_ostream SS(RetStmt);
626 SS << "return std::make_pair(" << CumulativeIndex << ", " << Ovl.size()
627 << ");";
628 SS.flush();
629 ValidBuiltins.push_back(
630 StringMatcher::StringPair(std::string(FctName), RetStmt));
631 }
632 CumulativeIndex += Ovl.size();
633 }
634
635 OS << R"(
636 // Find out whether a string matches an existing OpenCL builtin function name.
637 // Returns: A pair <0, 0> if no name matches.
638 // A pair <Index, Len> indexing the BuiltinTable if the name is
639 // matching an OpenCL builtin function.
640 static std::pair<unsigned, unsigned> isOpenCLBuiltin(llvm::StringRef Name) {
641
642 )";
643
644 StringMatcher("Name", ValidBuiltins, OS).Emit(0, true);
645
646 OS << " return std::make_pair(0, 0);\n";
647 OS << "} // isOpenCLBuiltin\n";
648 }
649
EmitQualTypeFinder()650 void BuiltinNameEmitter::EmitQualTypeFinder() {
651 OS << R"(
652
653 static QualType getOpenCLEnumType(Sema &S, llvm::StringRef Name);
654 static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name);
655
656 // Convert an OpenCLTypeStruct type to a list of QualTypes.
657 // Generic types represent multiple types and vector sizes, thus a vector
658 // is returned. The conversion is done in two steps:
659 // Step 1: A switch statement fills a vector with scalar base types for the
660 // Cartesian product of (vector sizes) x (types) for generic types,
661 // or a single scalar type for non generic types.
662 // Step 2: Qualifiers and other type properties such as vector size are
663 // applied.
664 static void OCL2Qual(Sema &S, const OpenCLTypeStruct &Ty,
665 llvm::SmallVectorImpl<QualType> &QT) {
666 ASTContext &Context = S.Context;
667 // Number of scalar types in the GenType.
668 unsigned GenTypeNumTypes;
669 // Pointer to the list of vector sizes for the GenType.
670 llvm::ArrayRef<unsigned> GenVectorSizes;
671 )";
672
673 // Generate list of vector sizes for each generic type.
674 for (const auto *VectList : Records.getAllDerivedDefinitions("IntList")) {
675 OS << " constexpr unsigned List"
676 << VectList->getValueAsString("Name") << "[] = {";
677 for (const auto V : VectList->getValueAsListOfInts("List")) {
678 OS << V << ", ";
679 }
680 OS << "};\n";
681 }
682
683 // Step 1.
684 // Start of switch statement over all types.
685 OS << "\n switch (Ty.ID) {\n";
686
687 // Switch cases for image types (Image2d, Image3d, ...)
688 std::vector<Record *> ImageTypes =
689 Records.getAllDerivedDefinitions("ImageType");
690
691 // Map an image type name to its 3 access-qualified types (RO, WO, RW).
692 StringMap<SmallVector<Record *, 3>> ImageTypesMap;
693 for (auto *IT : ImageTypes) {
694 auto Entry = ImageTypesMap.find(IT->getValueAsString("Name"));
695 if (Entry == ImageTypesMap.end()) {
696 SmallVector<Record *, 3> ImageList;
697 ImageList.push_back(IT);
698 ImageTypesMap.insert(
699 std::make_pair(IT->getValueAsString("Name"), ImageList));
700 } else {
701 Entry->second.push_back(IT);
702 }
703 }
704
705 // Emit the cases for the image types. For an image type name, there are 3
706 // corresponding QualTypes ("RO", "WO", "RW"). The "AccessQualifier" field
707 // tells which one is needed. Emit a switch statement that puts the
708 // corresponding QualType into "QT".
709 for (const auto &ITE : ImageTypesMap) {
710 OS << " case OCLT_" << ITE.getKey() << ":\n"
711 << " switch (Ty.AccessQualifier) {\n"
712 << " case OCLAQ_None:\n"
713 << " llvm_unreachable(\"Image without access qualifier\");\n";
714 for (const auto &Image : ITE.getValue()) {
715 OS << StringSwitch<const char *>(
716 Image->getValueAsString("AccessQualifier"))
717 .Case("RO", " case OCLAQ_ReadOnly:\n")
718 .Case("WO", " case OCLAQ_WriteOnly:\n")
719 .Case("RW", " case OCLAQ_ReadWrite:\n")
720 << " QT.push_back("
721 << Image->getValueAsDef("QTExpr")->getValueAsString("TypeExpr")
722 << ");\n"
723 << " break;\n";
724 }
725 OS << " }\n"
726 << " break;\n";
727 }
728
729 // Switch cases for generic types.
730 for (const auto *GenType : Records.getAllDerivedDefinitions("GenericType")) {
731 OS << " case OCLT_" << GenType->getValueAsString("Name") << ": {\n";
732
733 // Build the Cartesian product of (vector sizes) x (types). Only insert
734 // the plain scalar types for now; other type information such as vector
735 // size and type qualifiers will be added after the switch statement.
736 std::vector<Record *> BaseTypes =
737 GenType->getValueAsDef("TypeList")->getValueAsListOfDefs("List");
738
739 // Collect all QualTypes for a single vector size into TypeList.
740 OS << " SmallVector<QualType, " << BaseTypes.size() << "> TypeList;\n";
741 for (const auto *T : BaseTypes) {
742 StringRef Ext =
743 T->getValueAsDef("Extension")->getValueAsString("ExtName");
744 if (!Ext.empty()) {
745 OS << " if (S.getPreprocessor().isMacroDefined(\"" << Ext
746 << "\")) {\n ";
747 }
748 OS << " TypeList.push_back("
749 << T->getValueAsDef("QTExpr")->getValueAsString("TypeExpr") << ");\n";
750 if (!Ext.empty()) {
751 OS << " }\n";
752 }
753 }
754 OS << " GenTypeNumTypes = TypeList.size();\n";
755
756 // Duplicate the TypeList for every vector size.
757 std::vector<int64_t> VectorList =
758 GenType->getValueAsDef("VectorList")->getValueAsListOfInts("List");
759 OS << " QT.reserve(" << VectorList.size() * BaseTypes.size() << ");\n"
760 << " for (unsigned I = 0; I < " << VectorList.size() << "; I++) {\n"
761 << " QT.append(TypeList);\n"
762 << " }\n";
763
764 // GenVectorSizes is the list of vector sizes for this GenType.
765 OS << " GenVectorSizes = List"
766 << GenType->getValueAsDef("VectorList")->getValueAsString("Name")
767 << ";\n"
768 << " break;\n"
769 << " }\n";
770 }
771
772 // Switch cases for non generic, non image types (int, int4, float, ...).
773 // Only insert the plain scalar type; vector information and type qualifiers
774 // are added in step 2.
775 std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
776 StringMap<bool> TypesSeen;
777
778 for (const auto *T : Types) {
779 // Check this is not an image type
780 if (ImageTypesMap.find(T->getValueAsString("Name")) != ImageTypesMap.end())
781 continue;
782 // Check we have not seen this Type
783 if (TypesSeen.find(T->getValueAsString("Name")) != TypesSeen.end())
784 continue;
785 TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true));
786
787 // Check the Type does not have an "abstract" QualType
788 auto QT = T->getValueAsDef("QTExpr");
789 if (QT->getValueAsBit("IsAbstract") == 1)
790 continue;
791 // Emit the cases for non generic, non image types.
792 OS << " case OCLT_" << T->getValueAsString("Name") << ":\n";
793
794 StringRef Ext = T->getValueAsDef("Extension")->getValueAsString("ExtName");
795 // If this type depends on an extension, ensure the extension macro is
796 // defined.
797 if (!Ext.empty()) {
798 OS << " if (S.getPreprocessor().isMacroDefined(\"" << Ext
799 << "\")) {\n ";
800 }
801 OS << " QT.push_back(" << QT->getValueAsString("TypeExpr") << ");\n";
802 if (!Ext.empty()) {
803 OS << " }\n";
804 }
805 OS << " break;\n";
806 }
807
808 // End of switch statement.
809 OS << " } // end of switch (Ty.ID)\n\n";
810
811 // Step 2.
812 // Add ExtVector types if this was a generic type, as the switch statement
813 // above only populated the list with scalar types. This completes the
814 // construction of the Cartesian product of (vector sizes) x (types).
815 OS << " // Construct the different vector types for each generic type.\n";
816 OS << " if (Ty.ID >= " << TypeList.size() << ") {";
817 OS << R"(
818 for (unsigned I = 0; I < QT.size(); I++) {
819 // For scalars, size is 1.
820 if (GenVectorSizes[I / GenTypeNumTypes] != 1) {
821 QT[I] = Context.getExtVectorType(QT[I],
822 GenVectorSizes[I / GenTypeNumTypes]);
823 }
824 }
825 }
826 )";
827
828 // Assign the right attributes to the types (e.g. vector size).
829 OS << R"(
830 // Set vector size for non-generic vector types.
831 if (Ty.VectorWidth > 1) {
832 for (unsigned Index = 0; Index < QT.size(); Index++) {
833 QT[Index] = Context.getExtVectorType(QT[Index], Ty.VectorWidth);
834 }
835 }
836
837 if (Ty.IsVolatile != 0) {
838 for (unsigned Index = 0; Index < QT.size(); Index++) {
839 QT[Index] = Context.getVolatileType(QT[Index]);
840 }
841 }
842
843 if (Ty.IsConst != 0) {
844 for (unsigned Index = 0; Index < QT.size(); Index++) {
845 QT[Index] = Context.getConstType(QT[Index]);
846 }
847 }
848
849 // Transform the type to a pointer as the last step, if necessary.
850 // Builtin functions only have pointers on [const|volatile], no
851 // [const|volatile] pointers, so this is ok to do it as a last step.
852 if (Ty.IsPointer != 0) {
853 for (unsigned Index = 0; Index < QT.size(); Index++) {
854 QT[Index] = Context.getAddrSpaceQualType(QT[Index], Ty.AS);
855 QT[Index] = Context.getPointerType(QT[Index]);
856 }
857 }
858 )";
859
860 // End of the "OCL2Qual" function.
861 OS << "\n} // OCL2Qual\n";
862 }
863
EmitClangOpenCLBuiltins(RecordKeeper & Records,raw_ostream & OS)864 void clang::EmitClangOpenCLBuiltins(RecordKeeper &Records, raw_ostream &OS) {
865 BuiltinNameEmitter NameChecker(Records, OS);
866 NameChecker.Emit();
867 }
868