ClangOpenCLBuiltinEmitter.cpp 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196
  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. // These backends consume the definitions of OpenCL builtin functions in
  12. // clang/lib/Sema/OpenCLBuiltins.td and produce builtin handling code for
  13. // inclusion in SemaLookup.cpp, or a test file that calls all declared builtins.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "TableGenBackends.h"
  17. #include "llvm/ADT/MapVector.h"
  18. #include "llvm/ADT/STLExtras.h"
  19. #include "llvm/ADT/SmallString.h"
  20. #include "llvm/ADT/StringExtras.h"
  21. #include "llvm/ADT/StringMap.h"
  22. #include "llvm/ADT/StringRef.h"
  23. #include "llvm/ADT/StringSwitch.h"
  24. #include "llvm/Support/ErrorHandling.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. #include "llvm/TableGen/Error.h"
  27. #include "llvm/TableGen/Record.h"
  28. #include "llvm/TableGen/StringMatcher.h"
  29. #include "llvm/TableGen/TableGenBackend.h"
  30. using namespace llvm;
  31. namespace {
  32. // A list of signatures that are shared by one or more builtin functions.
  33. struct BuiltinTableEntries {
  34. SmallVector<StringRef, 4> Names;
  35. std::vector<std::pair<const Record *, unsigned>> Signatures;
  36. };
  37. // This tablegen backend emits code for checking whether a function is an
  38. // OpenCL builtin function. If so, all overloads of this function are
  39. // added to the LookupResult. The generated include file is used by
  40. // SemaLookup.cpp
  41. //
  42. // For a successful lookup of e.g. the "cos" builtin, isOpenCLBuiltin("cos")
  43. // returns a pair <Index, Len>.
  44. // BuiltinTable[Index] to BuiltinTable[Index + Len] contains the pairs
  45. // <SigIndex, SigLen> of the overloads of "cos".
  46. // SignatureTable[SigIndex] to SignatureTable[SigIndex + SigLen] contains
  47. // one of the signatures of "cos". The SignatureTable entry can be
  48. // referenced by other functions, e.g. "sin", to exploit the fact that
  49. // many OpenCL builtins share the same signature.
  50. //
  51. // The file generated by this TableGen emitter contains the following:
  52. //
  53. // * Structs and enums to represent types and function signatures.
  54. //
  55. // * const char *FunctionExtensionTable[]
  56. // List of space-separated OpenCL extensions. A builtin references an
  57. // entry in this table when the builtin requires a particular (set of)
  58. // extension(s) to be enabled.
  59. //
  60. // * OpenCLTypeStruct TypeTable[]
  61. // Type information for return types and arguments.
  62. //
  63. // * unsigned SignatureTable[]
  64. // A list of types representing function signatures. Each entry is an index
  65. // into the above TypeTable. Multiple entries following each other form a
  66. // signature, where the first entry is the return type and subsequent
  67. // entries are the argument types.
  68. //
  69. // * OpenCLBuiltinStruct BuiltinTable[]
  70. // Each entry represents one overload of an OpenCL builtin function and
  71. // consists of an index into the SignatureTable and the number of arguments.
  72. //
  73. // * std::pair<unsigned, unsigned> isOpenCLBuiltin(llvm::StringRef Name)
  74. // Find out whether a string matches an existing OpenCL builtin function
  75. // name and return an index into BuiltinTable and the number of overloads.
  76. //
  77. // * void OCL2Qual(Sema&, OpenCLTypeStruct, std::vector<QualType>&)
  78. // Convert an OpenCLTypeStruct type to a list of QualType instances.
  79. // One OpenCLTypeStruct can represent multiple types, primarily when using
  80. // GenTypes.
  81. //
  82. class BuiltinNameEmitter {
  83. public:
  84. BuiltinNameEmitter(RecordKeeper &Records, raw_ostream &OS)
  85. : Records(Records), OS(OS) {}
  86. // Entrypoint to generate the functions and structures for checking
  87. // whether a function is an OpenCL builtin function.
  88. void Emit();
  89. private:
  90. // A list of indices into the builtin function table.
  91. using BuiltinIndexListTy = SmallVector<unsigned, 11>;
  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. // The output file.
  96. raw_ostream &OS;
  97. // Helper function for BuiltinNameEmitter::EmitDeclarations. Generate enum
  98. // definitions in the Output string parameter, and save their Record instances
  99. // in the List parameter.
  100. // \param Types (in) List containing the Types to extract.
  101. // \param TypesSeen (inout) List containing the Types already extracted.
  102. // \param Output (out) String containing the enums to emit in the output file.
  103. // \param List (out) List containing the extracted Types, except the Types in
  104. // TypesSeen.
  105. void ExtractEnumTypes(std::vector<Record *> &Types,
  106. StringMap<bool> &TypesSeen, std::string &Output,
  107. std::vector<const Record *> &List);
  108. // Emit the enum or struct used in the generated file.
  109. // Populate the TypeList at the same time.
  110. void EmitDeclarations();
  111. // Parse the Records generated by TableGen to populate the SignaturesList,
  112. // FctOverloadMap and TypeMap.
  113. void GetOverloads();
  114. // Compare two lists of signatures and check that e.g. the OpenCL version,
  115. // function attributes, and extension are equal for each signature.
  116. // \param Candidate (in) Entry in the SignatureListMap to check.
  117. // \param SignatureList (in) List of signatures of the considered function.
  118. // \returns true if the two lists of signatures are identical.
  119. bool CanReuseSignature(
  120. BuiltinIndexListTy *Candidate,
  121. std::vector<std::pair<const Record *, unsigned>> &SignatureList);
  122. // Group functions with the same list of signatures by populating the
  123. // SignatureListMap.
  124. // Some builtin functions have the same list of signatures, for example the
  125. // "sin" and "cos" functions. To save space in the BuiltinTable, the
  126. // "isOpenCLBuiltin" function will have the same output for these two
  127. // function names.
  128. void GroupBySignature();
  129. // Emit the FunctionExtensionTable that lists all function extensions.
  130. void EmitExtensionTable();
  131. // Emit the TypeTable containing all types used by OpenCL builtins.
  132. void EmitTypeTable();
  133. // Emit the SignatureTable. This table contains all the possible signatures.
  134. // A signature is stored as a list of indexes of the TypeTable.
  135. // The first index references the return type (mandatory), and the followings
  136. // reference its arguments.
  137. // E.g.:
  138. // 15, 2, 15 can represent a function with the signature:
  139. // int func(float, int)
  140. // The "int" type being at the index 15 in the TypeTable.
  141. void EmitSignatureTable();
  142. // Emit the BuiltinTable table. This table contains all the overloads of
  143. // each function, and is a struct OpenCLBuiltinDecl.
  144. // E.g.:
  145. // // 891 convert_float2_rtn
  146. // { 58, 2, 3, 100, 0 },
  147. // This means that the signature of this convert_float2_rtn overload has
  148. // 1 argument (+1 for the return type), stored at index 58 in
  149. // the SignatureTable. This prototype requires extension "3" in the
  150. // FunctionExtensionTable. The last two values represent the minimum (1.0)
  151. // and maximum (0, meaning no max version) OpenCL version in which this
  152. // overload is supported.
  153. void EmitBuiltinTable();
  154. // Emit a StringMatcher function to check whether a function name is an
  155. // OpenCL builtin function name.
  156. void EmitStringMatcher();
  157. // Emit a function returning the clang QualType instance associated with
  158. // the TableGen Record Type.
  159. void EmitQualTypeFinder();
  160. // Contains a list of the available signatures, without the name of the
  161. // function. Each pair consists of a signature and a cumulative index.
  162. // E.g.: <<float, float>, 0>,
  163. // <<float, int, int, 2>>,
  164. // <<float>, 5>,
  165. // ...
  166. // <<double, double>, 35>.
  167. std::vector<std::pair<std::vector<Record *>, unsigned>> SignaturesList;
  168. // Map the name of a builtin function to its prototypes (instances of the
  169. // TableGen "Builtin" class).
  170. // Each prototype is registered as a pair of:
  171. // <pointer to the "Builtin" instance,
  172. // cumulative index of the associated signature in the SignaturesList>
  173. // E.g.: The function cos: (float cos(float), double cos(double), ...)
  174. // <"cos", <<ptrToPrototype0, 5>,
  175. // <ptrToPrototype1, 35>,
  176. // <ptrToPrototype2, 79>>
  177. // ptrToPrototype1 has the following signature: <double, double>
  178. MapVector<StringRef, std::vector<std::pair<const Record *, unsigned>>>
  179. FctOverloadMap;
  180. // Contains the map of OpenCL types to their index in the TypeTable.
  181. MapVector<const Record *, unsigned> TypeMap;
  182. // List of OpenCL function extensions mapping extension strings to
  183. // an index into the FunctionExtensionTable.
  184. StringMap<unsigned> FunctionExtensionIndex;
  185. // List of OpenCL type names in the same order as in enum OpenCLTypeID.
  186. // This list does not contain generic types.
  187. std::vector<const Record *> TypeList;
  188. // Same as TypeList, but for generic types only.
  189. std::vector<const Record *> GenTypeList;
  190. // Map an ordered vector of signatures to their original Record instances,
  191. // and to a list of function names that share these signatures.
  192. //
  193. // For example, suppose the "cos" and "sin" functions have only three
  194. // signatures, and these signatures are at index Ix in the SignatureTable:
  195. // cos | sin | Signature | Index
  196. // float cos(float) | float sin(float) | Signature1 | I1
  197. // double cos(double) | double sin(double) | Signature2 | I2
  198. // half cos(half) | half sin(half) | Signature3 | I3
  199. //
  200. // Then we will create a mapping of the vector of signatures:
  201. // SignatureListMap[<I1, I2, I3>] = <
  202. // <"cos", "sin">,
  203. // <Signature1, Signature2, Signature3>>
  204. // The function "tan", having the same signatures, would be mapped to the
  205. // same entry (<I1, I2, I3>).
  206. MapVector<BuiltinIndexListTy *, BuiltinTableEntries> SignatureListMap;
  207. };
  208. /// Base class for emitting a file (e.g. header or test) from OpenCLBuiltins.td
  209. class OpenCLBuiltinFileEmitterBase {
  210. public:
  211. OpenCLBuiltinFileEmitterBase(RecordKeeper &Records, raw_ostream &OS)
  212. : Records(Records), OS(OS) {}
  213. virtual ~OpenCLBuiltinFileEmitterBase() = default;
  214. // Entrypoint to generate the functions for testing all OpenCL builtin
  215. // functions.
  216. virtual void emit() = 0;
  217. protected:
  218. struct TypeFlags {
  219. TypeFlags() : IsConst(false), IsVolatile(false), IsPointer(false) {}
  220. bool IsConst : 1;
  221. bool IsVolatile : 1;
  222. bool IsPointer : 1;
  223. StringRef AddrSpace;
  224. };
  225. // Return a string representation of the given type, such that it can be
  226. // used as a type in OpenCL C code.
  227. std::string getTypeString(const Record *Type, TypeFlags Flags,
  228. int VectorSize) const;
  229. // Return the type(s) and vector size(s) for the given type. For
  230. // non-GenericTypes, the resulting vectors will contain 1 element. For
  231. // GenericTypes, the resulting vectors typically contain multiple elements.
  232. void getTypeLists(Record *Type, TypeFlags &Flags,
  233. std::vector<Record *> &TypeList,
  234. std::vector<int64_t> &VectorList) const;
  235. // Expand the TableGen Records representing a builtin function signature into
  236. // one or more function signatures. Return them as a vector of a vector of
  237. // strings, with each string containing an OpenCL C type and optional
  238. // qualifiers.
  239. //
  240. // The Records may contain GenericTypes, which expand into multiple
  241. // signatures. Repeated occurrences of GenericType in a signature expand to
  242. // the same types. For example [char, FGenType, FGenType] expands to:
  243. // [char, float, float]
  244. // [char, float2, float2]
  245. // [char, float3, float3]
  246. // ...
  247. void
  248. expandTypesInSignature(const std::vector<Record *> &Signature,
  249. SmallVectorImpl<SmallVector<std::string, 2>> &Types);
  250. // Emit extension enabling pragmas.
  251. void emitExtensionSetup();
  252. // Emit an #if guard for a Builtin's extension. Return the corresponding
  253. // closing #endif, or an empty string if no extension #if guard was emitted.
  254. std::string emitExtensionGuard(const Record *Builtin);
  255. // Emit an #if guard for a Builtin's language version. Return the
  256. // corresponding closing #endif, or an empty string if no version #if guard
  257. // was emitted.
  258. std::string emitVersionGuard(const Record *Builtin);
  259. // Contains OpenCL builtin functions and related information, stored as
  260. // Record instances. They are coming from the associated TableGen file.
  261. RecordKeeper &Records;
  262. // The output file.
  263. raw_ostream &OS;
  264. };
  265. // OpenCL builtin test generator. This class processes the same TableGen input
  266. // as BuiltinNameEmitter, but generates a .cl file that contains a call to each
  267. // builtin function described in the .td input.
  268. class OpenCLBuiltinTestEmitter : public OpenCLBuiltinFileEmitterBase {
  269. public:
  270. OpenCLBuiltinTestEmitter(RecordKeeper &Records, raw_ostream &OS)
  271. : OpenCLBuiltinFileEmitterBase(Records, OS) {}
  272. // Entrypoint to generate the functions for testing all OpenCL builtin
  273. // functions.
  274. void emit() override;
  275. };
  276. } // namespace
  277. void BuiltinNameEmitter::Emit() {
  278. emitSourceFileHeader("OpenCL Builtin handling", OS);
  279. OS << "#include \"llvm/ADT/StringRef.h\"\n";
  280. OS << "using namespace clang;\n\n";
  281. // Emit enums and structs.
  282. EmitDeclarations();
  283. // Parse the Records to populate the internal lists.
  284. GetOverloads();
  285. GroupBySignature();
  286. // Emit tables.
  287. EmitExtensionTable();
  288. EmitTypeTable();
  289. EmitSignatureTable();
  290. EmitBuiltinTable();
  291. // Emit functions.
  292. EmitStringMatcher();
  293. EmitQualTypeFinder();
  294. }
  295. void BuiltinNameEmitter::ExtractEnumTypes(std::vector<Record *> &Types,
  296. StringMap<bool> &TypesSeen,
  297. std::string &Output,
  298. std::vector<const Record *> &List) {
  299. raw_string_ostream SS(Output);
  300. for (const auto *T : Types) {
  301. if (TypesSeen.find(T->getValueAsString("Name")) == TypesSeen.end()) {
  302. SS << " OCLT_" + T->getValueAsString("Name") << ",\n";
  303. // Save the type names in the same order as their enum value. Note that
  304. // the Record can be a VectorType or something else, only the name is
  305. // important.
  306. List.push_back(T);
  307. TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true));
  308. }
  309. }
  310. SS.flush();
  311. }
  312. void BuiltinNameEmitter::EmitDeclarations() {
  313. // Enum of scalar type names (float, int, ...) and generic type sets.
  314. OS << "enum OpenCLTypeID {\n";
  315. StringMap<bool> TypesSeen;
  316. std::string GenTypeEnums;
  317. std::string TypeEnums;
  318. // Extract generic types and non-generic types separately, to keep
  319. // gentypes at the end of the enum which simplifies the special handling
  320. // for gentypes in SemaLookup.
  321. std::vector<Record *> GenTypes =
  322. Records.getAllDerivedDefinitions("GenericType");
  323. ExtractEnumTypes(GenTypes, TypesSeen, GenTypeEnums, GenTypeList);
  324. std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
  325. ExtractEnumTypes(Types, TypesSeen, TypeEnums, TypeList);
  326. OS << TypeEnums;
  327. OS << GenTypeEnums;
  328. OS << "};\n";
  329. // Structure definitions.
  330. OS << R"(
  331. // Image access qualifier.
  332. enum OpenCLAccessQual : unsigned char {
  333. OCLAQ_None,
  334. OCLAQ_ReadOnly,
  335. OCLAQ_WriteOnly,
  336. OCLAQ_ReadWrite
  337. };
  338. // Represents a return type or argument type.
  339. struct OpenCLTypeStruct {
  340. // A type (e.g. float, int, ...).
  341. const OpenCLTypeID ID;
  342. // Vector size (if applicable; 0 for scalars and generic types).
  343. const unsigned VectorWidth;
  344. // 0 if the type is not a pointer.
  345. const bool IsPointer : 1;
  346. // 0 if the type is not const.
  347. const bool IsConst : 1;
  348. // 0 if the type is not volatile.
  349. const bool IsVolatile : 1;
  350. // Access qualifier.
  351. const OpenCLAccessQual AccessQualifier;
  352. // Address space of the pointer (if applicable).
  353. const LangAS AS;
  354. };
  355. // One overload of an OpenCL builtin function.
  356. struct OpenCLBuiltinStruct {
  357. // Index of the signature in the OpenCLTypeStruct table.
  358. const unsigned SigTableIndex;
  359. // Entries between index SigTableIndex and (SigTableIndex + NumTypes - 1) in
  360. // the SignatureTable represent the complete signature. The first type at
  361. // index SigTableIndex is the return type.
  362. const unsigned NumTypes;
  363. // Function attribute __attribute__((pure))
  364. const bool IsPure : 1;
  365. // Function attribute __attribute__((const))
  366. const bool IsConst : 1;
  367. // Function attribute __attribute__((convergent))
  368. const bool IsConv : 1;
  369. // OpenCL extension(s) required for this overload.
  370. const unsigned short Extension;
  371. // OpenCL versions in which this overload is available.
  372. const unsigned short Versions;
  373. };
  374. )";
  375. }
  376. // Verify that the combination of GenTypes in a signature is supported.
  377. // To simplify the logic for creating overloads in SemaLookup, only allow
  378. // a signature to contain different GenTypes if these GenTypes represent
  379. // the same number of actual scalar or vector types.
  380. //
  381. // Exit with a fatal error if an unsupported construct is encountered.
  382. static void VerifySignature(const std::vector<Record *> &Signature,
  383. const Record *BuiltinRec) {
  384. unsigned GenTypeVecSizes = 1;
  385. unsigned GenTypeTypes = 1;
  386. for (const auto *T : Signature) {
  387. // Check all GenericType arguments in this signature.
  388. if (T->isSubClassOf("GenericType")) {
  389. // Check number of vector sizes.
  390. unsigned NVecSizes =
  391. T->getValueAsDef("VectorList")->getValueAsListOfInts("List").size();
  392. if (NVecSizes != GenTypeVecSizes && NVecSizes != 1) {
  393. if (GenTypeVecSizes > 1) {
  394. // We already saw a gentype with a different number of vector sizes.
  395. PrintFatalError(BuiltinRec->getLoc(),
  396. "number of vector sizes should be equal or 1 for all gentypes "
  397. "in a declaration");
  398. }
  399. GenTypeVecSizes = NVecSizes;
  400. }
  401. // Check number of data types.
  402. unsigned NTypes =
  403. T->getValueAsDef("TypeList")->getValueAsListOfDefs("List").size();
  404. if (NTypes != GenTypeTypes && NTypes != 1) {
  405. if (GenTypeTypes > 1) {
  406. // We already saw a gentype with a different number of types.
  407. PrintFatalError(BuiltinRec->getLoc(),
  408. "number of types should be equal or 1 for all gentypes "
  409. "in a declaration");
  410. }
  411. GenTypeTypes = NTypes;
  412. }
  413. }
  414. }
  415. }
  416. void BuiltinNameEmitter::GetOverloads() {
  417. // Populate the TypeMap.
  418. std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
  419. unsigned I = 0;
  420. for (const auto &T : Types) {
  421. TypeMap.insert(std::make_pair(T, I++));
  422. }
  423. // Populate the SignaturesList and the FctOverloadMap.
  424. unsigned CumulativeSignIndex = 0;
  425. std::vector<Record *> Builtins = Records.getAllDerivedDefinitions("Builtin");
  426. for (const auto *B : Builtins) {
  427. StringRef BName = B->getValueAsString("Name");
  428. if (FctOverloadMap.find(BName) == FctOverloadMap.end()) {
  429. FctOverloadMap.insert(std::make_pair(
  430. BName, std::vector<std::pair<const Record *, unsigned>>{}));
  431. }
  432. auto Signature = B->getValueAsListOfDefs("Signature");
  433. // Reuse signatures to avoid unnecessary duplicates.
  434. auto it =
  435. llvm::find_if(SignaturesList,
  436. [&](const std::pair<std::vector<Record *>, unsigned> &a) {
  437. return a.first == Signature;
  438. });
  439. unsigned SignIndex;
  440. if (it == SignaturesList.end()) {
  441. VerifySignature(Signature, B);
  442. SignaturesList.push_back(std::make_pair(Signature, CumulativeSignIndex));
  443. SignIndex = CumulativeSignIndex;
  444. CumulativeSignIndex += Signature.size();
  445. } else {
  446. SignIndex = it->second;
  447. }
  448. FctOverloadMap[BName].push_back(std::make_pair(B, SignIndex));
  449. }
  450. }
  451. void BuiltinNameEmitter::EmitExtensionTable() {
  452. OS << "static const char *FunctionExtensionTable[] = {\n";
  453. unsigned Index = 0;
  454. std::vector<Record *> FuncExtensions =
  455. Records.getAllDerivedDefinitions("FunctionExtension");
  456. for (const auto &FE : FuncExtensions) {
  457. // Emit OpenCL extension table entry.
  458. OS << " // " << Index << ": " << FE->getName() << "\n"
  459. << " \"" << FE->getValueAsString("ExtName") << "\",\n";
  460. // Record index of this extension.
  461. FunctionExtensionIndex[FE->getName()] = Index++;
  462. }
  463. OS << "};\n\n";
  464. }
  465. void BuiltinNameEmitter::EmitTypeTable() {
  466. OS << "static const OpenCLTypeStruct TypeTable[] = {\n";
  467. for (const auto &T : TypeMap) {
  468. const char *AccessQual =
  469. StringSwitch<const char *>(T.first->getValueAsString("AccessQualifier"))
  470. .Case("RO", "OCLAQ_ReadOnly")
  471. .Case("WO", "OCLAQ_WriteOnly")
  472. .Case("RW", "OCLAQ_ReadWrite")
  473. .Default("OCLAQ_None");
  474. OS << " // " << T.second << "\n"
  475. << " {OCLT_" << T.first->getValueAsString("Name") << ", "
  476. << T.first->getValueAsInt("VecWidth") << ", "
  477. << T.first->getValueAsBit("IsPointer") << ", "
  478. << T.first->getValueAsBit("IsConst") << ", "
  479. << T.first->getValueAsBit("IsVolatile") << ", "
  480. << AccessQual << ", "
  481. << T.first->getValueAsString("AddrSpace") << "},\n";
  482. }
  483. OS << "};\n\n";
  484. }
  485. void BuiltinNameEmitter::EmitSignatureTable() {
  486. // Store a type (e.g. int, float, int2, ...). The type is stored as an index
  487. // of a struct OpenCLType table. Multiple entries following each other form a
  488. // signature.
  489. OS << "static const unsigned short SignatureTable[] = {\n";
  490. for (const auto &P : SignaturesList) {
  491. OS << " // " << P.second << "\n ";
  492. for (const Record *R : P.first) {
  493. unsigned Entry = TypeMap.find(R)->second;
  494. if (Entry > USHRT_MAX) {
  495. // Report an error when seeing an entry that is too large for the
  496. // current index type (unsigned short). When hitting this, the type
  497. // of SignatureTable will need to be changed.
  498. PrintFatalError("Entry in SignatureTable exceeds limit.");
  499. }
  500. OS << Entry << ", ";
  501. }
  502. OS << "\n";
  503. }
  504. OS << "};\n\n";
  505. }
  506. // Encode a range MinVersion..MaxVersion into a single bit mask that can be
  507. // checked against LangOpts using isOpenCLVersionContainedInMask().
  508. // This must be kept in sync with OpenCLVersionID in OpenCLOptions.h.
  509. // (Including OpenCLOptions.h here would be a layering violation.)
  510. static unsigned short EncodeVersions(unsigned int MinVersion,
  511. unsigned int MaxVersion) {
  512. unsigned short Encoded = 0;
  513. // A maximum version of 0 means available in all later versions.
  514. if (MaxVersion == 0) {
  515. MaxVersion = UINT_MAX;
  516. }
  517. unsigned VersionIDs[] = {100, 110, 120, 200, 300};
  518. for (unsigned I = 0; I < sizeof(VersionIDs) / sizeof(VersionIDs[0]); I++) {
  519. if (VersionIDs[I] >= MinVersion && VersionIDs[I] < MaxVersion) {
  520. Encoded |= 1 << I;
  521. }
  522. }
  523. return Encoded;
  524. }
  525. void BuiltinNameEmitter::EmitBuiltinTable() {
  526. unsigned Index = 0;
  527. OS << "static const OpenCLBuiltinStruct BuiltinTable[] = {\n";
  528. for (const auto &SLM : SignatureListMap) {
  529. OS << " // " << (Index + 1) << ": ";
  530. for (const auto &Name : SLM.second.Names) {
  531. OS << Name << ", ";
  532. }
  533. OS << "\n";
  534. for (const auto &Overload : SLM.second.Signatures) {
  535. StringRef ExtName = Overload.first->getValueAsDef("Extension")->getName();
  536. unsigned int MinVersion =
  537. Overload.first->getValueAsDef("MinVersion")->getValueAsInt("ID");
  538. unsigned int MaxVersion =
  539. Overload.first->getValueAsDef("MaxVersion")->getValueAsInt("ID");
  540. OS << " { " << Overload.second << ", "
  541. << Overload.first->getValueAsListOfDefs("Signature").size() << ", "
  542. << (Overload.first->getValueAsBit("IsPure")) << ", "
  543. << (Overload.first->getValueAsBit("IsConst")) << ", "
  544. << (Overload.first->getValueAsBit("IsConv")) << ", "
  545. << FunctionExtensionIndex[ExtName] << ", "
  546. << EncodeVersions(MinVersion, MaxVersion) << " },\n";
  547. Index++;
  548. }
  549. }
  550. OS << "};\n\n";
  551. }
  552. bool BuiltinNameEmitter::CanReuseSignature(
  553. BuiltinIndexListTy *Candidate,
  554. std::vector<std::pair<const Record *, unsigned>> &SignatureList) {
  555. assert(Candidate->size() == SignatureList.size() &&
  556. "signature lists should have the same size");
  557. auto &CandidateSigs =
  558. SignatureListMap.find(Candidate)->second.Signatures;
  559. for (unsigned Index = 0; Index < Candidate->size(); Index++) {
  560. const Record *Rec = SignatureList[Index].first;
  561. const Record *Rec2 = CandidateSigs[Index].first;
  562. if (Rec->getValueAsBit("IsPure") == Rec2->getValueAsBit("IsPure") &&
  563. Rec->getValueAsBit("IsConst") == Rec2->getValueAsBit("IsConst") &&
  564. Rec->getValueAsBit("IsConv") == Rec2->getValueAsBit("IsConv") &&
  565. Rec->getValueAsDef("MinVersion")->getValueAsInt("ID") ==
  566. Rec2->getValueAsDef("MinVersion")->getValueAsInt("ID") &&
  567. Rec->getValueAsDef("MaxVersion")->getValueAsInt("ID") ==
  568. Rec2->getValueAsDef("MaxVersion")->getValueAsInt("ID") &&
  569. Rec->getValueAsDef("Extension")->getName() ==
  570. Rec2->getValueAsDef("Extension")->getName()) {
  571. return true;
  572. }
  573. }
  574. return false;
  575. }
  576. void BuiltinNameEmitter::GroupBySignature() {
  577. // List of signatures known to be emitted.
  578. std::vector<BuiltinIndexListTy *> KnownSignatures;
  579. for (auto &Fct : FctOverloadMap) {
  580. bool FoundReusableSig = false;
  581. // Gather all signatures for the current function.
  582. auto *CurSignatureList = new BuiltinIndexListTy();
  583. for (const auto &Signature : Fct.second) {
  584. CurSignatureList->push_back(Signature.second);
  585. }
  586. // Sort the list to facilitate future comparisons.
  587. llvm::sort(*CurSignatureList);
  588. // Check if we have already seen another function with the same list of
  589. // signatures. If so, just add the name of the function.
  590. for (auto *Candidate : KnownSignatures) {
  591. if (Candidate->size() == CurSignatureList->size() &&
  592. *Candidate == *CurSignatureList) {
  593. if (CanReuseSignature(Candidate, Fct.second)) {
  594. SignatureListMap.find(Candidate)->second.Names.push_back(Fct.first);
  595. FoundReusableSig = true;
  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. for (auto *I : KnownSignatures) {
  609. delete I;
  610. }
  611. }
  612. void BuiltinNameEmitter::EmitStringMatcher() {
  613. std::vector<StringMatcher::StringPair> ValidBuiltins;
  614. unsigned CumulativeIndex = 1;
  615. for (const auto &SLM : SignatureListMap) {
  616. const auto &Ovl = SLM.second.Signatures;
  617. // A single signature list may be used by different builtins. Return the
  618. // same <index, length> pair for each of those builtins.
  619. for (const auto &FctName : SLM.second.Names) {
  620. std::string RetStmt;
  621. raw_string_ostream SS(RetStmt);
  622. SS << "return std::make_pair(" << CumulativeIndex << ", " << Ovl.size()
  623. << ");";
  624. SS.flush();
  625. ValidBuiltins.push_back(
  626. StringMatcher::StringPair(std::string(FctName), RetStmt));
  627. }
  628. CumulativeIndex += Ovl.size();
  629. }
  630. OS << R"(
  631. // Find out whether a string matches an existing OpenCL builtin function name.
  632. // Returns: A pair <0, 0> if no name matches.
  633. // A pair <Index, Len> indexing the BuiltinTable if the name is
  634. // matching an OpenCL builtin function.
  635. static std::pair<unsigned, unsigned> isOpenCLBuiltin(llvm::StringRef Name) {
  636. )";
  637. StringMatcher("Name", ValidBuiltins, OS).Emit(0, true);
  638. OS << " return std::make_pair(0, 0);\n";
  639. OS << "} // isOpenCLBuiltin\n";
  640. }
  641. void BuiltinNameEmitter::EmitQualTypeFinder() {
  642. OS << R"(
  643. static QualType getOpenCLEnumType(Sema &S, llvm::StringRef Name);
  644. static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name);
  645. // Convert an OpenCLTypeStruct type to a list of QualTypes.
  646. // Generic types represent multiple types and vector sizes, thus a vector
  647. // is returned. The conversion is done in two steps:
  648. // Step 1: A switch statement fills a vector with scalar base types for the
  649. // Cartesian product of (vector sizes) x (types) for generic types,
  650. // or a single scalar type for non generic types.
  651. // Step 2: Qualifiers and other type properties such as vector size are
  652. // applied.
  653. static void OCL2Qual(Sema &S, const OpenCLTypeStruct &Ty,
  654. llvm::SmallVectorImpl<QualType> &QT) {
  655. ASTContext &Context = S.Context;
  656. // Number of scalar types in the GenType.
  657. unsigned GenTypeNumTypes;
  658. // Pointer to the list of vector sizes for the GenType.
  659. llvm::ArrayRef<unsigned> GenVectorSizes;
  660. )";
  661. // Generate list of vector sizes for each generic type.
  662. for (const auto *VectList : Records.getAllDerivedDefinitions("IntList")) {
  663. OS << " constexpr unsigned List"
  664. << VectList->getValueAsString("Name") << "[] = {";
  665. for (const auto V : VectList->getValueAsListOfInts("List")) {
  666. OS << V << ", ";
  667. }
  668. OS << "};\n";
  669. }
  670. // Step 1.
  671. // Start of switch statement over all types.
  672. OS << "\n switch (Ty.ID) {\n";
  673. // Switch cases for image types (Image2d, Image3d, ...)
  674. std::vector<Record *> ImageTypes =
  675. Records.getAllDerivedDefinitions("ImageType");
  676. // Map an image type name to its 3 access-qualified types (RO, WO, RW).
  677. StringMap<SmallVector<Record *, 3>> ImageTypesMap;
  678. for (auto *IT : ImageTypes) {
  679. auto Entry = ImageTypesMap.find(IT->getValueAsString("Name"));
  680. if (Entry == ImageTypesMap.end()) {
  681. SmallVector<Record *, 3> ImageList;
  682. ImageList.push_back(IT);
  683. ImageTypesMap.insert(
  684. std::make_pair(IT->getValueAsString("Name"), ImageList));
  685. } else {
  686. Entry->second.push_back(IT);
  687. }
  688. }
  689. // Emit the cases for the image types. For an image type name, there are 3
  690. // corresponding QualTypes ("RO", "WO", "RW"). The "AccessQualifier" field
  691. // tells which one is needed. Emit a switch statement that puts the
  692. // corresponding QualType into "QT".
  693. for (const auto &ITE : ImageTypesMap) {
  694. OS << " case OCLT_" << ITE.getKey() << ":\n"
  695. << " switch (Ty.AccessQualifier) {\n"
  696. << " case OCLAQ_None:\n"
  697. << " llvm_unreachable(\"Image without access qualifier\");\n";
  698. for (const auto &Image : ITE.getValue()) {
  699. OS << StringSwitch<const char *>(
  700. Image->getValueAsString("AccessQualifier"))
  701. .Case("RO", " case OCLAQ_ReadOnly:\n")
  702. .Case("WO", " case OCLAQ_WriteOnly:\n")
  703. .Case("RW", " case OCLAQ_ReadWrite:\n")
  704. << " QT.push_back("
  705. << Image->getValueAsDef("QTExpr")->getValueAsString("TypeExpr")
  706. << ");\n"
  707. << " break;\n";
  708. }
  709. OS << " }\n"
  710. << " break;\n";
  711. }
  712. // Switch cases for generic types.
  713. for (const auto *GenType : Records.getAllDerivedDefinitions("GenericType")) {
  714. OS << " case OCLT_" << GenType->getValueAsString("Name") << ": {\n";
  715. // Build the Cartesian product of (vector sizes) x (types). Only insert
  716. // the plain scalar types for now; other type information such as vector
  717. // size and type qualifiers will be added after the switch statement.
  718. std::vector<Record *> BaseTypes =
  719. GenType->getValueAsDef("TypeList")->getValueAsListOfDefs("List");
  720. // Collect all QualTypes for a single vector size into TypeList.
  721. OS << " SmallVector<QualType, " << BaseTypes.size() << "> TypeList;\n";
  722. for (const auto *T : BaseTypes) {
  723. StringRef Ext =
  724. T->getValueAsDef("Extension")->getValueAsString("ExtName");
  725. if (!Ext.empty()) {
  726. OS << " if (S.getPreprocessor().isMacroDefined(\"" << Ext
  727. << "\")) {\n ";
  728. }
  729. OS << " TypeList.push_back("
  730. << T->getValueAsDef("QTExpr")->getValueAsString("TypeExpr") << ");\n";
  731. if (!Ext.empty()) {
  732. OS << " }\n";
  733. }
  734. }
  735. OS << " GenTypeNumTypes = TypeList.size();\n";
  736. // Duplicate the TypeList for every vector size.
  737. std::vector<int64_t> VectorList =
  738. GenType->getValueAsDef("VectorList")->getValueAsListOfInts("List");
  739. OS << " QT.reserve(" << VectorList.size() * BaseTypes.size() << ");\n"
  740. << " for (unsigned I = 0; I < " << VectorList.size() << "; I++) {\n"
  741. << " QT.append(TypeList);\n"
  742. << " }\n";
  743. // GenVectorSizes is the list of vector sizes for this GenType.
  744. OS << " GenVectorSizes = List"
  745. << GenType->getValueAsDef("VectorList")->getValueAsString("Name")
  746. << ";\n"
  747. << " break;\n"
  748. << " }\n";
  749. }
  750. // Switch cases for non generic, non image types (int, int4, float, ...).
  751. // Only insert the plain scalar type; vector information and type qualifiers
  752. // are added in step 2.
  753. std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
  754. StringMap<bool> TypesSeen;
  755. for (const auto *T : Types) {
  756. // Check this is not an image type
  757. if (ImageTypesMap.find(T->getValueAsString("Name")) != ImageTypesMap.end())
  758. continue;
  759. // Check we have not seen this Type
  760. if (TypesSeen.find(T->getValueAsString("Name")) != TypesSeen.end())
  761. continue;
  762. TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true));
  763. // Check the Type does not have an "abstract" QualType
  764. auto QT = T->getValueAsDef("QTExpr");
  765. if (QT->getValueAsBit("IsAbstract") == 1)
  766. continue;
  767. // Emit the cases for non generic, non image types.
  768. OS << " case OCLT_" << T->getValueAsString("Name") << ":\n";
  769. StringRef Ext = T->getValueAsDef("Extension")->getValueAsString("ExtName");
  770. // If this type depends on an extension, ensure the extension macro is
  771. // defined.
  772. if (!Ext.empty()) {
  773. OS << " if (S.getPreprocessor().isMacroDefined(\"" << Ext
  774. << "\")) {\n ";
  775. }
  776. OS << " QT.push_back(" << QT->getValueAsString("TypeExpr") << ");\n";
  777. if (!Ext.empty()) {
  778. OS << " }\n";
  779. }
  780. OS << " break;\n";
  781. }
  782. // End of switch statement.
  783. OS << " } // end of switch (Ty.ID)\n\n";
  784. // Step 2.
  785. // Add ExtVector types if this was a generic type, as the switch statement
  786. // above only populated the list with scalar types. This completes the
  787. // construction of the Cartesian product of (vector sizes) x (types).
  788. OS << " // Construct the different vector types for each generic type.\n";
  789. OS << " if (Ty.ID >= " << TypeList.size() << ") {";
  790. OS << R"(
  791. for (unsigned I = 0; I < QT.size(); I++) {
  792. // For scalars, size is 1.
  793. if (GenVectorSizes[I / GenTypeNumTypes] != 1) {
  794. QT[I] = Context.getExtVectorType(QT[I],
  795. GenVectorSizes[I / GenTypeNumTypes]);
  796. }
  797. }
  798. }
  799. )";
  800. // Assign the right attributes to the types (e.g. vector size).
  801. OS << R"(
  802. // Set vector size for non-generic vector types.
  803. if (Ty.VectorWidth > 1) {
  804. for (unsigned Index = 0; Index < QT.size(); Index++) {
  805. QT[Index] = Context.getExtVectorType(QT[Index], Ty.VectorWidth);
  806. }
  807. }
  808. if (Ty.IsVolatile != 0) {
  809. for (unsigned Index = 0; Index < QT.size(); Index++) {
  810. QT[Index] = Context.getVolatileType(QT[Index]);
  811. }
  812. }
  813. if (Ty.IsConst != 0) {
  814. for (unsigned Index = 0; Index < QT.size(); Index++) {
  815. QT[Index] = Context.getConstType(QT[Index]);
  816. }
  817. }
  818. // Transform the type to a pointer as the last step, if necessary.
  819. // Builtin functions only have pointers on [const|volatile], no
  820. // [const|volatile] pointers, so this is ok to do it as a last step.
  821. if (Ty.IsPointer != 0) {
  822. for (unsigned Index = 0; Index < QT.size(); Index++) {
  823. QT[Index] = Context.getAddrSpaceQualType(QT[Index], Ty.AS);
  824. QT[Index] = Context.getPointerType(QT[Index]);
  825. }
  826. }
  827. )";
  828. // End of the "OCL2Qual" function.
  829. OS << "\n} // OCL2Qual\n";
  830. }
  831. std::string OpenCLBuiltinFileEmitterBase::getTypeString(const Record *Type,
  832. TypeFlags Flags,
  833. int VectorSize) const {
  834. std::string S;
  835. if (Type->getValueAsBit("IsConst") || Flags.IsConst) {
  836. S += "const ";
  837. }
  838. if (Type->getValueAsBit("IsVolatile") || Flags.IsVolatile) {
  839. S += "volatile ";
  840. }
  841. auto PrintAddrSpace = [&S](StringRef AddrSpace) {
  842. S += StringSwitch<const char *>(AddrSpace)
  843. .Case("clang::LangAS::opencl_private", "__private")
  844. .Case("clang::LangAS::opencl_global", "__global")
  845. .Case("clang::LangAS::opencl_constant", "__constant")
  846. .Case("clang::LangAS::opencl_local", "__local")
  847. .Case("clang::LangAS::opencl_generic", "__generic")
  848. .Default("__private");
  849. S += " ";
  850. };
  851. if (Flags.IsPointer) {
  852. PrintAddrSpace(Flags.AddrSpace);
  853. } else if (Type->getValueAsBit("IsPointer")) {
  854. PrintAddrSpace(Type->getValueAsString("AddrSpace"));
  855. }
  856. StringRef Acc = Type->getValueAsString("AccessQualifier");
  857. if (Acc != "") {
  858. S += StringSwitch<const char *>(Acc)
  859. .Case("RO", "__read_only ")
  860. .Case("WO", "__write_only ")
  861. .Case("RW", "__read_write ");
  862. }
  863. S += Type->getValueAsString("Name").str();
  864. if (VectorSize > 1) {
  865. S += std::to_string(VectorSize);
  866. }
  867. if (Type->getValueAsBit("IsPointer") || Flags.IsPointer) {
  868. S += " *";
  869. }
  870. return S;
  871. }
  872. void OpenCLBuiltinFileEmitterBase::getTypeLists(
  873. Record *Type, TypeFlags &Flags, std::vector<Record *> &TypeList,
  874. std::vector<int64_t> &VectorList) const {
  875. bool isGenType = Type->isSubClassOf("GenericType");
  876. if (isGenType) {
  877. TypeList = Type->getValueAsDef("TypeList")->getValueAsListOfDefs("List");
  878. VectorList =
  879. Type->getValueAsDef("VectorList")->getValueAsListOfInts("List");
  880. return;
  881. }
  882. if (Type->isSubClassOf("PointerType") || Type->isSubClassOf("ConstType") ||
  883. Type->isSubClassOf("VolatileType")) {
  884. StringRef SubTypeName = Type->getValueAsString("Name");
  885. Record *PossibleGenType = Records.getDef(SubTypeName);
  886. if (PossibleGenType && PossibleGenType->isSubClassOf("GenericType")) {
  887. // When PointerType, ConstType, or VolatileType is applied to a
  888. // GenericType, the flags need to be taken from the subtype, not from the
  889. // GenericType.
  890. Flags.IsPointer = Type->getValueAsBit("IsPointer");
  891. Flags.IsConst = Type->getValueAsBit("IsConst");
  892. Flags.IsVolatile = Type->getValueAsBit("IsVolatile");
  893. Flags.AddrSpace = Type->getValueAsString("AddrSpace");
  894. getTypeLists(PossibleGenType, Flags, TypeList, VectorList);
  895. return;
  896. }
  897. }
  898. // Not a GenericType, so just insert the single type.
  899. TypeList.push_back(Type);
  900. VectorList.push_back(Type->getValueAsInt("VecWidth"));
  901. }
  902. void OpenCLBuiltinFileEmitterBase::expandTypesInSignature(
  903. const std::vector<Record *> &Signature,
  904. SmallVectorImpl<SmallVector<std::string, 2>> &Types) {
  905. // Find out if there are any GenTypes in this signature, and if so, calculate
  906. // into how many signatures they will expand.
  907. unsigned NumSignatures = 1;
  908. SmallVector<SmallVector<std::string, 4>, 4> ExpandedGenTypes;
  909. for (const auto &Arg : Signature) {
  910. SmallVector<std::string, 4> ExpandedArg;
  911. std::vector<Record *> TypeList;
  912. std::vector<int64_t> VectorList;
  913. TypeFlags Flags;
  914. getTypeLists(Arg, Flags, TypeList, VectorList);
  915. // Insert the Cartesian product of the types and vector sizes.
  916. for (const auto &Vector : VectorList) {
  917. for (const auto &Type : TypeList) {
  918. ExpandedArg.push_back(getTypeString(Type, Flags, Vector));
  919. }
  920. }
  921. NumSignatures = std::max<unsigned>(NumSignatures, ExpandedArg.size());
  922. ExpandedGenTypes.push_back(ExpandedArg);
  923. }
  924. // Now the total number of signatures is known. Populate the return list with
  925. // all signatures.
  926. for (unsigned I = 0; I < NumSignatures; I++) {
  927. SmallVector<std::string, 2> Args;
  928. // Process a single signature.
  929. for (unsigned ArgNum = 0; ArgNum < Signature.size(); ArgNum++) {
  930. // For differently-sized GenTypes in a parameter list, the smaller
  931. // GenTypes just repeat, so index modulo the number of expanded types.
  932. size_t TypeIndex = I % ExpandedGenTypes[ArgNum].size();
  933. Args.push_back(ExpandedGenTypes[ArgNum][TypeIndex]);
  934. }
  935. Types.push_back(Args);
  936. }
  937. }
  938. void OpenCLBuiltinFileEmitterBase::emitExtensionSetup() {
  939. OS << R"(
  940. #pragma OPENCL EXTENSION cl_khr_fp16 : enable
  941. #pragma OPENCL EXTENSION cl_khr_fp64 : enable
  942. #pragma OPENCL EXTENSION cl_khr_int64_base_atomics : enable
  943. #pragma OPENCL EXTENSION cl_khr_int64_extended_atomics : enable
  944. #pragma OPENCL EXTENSION cl_khr_gl_msaa_sharing : enable
  945. #pragma OPENCL EXTENSION cl_khr_mipmap_image_writes : enable
  946. #pragma OPENCL EXTENSION cl_khr_3d_image_writes : enable
  947. )";
  948. }
  949. std::string
  950. OpenCLBuiltinFileEmitterBase::emitExtensionGuard(const Record *Builtin) {
  951. StringRef Extensions =
  952. Builtin->getValueAsDef("Extension")->getValueAsString("ExtName");
  953. if (Extensions.empty())
  954. return "";
  955. OS << "#if";
  956. SmallVector<StringRef, 2> ExtVec;
  957. Extensions.split(ExtVec, " ");
  958. bool isFirst = true;
  959. for (StringRef Ext : ExtVec) {
  960. if (!isFirst) {
  961. OS << " &&";
  962. }
  963. OS << " defined(" << Ext << ")";
  964. isFirst = false;
  965. }
  966. OS << "\n";
  967. return "#endif // Extension\n";
  968. }
  969. std::string
  970. OpenCLBuiltinFileEmitterBase::emitVersionGuard(const Record *Builtin) {
  971. std::string OptionalEndif;
  972. auto PrintOpenCLVersion = [this](int Version) {
  973. OS << "CL_VERSION_" << (Version / 100) << "_" << ((Version % 100) / 10);
  974. };
  975. int MinVersion = Builtin->getValueAsDef("MinVersion")->getValueAsInt("ID");
  976. if (MinVersion != 100) {
  977. // OpenCL 1.0 is the default minimum version.
  978. OS << "#if __OPENCL_C_VERSION__ >= ";
  979. PrintOpenCLVersion(MinVersion);
  980. OS << "\n";
  981. OptionalEndif = "#endif // MinVersion\n" + OptionalEndif;
  982. }
  983. int MaxVersion = Builtin->getValueAsDef("MaxVersion")->getValueAsInt("ID");
  984. if (MaxVersion) {
  985. OS << "#if __OPENCL_C_VERSION__ < ";
  986. PrintOpenCLVersion(MaxVersion);
  987. OS << "\n";
  988. OptionalEndif = "#endif // MaxVersion\n" + OptionalEndif;
  989. }
  990. return OptionalEndif;
  991. }
  992. void OpenCLBuiltinTestEmitter::emit() {
  993. emitSourceFileHeader("OpenCL Builtin exhaustive testing", OS);
  994. emitExtensionSetup();
  995. // Ensure each test has a unique name by numbering them.
  996. unsigned TestID = 0;
  997. // Iterate over all builtins.
  998. std::vector<Record *> Builtins = Records.getAllDerivedDefinitions("Builtin");
  999. for (const auto *B : Builtins) {
  1000. StringRef Name = B->getValueAsString("Name");
  1001. SmallVector<SmallVector<std::string, 2>, 4> FTypes;
  1002. expandTypesInSignature(B->getValueAsListOfDefs("Signature"), FTypes);
  1003. OS << "// Test " << Name << "\n";
  1004. std::string OptionalExtensionEndif = emitExtensionGuard(B);
  1005. std::string OptionalVersionEndif = emitVersionGuard(B);
  1006. for (const auto &Signature : FTypes) {
  1007. // Emit function declaration.
  1008. OS << Signature[0] << " test" << TestID++ << "_" << Name << "(";
  1009. if (Signature.size() > 1) {
  1010. for (unsigned I = 1; I < Signature.size(); I++) {
  1011. if (I != 1)
  1012. OS << ", ";
  1013. OS << Signature[I] << " arg" << I;
  1014. }
  1015. }
  1016. OS << ") {\n";
  1017. // Emit function body.
  1018. OS << " ";
  1019. if (Signature[0] != "void") {
  1020. OS << "return ";
  1021. }
  1022. OS << Name << "(";
  1023. for (unsigned I = 1; I < Signature.size(); I++) {
  1024. if (I != 1)
  1025. OS << ", ";
  1026. OS << "arg" << I;
  1027. }
  1028. OS << ");\n";
  1029. // End of function body.
  1030. OS << "}\n";
  1031. }
  1032. OS << OptionalVersionEndif;
  1033. OS << OptionalExtensionEndif;
  1034. }
  1035. }
  1036. void clang::EmitClangOpenCLBuiltins(RecordKeeper &Records, raw_ostream &OS) {
  1037. BuiltinNameEmitter NameChecker(Records, OS);
  1038. NameChecker.Emit();
  1039. }
  1040. void clang::EmitClangOpenCLBuiltinTests(RecordKeeper &Records,
  1041. raw_ostream &OS) {
  1042. OpenCLBuiltinTestEmitter TestFileGenerator(Records, OS);
  1043. TestFileGenerator.emit();
  1044. }