b3OpenCLUtils.cpp 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  1. /*
  2. Bullet Continuous Collision Detection and Physics Library, http://bulletphysics.org
  3. Copyright (C) 2006 - 2011 Sony Computer Entertainment Inc.
  4. This software is provided 'as-is', without any express or implied warranty.
  5. In no event will the authors be held liable for any damages arising from the use of this software.
  6. Permission is granted to anyone to use this software for any purpose,
  7. including commercial applications, and to alter it and redistribute it freely,
  8. subject to the following restrictions:
  9. 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
  10. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  11. 3. This notice may not be removed or altered from any source distribution.
  12. */
  13. //Original author: Roman Ponomarev
  14. //Mostly Reimplemented by Erwin Coumans
  15. bool gDebugForceLoadingFromSource = false;
  16. bool gDebugSkipLoadingBinary = false;
  17. #include "Bullet3Common/b3Logging.h"
  18. #include <string.h>
  19. #ifdef _WIN32
  20. #pragma warning (disable:4996)
  21. #endif
  22. #include "b3OpenCLUtils.h"
  23. //#include "b3OpenCLInclude.h"
  24. #include <stdio.h>
  25. #include <stdlib.h>
  26. #define B3_MAX_CL_DEVICES 16 //who needs 16 devices?
  27. #ifdef _WIN32
  28. #include <windows.h>
  29. #endif
  30. #include <assert.h>
  31. #define b3Assert assert
  32. #ifndef _WIN32
  33. #include <sys/stat.h>
  34. #endif
  35. static const char* sCachedBinaryPath="cache";
  36. //Set the preferred platform vendor using the OpenCL SDK
  37. static const char* spPlatformVendor =
  38. #if defined(CL_PLATFORM_MINI_CL)
  39. "MiniCL, SCEA";
  40. #elif defined(CL_PLATFORM_AMD)
  41. "Advanced Micro Devices, Inc.";
  42. #elif defined(CL_PLATFORM_NVIDIA)
  43. "NVIDIA Corporation";
  44. #elif defined(CL_PLATFORM_INTEL)
  45. "Intel(R) Corporation";
  46. #elif defined(B3_USE_CLEW)
  47. "clew (OpenCL Extension Wrangler library)";
  48. #else
  49. "Unknown Vendor";
  50. #endif
  51. #ifndef CL_PLATFORM_MINI_CL
  52. #ifdef _WIN32
  53. #ifndef B3_USE_CLEW
  54. #include "CL/cl_gl.h"
  55. #endif //B3_USE_CLEW
  56. #endif //_WIN32
  57. #endif
  58. void MyFatalBreakAPPLE( const char * errstr ,
  59. const void * private_info ,
  60. size_t cb ,
  61. void * user_data )
  62. {
  63. const char* patloc = strstr(errstr, "Warning");
  64. //find out if it is a warning or error, exit if error
  65. if (patloc)
  66. {
  67. b3Warning("Warning: %s\n", errstr);
  68. } else
  69. {
  70. b3Error("Error: %s\n", errstr);
  71. b3Assert(0);
  72. }
  73. }
  74. #ifdef B3_USE_CLEW
  75. int b3OpenCLUtils_clewInit()
  76. {
  77. int result = -1;
  78. #ifdef _WIN32
  79. const char* cl = "OpenCL.dll";
  80. #elif defined __APPLE__
  81. const char* cl = "/System/Library/Frameworks/OpenCL.framework/Versions/Current/OpenCL";
  82. #else//presumable Linux?
  83. //linux (tested on Ubuntu 12.10 with Catalyst 13.4 beta drivers, not that there is no symbolic link from libOpenCL.so
  84. const char* cl = "libOpenCL.so.1";
  85. result = clewInit(cl);
  86. if (result != CLEW_SUCCESS)
  87. {
  88. cl = "libOpenCL.so";
  89. } else
  90. {
  91. clewExit();
  92. }
  93. #endif
  94. result = clewInit(cl);
  95. if (result!=CLEW_SUCCESS)
  96. {
  97. b3Error("clewInit failed with error code %d\n",result);
  98. }
  99. else
  100. {
  101. b3Printf("clewInit succesfull using %s\n",cl);
  102. }
  103. return result;
  104. }
  105. #endif
  106. int b3OpenCLUtils_getNumPlatforms(cl_int* pErrNum)
  107. {
  108. #ifdef B3_USE_CLEW
  109. b3OpenCLUtils_clewInit();
  110. #endif
  111. cl_platform_id pPlatforms[10] = { 0 };
  112. cl_uint numPlatforms = 0;
  113. cl_int ciErrNum = clGetPlatformIDs(10, pPlatforms, &numPlatforms);
  114. //cl_int ciErrNum = clGetPlatformIDs(0, NULL, &numPlatforms);
  115. if(ciErrNum != CL_SUCCESS)
  116. {
  117. if(pErrNum != NULL)
  118. *pErrNum = ciErrNum;
  119. }
  120. return numPlatforms;
  121. }
  122. const char* b3OpenCLUtils_getSdkVendorName()
  123. {
  124. return spPlatformVendor;
  125. }
  126. void b3OpenCLUtils_setCachePath(const char* path)
  127. {
  128. sCachedBinaryPath = path;
  129. }
  130. cl_platform_id b3OpenCLUtils_getPlatform(int platformIndex0, cl_int* pErrNum)
  131. {
  132. #ifdef B3_USE_CLEW
  133. b3OpenCLUtils_clewInit();
  134. #endif
  135. cl_platform_id platform = 0;
  136. unsigned int platformIndex = (unsigned int )platformIndex0;
  137. cl_uint numPlatforms;
  138. cl_int ciErrNum = clGetPlatformIDs(0, NULL, &numPlatforms);
  139. if (platformIndex<numPlatforms)
  140. {
  141. cl_platform_id* platforms = (cl_platform_id*) malloc (sizeof(cl_platform_id)*numPlatforms);
  142. ciErrNum = clGetPlatformIDs(numPlatforms, platforms, NULL);
  143. if(ciErrNum != CL_SUCCESS)
  144. {
  145. if(pErrNum != NULL)
  146. *pErrNum = ciErrNum;
  147. return platform;
  148. }
  149. platform = platforms[platformIndex];
  150. free (platforms);
  151. }
  152. return platform;
  153. }
  154. void b3OpenCLUtils::getPlatformInfo(cl_platform_id platform, b3OpenCLPlatformInfo* platformInfo)
  155. {
  156. b3Assert(platform);
  157. cl_int ciErrNum;
  158. ciErrNum = clGetPlatformInfo( platform,CL_PLATFORM_VENDOR,B3_MAX_STRING_LENGTH,platformInfo->m_platformVendor,NULL);
  159. oclCHECKERROR(ciErrNum,CL_SUCCESS);
  160. ciErrNum = clGetPlatformInfo( platform,CL_PLATFORM_NAME,B3_MAX_STRING_LENGTH,platformInfo->m_platformName,NULL);
  161. oclCHECKERROR(ciErrNum,CL_SUCCESS);
  162. ciErrNum = clGetPlatformInfo( platform,CL_PLATFORM_VERSION,B3_MAX_STRING_LENGTH,platformInfo->m_platformVersion,NULL);
  163. oclCHECKERROR(ciErrNum,CL_SUCCESS);
  164. }
  165. void b3OpenCLUtils_printPlatformInfo( cl_platform_id platform)
  166. {
  167. b3OpenCLPlatformInfo platformInfo;
  168. b3OpenCLUtils::getPlatformInfo (platform, &platformInfo);
  169. b3Printf("Platform info:\n");
  170. b3Printf(" CL_PLATFORM_VENDOR: \t\t\t%s\n",platformInfo.m_platformVendor);
  171. b3Printf(" CL_PLATFORM_NAME: \t\t\t%s\n",platformInfo.m_platformName);
  172. b3Printf(" CL_PLATFORM_VERSION: \t\t\t%s\n",platformInfo.m_platformVersion);
  173. }
  174. cl_context b3OpenCLUtils_createContextFromPlatform(cl_platform_id platform, cl_device_type deviceType, cl_int* pErrNum, void* pGLContext, void* pGLDC, int preferredDeviceIndex, int preferredPlatformIndex)
  175. {
  176. cl_context retContext = 0;
  177. cl_int ciErrNum=0;
  178. cl_uint num_entries;
  179. cl_device_id devices[B3_MAX_CL_DEVICES];
  180. cl_uint num_devices;
  181. cl_context_properties* cprops;
  182. /*
  183. * If we could find our platform, use it. Otherwise pass a NULL and get whatever the
  184. * implementation thinks we should be using.
  185. */
  186. cl_context_properties cps[7] = {0,0,0,0,0,0,0};
  187. cps[0] = CL_CONTEXT_PLATFORM;
  188. cps[1] = (cl_context_properties)platform;
  189. #ifdef _WIN32
  190. #ifndef B3_USE_CLEW
  191. if (pGLContext && pGLDC)
  192. {
  193. cps[2] = CL_GL_CONTEXT_KHR;
  194. cps[3] = (cl_context_properties)pGLContext;
  195. cps[4] = CL_WGL_HDC_KHR;
  196. cps[5] = (cl_context_properties)pGLDC;
  197. }
  198. #endif //B3_USE_CLEW
  199. #endif //_WIN32
  200. num_entries = B3_MAX_CL_DEVICES;
  201. num_devices=-1;
  202. ciErrNum = clGetDeviceIDs(
  203. platform,
  204. deviceType,
  205. num_entries,
  206. devices,
  207. &num_devices);
  208. if (ciErrNum<0)
  209. {
  210. b3Printf("clGetDeviceIDs returned %d\n",ciErrNum);
  211. return 0;
  212. }
  213. cprops = (NULL == platform) ? NULL : cps;
  214. if (!num_devices)
  215. return 0;
  216. if (pGLContext)
  217. {
  218. //search for the GPU that relates to the OpenCL context
  219. unsigned int i;
  220. for (i=0;i<num_devices;i++)
  221. {
  222. retContext = clCreateContext(cprops,1,&devices[i],NULL,NULL,&ciErrNum);
  223. if (ciErrNum==CL_SUCCESS)
  224. break;
  225. }
  226. }
  227. else
  228. {
  229. if (preferredDeviceIndex>=0 && (unsigned int)preferredDeviceIndex<num_devices)
  230. {
  231. //create a context of the preferred device index
  232. retContext = clCreateContext(cprops,1,&devices[preferredDeviceIndex],NULL,NULL,&ciErrNum);
  233. } else
  234. {
  235. //create a context of all devices
  236. #if defined (__APPLE__)
  237. retContext = clCreateContext(cprops,num_devices,devices,MyFatalBreakAPPLE,NULL,&ciErrNum);
  238. #else
  239. b3Printf("numDevices=%d\n",num_devices);
  240. retContext = clCreateContext(cprops,num_devices,devices,NULL,NULL,&ciErrNum);
  241. #endif
  242. }
  243. }
  244. if(pErrNum != NULL)
  245. {
  246. *pErrNum = ciErrNum;
  247. };
  248. return retContext;
  249. }
  250. cl_context b3OpenCLUtils_createContextFromType(cl_device_type deviceType, cl_int* pErrNum, void* pGLContext, void* pGLDC , int preferredDeviceIndex, int preferredPlatformIndex, cl_platform_id* retPlatformId)
  251. {
  252. #ifdef B3_USE_CLEW
  253. b3OpenCLUtils_clewInit();
  254. #endif
  255. cl_uint numPlatforms;
  256. cl_context retContext = 0;
  257. unsigned int i;
  258. cl_int ciErrNum = clGetPlatformIDs(0, NULL, &numPlatforms);
  259. if(ciErrNum != CL_SUCCESS)
  260. {
  261. if(pErrNum != NULL) *pErrNum = ciErrNum;
  262. return NULL;
  263. }
  264. if(numPlatforms > 0)
  265. {
  266. cl_platform_id* platforms = (cl_platform_id*) malloc (sizeof(cl_platform_id)*numPlatforms);
  267. ciErrNum = clGetPlatformIDs(numPlatforms, platforms, NULL);
  268. if(ciErrNum != CL_SUCCESS)
  269. {
  270. if(pErrNum != NULL)
  271. *pErrNum = ciErrNum;
  272. free(platforms);
  273. return NULL;
  274. }
  275. for ( i = 0; i < numPlatforms; ++i)
  276. {
  277. char pbuf[128];
  278. ciErrNum = clGetPlatformInfo( platforms[i],
  279. CL_PLATFORM_VENDOR,
  280. sizeof(pbuf),
  281. pbuf,
  282. NULL);
  283. if(ciErrNum != CL_SUCCESS)
  284. {
  285. if(pErrNum != NULL) *pErrNum = ciErrNum;
  286. return NULL;
  287. }
  288. if (preferredPlatformIndex>=0 && i==preferredPlatformIndex)
  289. {
  290. cl_platform_id tmpPlatform = platforms[0];
  291. platforms[0] = platforms[i];
  292. platforms[i] = tmpPlatform;
  293. break;
  294. } else
  295. {
  296. if(!strcmp(pbuf, spPlatformVendor))
  297. {
  298. cl_platform_id tmpPlatform = platforms[0];
  299. platforms[0] = platforms[i];
  300. platforms[i] = tmpPlatform;
  301. }
  302. }
  303. }
  304. for (i = 0; i < numPlatforms; ++i)
  305. {
  306. cl_platform_id platform = platforms[i];
  307. assert(platform);
  308. retContext = b3OpenCLUtils_createContextFromPlatform(platform,deviceType,pErrNum,pGLContext,pGLDC,preferredDeviceIndex,preferredPlatformIndex);
  309. if (retContext)
  310. {
  311. // printf("OpenCL platform details:\n");
  312. b3OpenCLPlatformInfo platformInfo;
  313. b3OpenCLUtils::getPlatformInfo(platform, &platformInfo);
  314. if (retPlatformId)
  315. *retPlatformId = platform;
  316. break;
  317. }
  318. }
  319. free (platforms);
  320. }
  321. return retContext;
  322. }
  323. //////////////////////////////////////////////////////////////////////////////
  324. //! Gets the id of the nth device from the context
  325. //!
  326. //! @return the id or -1 when out of range
  327. //! @param cxMainContext OpenCL context
  328. //! @param device_idx index of the device of interest
  329. //////////////////////////////////////////////////////////////////////////////
  330. cl_device_id b3OpenCLUtils_getDevice(cl_context cxMainContext, int deviceIndex)
  331. {
  332. assert(cxMainContext);
  333. size_t szParmDataBytes;
  334. cl_device_id* cdDevices;
  335. cl_device_id device ;
  336. // get the list of devices associated with context
  337. clGetContextInfo(cxMainContext, CL_CONTEXT_DEVICES, 0, NULL, &szParmDataBytes);
  338. if( szParmDataBytes / sizeof(cl_device_id) < (unsigned int)deviceIndex ) {
  339. return (cl_device_id)-1;
  340. }
  341. cdDevices = (cl_device_id*) malloc(szParmDataBytes);
  342. clGetContextInfo(cxMainContext, CL_CONTEXT_DEVICES, szParmDataBytes, cdDevices, NULL);
  343. device = cdDevices[deviceIndex];
  344. free(cdDevices);
  345. return device;
  346. }
  347. int b3OpenCLUtils_getNumDevices(cl_context cxMainContext)
  348. {
  349. size_t szParamDataBytes;
  350. int device_count;
  351. clGetContextInfo(cxMainContext, CL_CONTEXT_DEVICES, 0, NULL, &szParamDataBytes);
  352. device_count = (int) szParamDataBytes/ sizeof(cl_device_id);
  353. return device_count;
  354. }
  355. void b3OpenCLUtils::getDeviceInfo(cl_device_id device, b3OpenCLDeviceInfo* info)
  356. {
  357. // CL_DEVICE_NAME
  358. clGetDeviceInfo(device, CL_DEVICE_NAME, B3_MAX_STRING_LENGTH, &info->m_deviceName, NULL);
  359. // CL_DEVICE_VENDOR
  360. clGetDeviceInfo(device, CL_DEVICE_VENDOR, B3_MAX_STRING_LENGTH, &info->m_deviceVendor, NULL);
  361. // CL_DRIVER_VERSION
  362. clGetDeviceInfo(device, CL_DRIVER_VERSION, B3_MAX_STRING_LENGTH, &info->m_driverVersion, NULL);
  363. // CL_DEVICE_INFO
  364. clGetDeviceInfo(device, CL_DEVICE_TYPE, sizeof(cl_device_type), &info->m_deviceType, NULL);
  365. // CL_DEVICE_MAX_COMPUTE_UNITS
  366. clGetDeviceInfo(device, CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(info->m_computeUnits), &info->m_computeUnits, NULL);
  367. // CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS
  368. clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS, sizeof(info->m_workitemDims), &info->m_workitemDims, NULL);
  369. // CL_DEVICE_MAX_WORK_ITEM_SIZES
  370. clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_ITEM_SIZES, sizeof(info->m_workItemSize), &info->m_workItemSize, NULL);
  371. // CL_DEVICE_MAX_WORK_GROUP_SIZE
  372. clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(info->m_workgroupSize), &info->m_workgroupSize, NULL);
  373. // CL_DEVICE_MAX_CLOCK_FREQUENCY
  374. clGetDeviceInfo(device, CL_DEVICE_MAX_CLOCK_FREQUENCY, sizeof(info->m_clockFrequency), &info->m_clockFrequency, NULL);
  375. // CL_DEVICE_ADDRESS_BITS
  376. clGetDeviceInfo(device, CL_DEVICE_ADDRESS_BITS, sizeof(info->m_addressBits), &info->m_addressBits, NULL);
  377. // CL_DEVICE_MAX_MEM_ALLOC_SIZE
  378. clGetDeviceInfo(device, CL_DEVICE_MAX_MEM_ALLOC_SIZE, sizeof(info->m_maxMemAllocSize), &info->m_maxMemAllocSize, NULL);
  379. // CL_DEVICE_GLOBAL_MEM_SIZE
  380. clGetDeviceInfo(device, CL_DEVICE_GLOBAL_MEM_SIZE, sizeof(info->m_globalMemSize), &info->m_globalMemSize, NULL);
  381. // CL_DEVICE_ERROR_CORRECTION_SUPPORT
  382. clGetDeviceInfo(device, CL_DEVICE_ERROR_CORRECTION_SUPPORT, sizeof(info->m_errorCorrectionSupport), &info->m_errorCorrectionSupport, NULL);
  383. // CL_DEVICE_LOCAL_MEM_TYPE
  384. clGetDeviceInfo(device, CL_DEVICE_LOCAL_MEM_TYPE, sizeof(info->m_localMemType), &info->m_localMemType, NULL);
  385. // CL_DEVICE_LOCAL_MEM_SIZE
  386. clGetDeviceInfo(device, CL_DEVICE_LOCAL_MEM_SIZE, sizeof(info->m_localMemSize), &info->m_localMemSize, NULL);
  387. // CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE
  388. clGetDeviceInfo(device, CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE, sizeof(info->m_constantBufferSize), &info->m_constantBufferSize, NULL);
  389. // CL_DEVICE_QUEUE_PROPERTIES
  390. clGetDeviceInfo(device, CL_DEVICE_QUEUE_PROPERTIES, sizeof(info->m_queueProperties), &info->m_queueProperties, NULL);
  391. // CL_DEVICE_IMAGE_SUPPORT
  392. clGetDeviceInfo(device, CL_DEVICE_IMAGE_SUPPORT, sizeof(info->m_imageSupport), &info->m_imageSupport, NULL);
  393. // CL_DEVICE_MAX_READ_IMAGE_ARGS
  394. clGetDeviceInfo(device, CL_DEVICE_MAX_READ_IMAGE_ARGS, sizeof(info->m_maxReadImageArgs), &info->m_maxReadImageArgs, NULL);
  395. // CL_DEVICE_MAX_WRITE_IMAGE_ARGS
  396. clGetDeviceInfo(device, CL_DEVICE_MAX_WRITE_IMAGE_ARGS, sizeof(info->m_maxWriteImageArgs), &info->m_maxWriteImageArgs, NULL);
  397. // CL_DEVICE_IMAGE2D_MAX_WIDTH, CL_DEVICE_IMAGE2D_MAX_HEIGHT, CL_DEVICE_IMAGE3D_MAX_WIDTH, CL_DEVICE_IMAGE3D_MAX_HEIGHT, CL_DEVICE_IMAGE3D_MAX_DEPTH
  398. clGetDeviceInfo(device, CL_DEVICE_IMAGE2D_MAX_WIDTH, sizeof(size_t), &info->m_image2dMaxWidth, NULL);
  399. clGetDeviceInfo(device, CL_DEVICE_IMAGE2D_MAX_HEIGHT, sizeof(size_t), &info->m_image2dMaxHeight, NULL);
  400. clGetDeviceInfo(device, CL_DEVICE_IMAGE3D_MAX_WIDTH, sizeof(size_t), &info->m_image3dMaxWidth, NULL);
  401. clGetDeviceInfo(device, CL_DEVICE_IMAGE3D_MAX_HEIGHT, sizeof(size_t), &info->m_image3dMaxHeight, NULL);
  402. clGetDeviceInfo(device, CL_DEVICE_IMAGE3D_MAX_DEPTH, sizeof(size_t), &info->m_image3dMaxDepth, NULL);
  403. // CL_DEVICE_EXTENSIONS: get device extensions, and if any then parse & log the string onto separate lines
  404. clGetDeviceInfo(device, CL_DEVICE_EXTENSIONS, B3_MAX_STRING_LENGTH, &info->m_deviceExtensions, NULL);
  405. // CL_DEVICE_PREFERRED_VECTOR_WIDTH_<type>
  406. clGetDeviceInfo(device, CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR, sizeof(cl_uint), &info->m_vecWidthChar, NULL);
  407. clGetDeviceInfo(device, CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT, sizeof(cl_uint), &info->m_vecWidthShort, NULL);
  408. clGetDeviceInfo(device, CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT, sizeof(cl_uint), &info->m_vecWidthInt, NULL);
  409. clGetDeviceInfo(device, CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG, sizeof(cl_uint), &info->m_vecWidthLong, NULL);
  410. clGetDeviceInfo(device, CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT, sizeof(cl_uint), &info->m_vecWidthFloat, NULL);
  411. clGetDeviceInfo(device, CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE, sizeof(cl_uint), &info->m_vecWidthDouble, NULL);
  412. }
  413. void b3OpenCLUtils_printDeviceInfo(cl_device_id device)
  414. {
  415. b3OpenCLDeviceInfo info;
  416. b3OpenCLUtils::getDeviceInfo(device,&info);
  417. b3Printf("Device Info:\n");
  418. b3Printf(" CL_DEVICE_NAME: \t\t\t%s\n", info.m_deviceName);
  419. b3Printf(" CL_DEVICE_VENDOR: \t\t\t%s\n", info.m_deviceVendor);
  420. b3Printf(" CL_DRIVER_VERSION: \t\t\t%s\n", info.m_driverVersion);
  421. if( info.m_deviceType & CL_DEVICE_TYPE_CPU )
  422. b3Printf(" CL_DEVICE_TYPE:\t\t\t%s\n", "CL_DEVICE_TYPE_CPU");
  423. if( info.m_deviceType & CL_DEVICE_TYPE_GPU )
  424. b3Printf(" CL_DEVICE_TYPE:\t\t\t%s\n", "CL_DEVICE_TYPE_GPU");
  425. if( info.m_deviceType & CL_DEVICE_TYPE_ACCELERATOR )
  426. b3Printf(" CL_DEVICE_TYPE:\t\t\t%s\n", "CL_DEVICE_TYPE_ACCELERATOR");
  427. if( info.m_deviceType & CL_DEVICE_TYPE_DEFAULT )
  428. b3Printf(" CL_DEVICE_TYPE:\t\t\t%s\n", "CL_DEVICE_TYPE_DEFAULT");
  429. b3Printf(" CL_DEVICE_MAX_COMPUTE_UNITS:\t\t%u\n", info.m_computeUnits);
  430. b3Printf(" CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS:\t%u\n", info.m_workitemDims);
  431. b3Printf(" CL_DEVICE_MAX_WORK_ITEM_SIZES:\t%u / %u / %u \n", info.m_workItemSize[0], info.m_workItemSize[1], info.m_workItemSize[2]);
  432. b3Printf(" CL_DEVICE_MAX_WORK_GROUP_SIZE:\t%u\n", info.m_workgroupSize);
  433. b3Printf(" CL_DEVICE_MAX_CLOCK_FREQUENCY:\t%u MHz\n", info.m_clockFrequency);
  434. b3Printf(" CL_DEVICE_ADDRESS_BITS:\t\t%u\n", info.m_addressBits);
  435. b3Printf(" CL_DEVICE_MAX_MEM_ALLOC_SIZE:\t\t%u MByte\n", (unsigned int)(info.m_maxMemAllocSize/ (1024 * 1024)));
  436. b3Printf(" CL_DEVICE_GLOBAL_MEM_SIZE:\t\t%u MByte\n", (unsigned int)(info.m_globalMemSize/ (1024 * 1024)));
  437. b3Printf(" CL_DEVICE_ERROR_CORRECTION_SUPPORT:\t%s\n", info.m_errorCorrectionSupport== CL_TRUE ? "yes" : "no");
  438. b3Printf(" CL_DEVICE_LOCAL_MEM_TYPE:\t\t%s\n", info.m_localMemType == 1 ? "local" : "global");
  439. b3Printf(" CL_DEVICE_LOCAL_MEM_SIZE:\t\t%u KByte\n", (unsigned int)(info.m_localMemSize / 1024));
  440. b3Printf(" CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE:\t%u KByte\n", (unsigned int)(info.m_constantBufferSize / 1024));
  441. if( info.m_queueProperties & CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE )
  442. b3Printf(" CL_DEVICE_QUEUE_PROPERTIES:\t\t%s\n", "CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE");
  443. if( info.m_queueProperties & CL_QUEUE_PROFILING_ENABLE )
  444. b3Printf(" CL_DEVICE_QUEUE_PROPERTIES:\t\t%s\n", "CL_QUEUE_PROFILING_ENABLE");
  445. b3Printf(" CL_DEVICE_IMAGE_SUPPORT:\t\t%u\n", info.m_imageSupport);
  446. b3Printf(" CL_DEVICE_MAX_READ_IMAGE_ARGS:\t%u\n", info.m_maxReadImageArgs);
  447. b3Printf(" CL_DEVICE_MAX_WRITE_IMAGE_ARGS:\t%u\n", info.m_maxWriteImageArgs);
  448. b3Printf("\n CL_DEVICE_IMAGE <dim>");
  449. b3Printf("\t\t\t2D_MAX_WIDTH\t %u\n", info.m_image2dMaxWidth);
  450. b3Printf("\t\t\t\t\t2D_MAX_HEIGHT\t %u\n", info.m_image2dMaxHeight);
  451. b3Printf("\t\t\t\t\t3D_MAX_WIDTH\t %u\n", info.m_image3dMaxWidth);
  452. b3Printf("\t\t\t\t\t3D_MAX_HEIGHT\t %u\n", info.m_image3dMaxHeight);
  453. b3Printf("\t\t\t\t\t3D_MAX_DEPTH\t %u\n", info.m_image3dMaxDepth);
  454. if (*info.m_deviceExtensions != 0)
  455. {
  456. b3Printf("\n CL_DEVICE_EXTENSIONS:%s\n",info.m_deviceExtensions);
  457. }
  458. else
  459. {
  460. b3Printf(" CL_DEVICE_EXTENSIONS: None\n");
  461. }
  462. b3Printf(" CL_DEVICE_PREFERRED_VECTOR_WIDTH_<t>\t");
  463. b3Printf("CHAR %u, SHORT %u, INT %u,LONG %u, FLOAT %u, DOUBLE %u\n\n\n",
  464. info.m_vecWidthChar, info.m_vecWidthShort, info.m_vecWidthInt, info.m_vecWidthLong,info.m_vecWidthFloat, info.m_vecWidthDouble);
  465. }
  466. static const char* strip2(const char* name, const char* pattern)
  467. {
  468. size_t const patlen = strlen(pattern);
  469. size_t patcnt = 0;
  470. const char * oriptr;
  471. const char * patloc;
  472. // find how many times the pattern occurs in the original string
  473. for (oriptr = name; (patloc = strstr(oriptr, pattern)); oriptr = patloc + patlen)
  474. {
  475. patcnt++;
  476. }
  477. return oriptr;
  478. }
  479. cl_program b3OpenCLUtils_compileCLProgramFromString(cl_context clContext, cl_device_id device, const char* kernelSourceOrg, cl_int* pErrNum, const char* additionalMacrosArg , const char* clFileNameForCaching, bool disableBinaryCaching)
  480. {
  481. const char* additionalMacros = additionalMacrosArg?additionalMacrosArg:"";
  482. if (disableBinaryCaching)
  483. {
  484. //kernelSourceOrg = 0;
  485. }
  486. cl_program m_cpProgram=0;
  487. cl_int status;
  488. char binaryFileName[B3_MAX_STRING_LENGTH];
  489. char deviceName[256];
  490. char driverVersion[256];
  491. const char* strippedName;
  492. int fileUpToDate = 0;
  493. #ifdef _WIN32
  494. int binaryFileValid=0;
  495. #endif
  496. if (!disableBinaryCaching && clFileNameForCaching)
  497. {
  498. clGetDeviceInfo(device, CL_DEVICE_NAME, 256, &deviceName, NULL);
  499. clGetDeviceInfo(device, CL_DRIVER_VERSION, 256, &driverVersion, NULL);
  500. strippedName = strip2(clFileNameForCaching,"\\");
  501. strippedName = strip2(strippedName,"/");
  502. #ifdef _MSC_VER
  503. sprintf_s(binaryFileName,B3_MAX_STRING_LENGTH,"%s/%s.%s.%s.bin",sCachedBinaryPath,strippedName, deviceName,driverVersion );
  504. #else
  505. sprintf(binaryFileName,"%s/%s.%s.%s.bin",sCachedBinaryPath,strippedName, deviceName,driverVersion );
  506. #endif
  507. }
  508. if (clFileNameForCaching && !(disableBinaryCaching || gDebugSkipLoadingBinary||gDebugForceLoadingFromSource) )
  509. {
  510. #ifdef _WIN32
  511. char* bla=0;
  512. //printf("searching for %s\n", binaryFileName);
  513. FILETIME modtimeBinary;
  514. CreateDirectoryA(sCachedBinaryPath,0);
  515. {
  516. HANDLE binaryFileHandle = CreateFileA(binaryFileName,GENERIC_READ,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
  517. if (binaryFileHandle ==INVALID_HANDLE_VALUE)
  518. {
  519. DWORD errorCode;
  520. errorCode = GetLastError();
  521. switch (errorCode)
  522. {
  523. case ERROR_FILE_NOT_FOUND:
  524. {
  525. b3Warning("\nCached file not found %s\n", binaryFileName);
  526. break;
  527. }
  528. case ERROR_PATH_NOT_FOUND:
  529. {
  530. b3Warning("\nCached file path not found %s\n", binaryFileName);
  531. break;
  532. }
  533. default:
  534. {
  535. b3Warning("\nFailed reading cached file with errorCode = %d\n", errorCode);
  536. }
  537. }
  538. } else
  539. {
  540. if (GetFileTime(binaryFileHandle, NULL, NULL, &modtimeBinary)==0)
  541. {
  542. DWORD errorCode;
  543. errorCode = GetLastError();
  544. b3Warning("\nGetFileTime errorCode = %d\n", errorCode);
  545. } else
  546. {
  547. binaryFileValid = 1;
  548. }
  549. CloseHandle(binaryFileHandle);
  550. }
  551. if (binaryFileValid)
  552. {
  553. HANDLE srcFileHandle = CreateFileA(clFileNameForCaching,GENERIC_READ,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
  554. if (srcFileHandle==INVALID_HANDLE_VALUE)
  555. {
  556. const char* prefix[]={"./","../","../../","../../../","../../../../"};
  557. for (int i=0;(srcFileHandle==INVALID_HANDLE_VALUE) && i<5;i++)
  558. {
  559. char relativeFileName[1024];
  560. sprintf(relativeFileName,"%s%s",prefix[i],clFileNameForCaching);
  561. srcFileHandle = CreateFileA(relativeFileName,GENERIC_READ,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
  562. }
  563. }
  564. if (srcFileHandle!=INVALID_HANDLE_VALUE)
  565. {
  566. FILETIME modtimeSrc;
  567. if (GetFileTime(srcFileHandle, NULL, NULL, &modtimeSrc)==0)
  568. {
  569. DWORD errorCode;
  570. errorCode = GetLastError();
  571. b3Warning("\nGetFileTime errorCode = %d\n", errorCode);
  572. }
  573. if ( ( modtimeSrc.dwHighDateTime < modtimeBinary.dwHighDateTime)
  574. ||(( modtimeSrc.dwHighDateTime == modtimeBinary.dwHighDateTime)&&(modtimeSrc.dwLowDateTime <= modtimeBinary.dwLowDateTime)))
  575. {
  576. fileUpToDate=1;
  577. } else
  578. {
  579. b3Warning("\nCached binary file out-of-date (%s)\n",binaryFileName);
  580. }
  581. CloseHandle(srcFileHandle);
  582. }
  583. else
  584. {
  585. #ifdef _DEBUG
  586. DWORD errorCode;
  587. errorCode = GetLastError();
  588. switch (errorCode)
  589. {
  590. case ERROR_FILE_NOT_FOUND:
  591. {
  592. b3Warning("\nSrc file not found %s\n", clFileNameForCaching);
  593. break;
  594. }
  595. case ERROR_PATH_NOT_FOUND:
  596. {
  597. b3Warning("\nSrc path not found %s\n", clFileNameForCaching);
  598. break;
  599. }
  600. default:
  601. {
  602. b3Warning("\nnSrc file reading errorCode = %d\n", errorCode);
  603. }
  604. }
  605. //we should make sure the src file exists so we can verify the timestamp with binary
  606. // assert(0);
  607. b3Warning("Warning: cannot find OpenCL kernel %s to verify timestamp of binary cached kernel %s\n",clFileNameForCaching, binaryFileName);
  608. fileUpToDate = true;
  609. #else
  610. //if we cannot find the source, assume it is OK in release builds
  611. fileUpToDate = true;
  612. #endif
  613. }
  614. }
  615. }
  616. #else
  617. fileUpToDate = true;
  618. if (mkdir(sCachedBinaryPath,0777) == -1)
  619. {
  620. }
  621. else
  622. {
  623. b3Printf("Succesfully created cache directory: %s\n", sCachedBinaryPath);
  624. }
  625. #endif //_WIN32
  626. }
  627. if( fileUpToDate)
  628. {
  629. #ifdef _MSC_VER
  630. FILE* file;
  631. if (fopen_s(&file,binaryFileName, "rb")!=0)
  632. file=0;
  633. #else
  634. FILE* file = fopen(binaryFileName, "rb");
  635. #endif
  636. if (file)
  637. {
  638. size_t binarySize=0;
  639. char* binary =0;
  640. fseek( file, 0L, SEEK_END );
  641. binarySize = ftell( file );
  642. rewind( file );
  643. binary = (char*)malloc(sizeof(char)*binarySize);
  644. int bytesRead;
  645. bytesRead = fread( binary, sizeof(char), binarySize, file );
  646. fclose( file );
  647. m_cpProgram = clCreateProgramWithBinary( clContext, 1,&device, &binarySize, (const unsigned char**)&binary, 0, &status );
  648. b3Assert( status == CL_SUCCESS );
  649. status = clBuildProgram( m_cpProgram, 1, &device, additionalMacros, 0, 0 );
  650. b3Assert( status == CL_SUCCESS );
  651. if( status != CL_SUCCESS )
  652. {
  653. char *build_log;
  654. size_t ret_val_size;
  655. clGetProgramBuildInfo(m_cpProgram, device, CL_PROGRAM_BUILD_LOG, 0, NULL, &ret_val_size);
  656. build_log = (char*)malloc(sizeof(char)*(ret_val_size+1));
  657. clGetProgramBuildInfo(m_cpProgram, device, CL_PROGRAM_BUILD_LOG, ret_val_size, build_log, NULL);
  658. build_log[ret_val_size] = '\0';
  659. b3Error("%s\n", build_log);
  660. free (build_log);
  661. b3Assert(0);
  662. m_cpProgram = 0;
  663. b3Warning("clBuildProgram reported failure on cached binary: %s\n",binaryFileName);
  664. } else
  665. {
  666. b3Printf("clBuildProgram successfully compiled cached binary: %s\n",binaryFileName);
  667. }
  668. free (binary);
  669. } else
  670. {
  671. b3Warning("Cannot open cached binary: %s\n",binaryFileName);
  672. }
  673. }
  674. if (!m_cpProgram)
  675. {
  676. cl_int localErrNum;
  677. char* compileFlags;
  678. int flagsize;
  679. const char* kernelSource = kernelSourceOrg;
  680. if (!kernelSourceOrg || gDebugForceLoadingFromSource)
  681. {
  682. if (clFileNameForCaching)
  683. {
  684. FILE* file = fopen(clFileNameForCaching, "rb");
  685. //in many cases the relative path is a few levels up the directory hierarchy, so try it
  686. if (!file)
  687. {
  688. const char* prefix[]={"../","../../","../../../","../../../../"};
  689. for (int i=0;!file && i<3;i++)
  690. {
  691. char relativeFileName[1024];
  692. sprintf(relativeFileName,"%s%s",prefix[i],clFileNameForCaching);
  693. file = fopen(relativeFileName, "rb");
  694. }
  695. }
  696. if (file)
  697. {
  698. char* kernelSrc=0;
  699. fseek( file, 0L, SEEK_END );
  700. int kernelSize = ftell( file );
  701. rewind( file );
  702. kernelSrc = (char*)malloc(kernelSize+1);
  703. int readBytes;
  704. readBytes = fread((void*)kernelSrc,1,kernelSize, file);
  705. kernelSrc[kernelSize] = 0;
  706. fclose(file);
  707. kernelSource = kernelSrc;
  708. }
  709. }
  710. }
  711. size_t program_length = kernelSource ? strlen(kernelSource) : 0;
  712. #ifdef MAC //or __APPLE__?
  713. char* flags = "-cl-mad-enable -DMAC ";
  714. #else
  715. const char* flags = "";
  716. #endif
  717. m_cpProgram = clCreateProgramWithSource(clContext, 1, (const char**)&kernelSource, &program_length, &localErrNum);
  718. if (localErrNum!= CL_SUCCESS)
  719. {
  720. if (pErrNum)
  721. *pErrNum = localErrNum;
  722. return 0;
  723. }
  724. // Build the program with 'mad' Optimization option
  725. flagsize = sizeof(char)*(strlen(additionalMacros) + strlen(flags) + 5);
  726. compileFlags = (char*) malloc(flagsize);
  727. #ifdef _MSC_VER
  728. sprintf_s(compileFlags,flagsize, "%s %s", flags, additionalMacros);
  729. #else
  730. sprintf(compileFlags, "%s %s", flags, additionalMacros);
  731. #endif
  732. localErrNum = clBuildProgram(m_cpProgram, 1, &device, compileFlags, NULL, NULL);
  733. if (localErrNum!= CL_SUCCESS)
  734. {
  735. char *build_log;
  736. size_t ret_val_size;
  737. clGetProgramBuildInfo(m_cpProgram, device, CL_PROGRAM_BUILD_LOG, 0, NULL, &ret_val_size);
  738. build_log = (char*) malloc(sizeof(char)*(ret_val_size+1));
  739. clGetProgramBuildInfo(m_cpProgram, device, CL_PROGRAM_BUILD_LOG, ret_val_size, build_log, NULL);
  740. // to be carefully, terminate with \0
  741. // there's no information in the reference whether the string is 0 terminated or not
  742. build_log[ret_val_size] = '\0';
  743. b3Error("Error in clBuildProgram, Line %u in file %s, Log: \n%s\n !!!\n\n", __LINE__, __FILE__, build_log);
  744. free (build_log);
  745. if (pErrNum)
  746. *pErrNum = localErrNum;
  747. return 0;
  748. }
  749. if( !disableBinaryCaching && clFileNameForCaching )
  750. { // write to binary
  751. cl_uint numAssociatedDevices;
  752. status = clGetProgramInfo( m_cpProgram, CL_PROGRAM_NUM_DEVICES, sizeof(cl_uint), &numAssociatedDevices, 0 );
  753. b3Assert( status == CL_SUCCESS );
  754. if (numAssociatedDevices==1)
  755. {
  756. size_t binarySize;
  757. char* binary ;
  758. status = clGetProgramInfo( m_cpProgram, CL_PROGRAM_BINARY_SIZES, sizeof(size_t), &binarySize, 0 );
  759. b3Assert( status == CL_SUCCESS );
  760. binary = (char*)malloc(sizeof(char)*binarySize);
  761. status = clGetProgramInfo( m_cpProgram, CL_PROGRAM_BINARIES, sizeof(char*), &binary, 0 );
  762. b3Assert( status == CL_SUCCESS );
  763. {
  764. FILE* file=0;
  765. #ifdef _MSC_VER
  766. if (fopen_s(&file,binaryFileName, "wb")!=0)
  767. file=0;
  768. #else
  769. file = fopen(binaryFileName, "wb");
  770. #endif
  771. if (file)
  772. {
  773. fwrite( binary, sizeof(char), binarySize, file );
  774. fclose( file );
  775. } else
  776. {
  777. b3Warning("cannot write file %s\n", binaryFileName);
  778. }
  779. }
  780. free (binary);
  781. }
  782. }
  783. free(compileFlags);
  784. }
  785. return m_cpProgram;
  786. }
  787. cl_kernel b3OpenCLUtils_compileCLKernelFromString(cl_context clContext, cl_device_id device, const char* kernelSource, const char* kernelName, cl_int* pErrNum, cl_program prog, const char* additionalMacros )
  788. {
  789. cl_kernel kernel;
  790. cl_int localErrNum;
  791. cl_program m_cpProgram = prog;
  792. b3Printf("compiling kernel %s ",kernelName);
  793. if (!m_cpProgram)
  794. {
  795. m_cpProgram = b3OpenCLUtils_compileCLProgramFromString(clContext,device,kernelSource,pErrNum, additionalMacros,0, false);
  796. }
  797. // Create the kernel
  798. kernel = clCreateKernel(m_cpProgram, kernelName, &localErrNum);
  799. if (localErrNum != CL_SUCCESS)
  800. {
  801. b3Error("Error in clCreateKernel, Line %u in file %s, cannot find kernel function %s !!!\n\n", __LINE__, __FILE__, kernelName);
  802. assert(0);
  803. if (pErrNum)
  804. *pErrNum = localErrNum;
  805. return 0;
  806. }
  807. if (!prog && m_cpProgram)
  808. {
  809. clReleaseProgram(m_cpProgram);
  810. }
  811. b3Printf("ready. \n");
  812. if (pErrNum)
  813. *pErrNum = CL_SUCCESS;
  814. return kernel;
  815. }