| 1 | /*========================== begin_copyright_notice ============================ |
| 2 | |
| 3 | Copyright (C) 2017-2023 Intel Corporation |
| 4 | |
| 5 | SPDX-License-Identifier: MIT |
| 6 | |
| 7 | ============================= end_copyright_notice ===========================*/ |
| 8 | |
| 9 | #include "../headers/clang_tb.h" |
| 10 | #include "../headers/common_clang.h" |
| 11 | #include "../headers/RegistryAccess.h" |
| 12 | |
| 13 | #include "../headers/resource.h" |
| 14 | |
| 15 | #include "common/LLVMWarningsPush.hpp" |
| 16 | #include "llvm/Config/llvm-config.h" |
| 17 | #include "llvm/Bitcode/BitcodeReader.h" |
| 18 | #include "llvm/Bitcode/BitcodeWriter.h" |
| 19 | #include "common/LLVMWarningsPop.hpp" |
| 20 | #include "iStdLib/utility.h" |
| 21 | |
| 22 | #include "secure_mem.h" |
| 23 | #include "secure_string.h" |
| 24 | #include "AdaptorCommon/customApi.hpp" |
| 25 | |
| 26 | #include "SPIRVExtensionsSupport.h" |
| 27 | |
| 28 | #include <mutex> |
| 29 | #include <sstream> |
| 30 | #include <stdlib.h> |
| 31 | #include <string> |
| 32 | #include <iomanip> |
| 33 | |
| 34 | #include "3d/common/iStdLib/File.h" |
| 35 | #include "Probe/Assertion.h" |
| 36 | |
| 37 | #if defined(_DEBUG) || defined(_INTERNAL) |
| 38 | #define IGC_DEBUG_VARIABLES |
| 39 | #endif |
| 40 | |
| 41 | |
| 42 | #if defined(IGC_DEBUG_VARIABLES) |
| 43 | |
| 44 | // Code for reading IGC regkeys "ShaderDumpEnable", "DumpToCurrentDir", "ShaderDumpPidDisable". |
| 45 | // Code for shader dump directory name scheme. |
| 46 | // Code is copied from IGC project. This duplication is undesirable in the long term. |
| 47 | // IGC is expected to put this code in single file, without unncessary llvm (and other dependencies). |
| 48 | // Then FCL will just include this single file to avoid code duplication and maintainability issues. |
| 49 | |
| 50 | #if defined(_WIN32) || defined(_WIN64) |
| 51 | #include <direct.h> |
| 52 | #include <process.h> |
| 53 | #endif |
| 54 | |
| 55 | #if defined __linux__ |
| 56 | #include "iStdLib/File.h" |
| 57 | #endif |
| 58 | |
| 59 | namespace { |
| 60 | std::string g_shaderOutputFolder; |
| 61 | } |
| 62 | |
| 63 | namespace FCL { |
| 64 | namespace Debug { |
| 65 | static std::mutex stream_mutex; |
| 66 | |
| 67 | void DumpLock() { stream_mutex.lock(); } |
| 68 | |
| 69 | void DumpUnlock() { stream_mutex.unlock(); } |
| 70 | } // namespace Debug |
| 71 | |
| 72 | #define IGC_REGISTRY_KEY "SOFTWARE\\INTEL\\IGFX\\IGC" |
| 73 | |
| 74 | typedef char FCLdebugString[256]; |
| 75 | |
| 76 | int32_t FCLShDumpEn = 0; |
| 77 | int32_t FCLDumpToCurrDir = 0; |
| 78 | int32_t FCLDumpToCustomDir = 0; |
| 79 | int32_t FCLShDumpPidDis = 0; |
| 80 | int32_t FCLEnableKernelNamesBasedHash = 0; |
| 81 | #if LLVM_VERSION_MAJOR < 17 || defined(IGC_LLVM_TRUNK_REVISION) |
| 82 | int32_t FCLEnableOpaquePointersBackend = 0; |
| 83 | #endif |
| 84 | int32_t FCLEnvKeysRead = 0; |
| 85 | std::string RegKeysFlagsFromOptions = ""; |
| 86 | |
| 87 | /*****************************************************************************\ |
| 88 | FCLReadIGCEnv |
| 89 | \*****************************************************************************/ |
| 90 | static bool FCLReadIGCEnv(const char *pName, void *pValue, unsigned int size) { |
| 91 | if (pName != NULL) { |
| 92 | const char nameTag[] = "IGC_"; |
| 93 | std::string pKey = std::string(nameTag) + std::string(pName); |
| 94 | |
| 95 | const char *envVal = getenv(pKey.c_str()); |
| 96 | |
| 97 | if (envVal != NULL) { |
| 98 | if (size >= sizeof(unsigned int)) { |
| 99 | // Try integer conversion |
| 100 | char *pStopped = nullptr; |
| 101 | unsigned int *puVal = (unsigned int *)pValue; |
| 102 | *puVal = strtoul(envVal, &pStopped, 0); |
| 103 | if (pStopped == envVal + std::string(envVal).length()) { |
| 104 | return true; |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | // Just return the string |
| 109 | strncpy_s((char *)pValue, size, envVal, size); |
| 110 | |
| 111 | return true; |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | return false; |
| 116 | } |
| 117 | |
| 118 | /*****************************************************************************\ |
| 119 | FCLReadIGCRegistry |
| 120 | \*****************************************************************************/ |
| 121 | static bool FCLReadIGCRegistry(const char *pName, void *pValue, unsigned int size) { |
| 122 | // All platforms can retrieve settings from environment |
| 123 | if (FCLReadIGCEnv(pName, pValue, size)) { |
| 124 | return true; |
| 125 | } |
| 126 | |
| 127 | #if defined _WIN32 |
| 128 | LONG success = ERROR_SUCCESS; |
| 129 | HKEY uscKey; |
| 130 | |
| 131 | success = RegOpenKeyExA(HKEY_LOCAL_MACHINE, IGC_REGISTRY_KEY, 0, KEY_READ, &uscKey); |
| 132 | |
| 133 | if (ERROR_SUCCESS == success) { |
| 134 | DWORD dwSize = size; |
| 135 | success = RegQueryValueExA(uscKey, pName, NULL, NULL, (LPBYTE)pValue, &dwSize); |
| 136 | |
| 137 | RegCloseKey(uscKey); |
| 138 | } |
| 139 | return (ERROR_SUCCESS == success); |
| 140 | #endif // defined _WIN32 |
| 141 | |
| 142 | return false; |
| 143 | } |
| 144 | |
| 145 | bool getFCLIGCBinaryKey(const char *keyName) { |
| 146 | FCLdebugString value = {0}; |
| 147 | |
| 148 | bool isSet = FCLReadIGCRegistry(keyName, &value, sizeof(value)); |
| 149 | isSet = isSet; |
| 150 | |
| 151 | return (value[0] != 0); |
| 152 | } |
| 153 | |
| 154 | void FCLReadKeysFromEnv() { |
| 155 | if (!FCLEnvKeysRead) { |
| 156 | FCLShDumpEn = getFCLIGCBinaryKey("ShaderDumpEnable") || |
| 157 | (RegKeysFlagsFromOptions.find("ShaderDumpEnable=1") != std::string::npos); |
| 158 | FCLDumpToCurrDir = getFCLIGCBinaryKey("DumpToCurrentDir") || |
| 159 | (RegKeysFlagsFromOptions.find("DumpToCurrentDir=1") != std::string::npos); |
| 160 | FCLDumpToCustomDir = getFCLIGCBinaryKey("DumpToCustomDir") || |
| 161 | (RegKeysFlagsFromOptions.find("DumpToCustomDir=") != std::string::npos); |
| 162 | FCLShDumpPidDis = getFCLIGCBinaryKey("ShaderDumpPidDisable") || |
| 163 | (RegKeysFlagsFromOptions.find("ShaderDumpPidDisable=1") != std::string::npos); |
| 164 | FCLEnableKernelNamesBasedHash = getFCLIGCBinaryKey("EnableKernelNamesBasedHash") || |
| 165 | (RegKeysFlagsFromOptions.find("EnableKernelNamesBasedHash=1") != std::string::npos); |
| 166 | #if LLVM_VERSION_MAJOR < 17 || defined(IGC_LLVM_TRUNK_REVISION) |
| 167 | FCLEnableOpaquePointersBackend = |
| 168 | getFCLIGCBinaryKey("EnableOpaquePointersBackend") || |
| 169 | (RegKeysFlagsFromOptions.find("EnableOpaquePointersBackend=1") != std::string::npos); |
| 170 | #endif |
| 171 | FCLEnvKeysRead = 1; |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | bool GetFCLShaderDumpEnable() { |
| 176 | FCLReadKeysFromEnv(); |
| 177 | return FCLShDumpEn; |
| 178 | } |
| 179 | |
| 180 | bool GetFCLShaderDumpPidDisable() { |
| 181 | FCLReadKeysFromEnv(); |
| 182 | return FCLShDumpPidDis; |
| 183 | } |
| 184 | |
| 185 | bool GetFCLDumpToCurrentDir() { |
| 186 | FCLReadKeysFromEnv(); |
| 187 | return FCLDumpToCurrDir; |
| 188 | } |
| 189 | |
| 190 | bool GetFCLDumpToCustomDir() { |
| 191 | FCLReadKeysFromEnv(); |
| 192 | return FCLDumpToCustomDir; |
| 193 | } |
| 194 | |
| 195 | bool GetFCLEnableKernelNamesBasedHash() { |
| 196 | FCLReadKeysFromEnv(); |
| 197 | return FCLEnableKernelNamesBasedHash; |
| 198 | } |
| 199 | |
| 200 | #if LLVM_VERSION_MAJOR < 17 || defined(IGC_LLVM_TRUNK_REVISION) |
| 201 | bool GetFCLEnableOpaquePointersBackend() { |
| 202 | FCLReadKeysFromEnv(); |
| 203 | return FCLEnableOpaquePointersBackend; |
| 204 | } |
| 205 | #endif |
| 206 | |
| 207 | OutputFolderName GetBaseIGCOutputFolder() { |
| 208 | #if defined(IGC_DEBUG_VARIABLES) |
| 209 | static std::mutex m; |
| 210 | std::lock_guard<std::mutex> lck(m); |
| 211 | static std::string IGCBaseFolder; |
| 212 | if (IGCBaseFolder != "") { |
| 213 | return IGCBaseFolder.c_str(); |
| 214 | } |
| 215 | #if defined(_WIN64) || defined(_WIN32) |
| 216 | if (!FCL_IGC_IS_FLAG_ENABLED(DumpToCurrentDir) && !FCL_IGC_IS_FLAG_ENABLED(DumpToCustomDir)) { |
| 217 | bool needMkdir = 1; |
| 218 | char dumpPath[256]; |
| 219 | |
| 220 | sprintf_s(dumpPath, "c:\\Intel\\IGC\\"); |
| 221 | |
| 222 | if (GetFileAttributesA(dumpPath) != FILE_ATTRIBUTE_DIRECTORY && needMkdir) { |
| 223 | _mkdir(dumpPath); |
| 224 | } |
| 225 | |
| 226 | // Make sure we can write in the dump folder as the app may be sandboxed |
| 227 | if (needMkdir) { |
| 228 | int tmp_id = _getpid(); |
| 229 | std::string testFilename = std::string(dumpPath) + "testfile" + std::to_string(tmp_id); |
| 230 | HANDLE testFile = |
| 231 | CreateFileA(testFilename.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_FLAG_DELETE_ON_CLOSE, NULL); |
| 232 | if (testFile == INVALID_HANDLE_VALUE) { |
| 233 | char temppath[256]; |
| 234 | if (GetTempPathA(sizeof(temppath), temppath) != 0) { |
| 235 | sprintf_s(dumpPath, "%sIGC\\", temppath); |
| 236 | } |
| 237 | } else { |
| 238 | CloseHandle(testFile); |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | if (GetFileAttributesA(dumpPath) != FILE_ATTRIBUTE_DIRECTORY && needMkdir) { |
| 243 | _mkdir(dumpPath); |
| 244 | } |
| 245 | |
| 246 | IGCBaseFolder = dumpPath; |
| 247 | } else if (FCL_IGC_IS_FLAG_ENABLED(DumpToCustomDir)) { |
| 248 | std::string dumpPath = "c:\\Intel\\IGC\\"; // default if something goes wrong |
| 249 | char custom_dir[256]; |
| 250 | std::string DumpToCustomDirFlagNameWithEqual = "DumpToCustomDir="; |
| 251 | std::size_t found = RegKeysFlagsFromOptions.find(DumpToCustomDirFlagNameWithEqual); |
| 252 | FCLReadIGCRegistry("DumpToCustomDir", custom_dir, sizeof(custom_dir)); |
| 253 | if (std::string(custom_dir).length() > 0 && (found == std::string::npos)) { |
| 254 | dumpPath = custom_dir; |
| 255 | } else { |
| 256 | std::size_t foundComma = RegKeysFlagsFromOptions.find(',', found); |
| 257 | if (foundComma != std::string::npos) { |
| 258 | std::string token = |
| 259 | RegKeysFlagsFromOptions.substr(found + DumpToCustomDirFlagNameWithEqual.size(), |
| 260 | foundComma - (found + DumpToCustomDirFlagNameWithEqual.size())); |
| 261 | if (token.size() > 0) { |
| 262 | dumpPath = token; |
| 263 | } |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | char pathBuf[256]; |
| 268 | iSTD::CreateAppOutputDir(pathBuf, 256, dumpPath.c_str(), false, false, false); |
| 269 | |
| 270 | IGCBaseFolder = pathBuf; |
| 271 | } |
| 272 | #elif defined __linux__ |
| 273 | if (!FCL_IGC_IS_FLAG_ENABLED(DumpToCustomDir)) { |
| 274 | IGCBaseFolder = "/tmp/IntelIGC/"; |
| 275 | } else { |
| 276 | std::string dumpPath = "/tmp/IntelIGC/"; // default if something goes wrong |
| 277 | const size_t maxLen = 255; |
| 278 | char custom_dir[maxLen + 1] = {0}; |
| 279 | std::string DumpToCustomDirFlagNameWithEqual = "DumpToCustomDir="; |
| 280 | std::size_t found = RegKeysFlagsFromOptions.find(DumpToCustomDirFlagNameWithEqual); |
| 281 | FCLReadIGCRegistry("DumpToCustomDir", custom_dir, maxLen); |
| 282 | if (std::string(custom_dir).length() > 0 && (found == std::string::npos)) { |
| 283 | IGC_ASSERT_MESSAGE(std::string(custom_dir).length() < maxLen, "custom_dir path too long"); |
| 284 | dumpPath = custom_dir; |
| 285 | dumpPath += "/"; |
| 286 | } else { |
| 287 | std::size_t foundComma = RegKeysFlagsFromOptions.find(',', found); |
| 288 | if (foundComma != std::string::npos) { |
| 289 | std::string token = |
| 290 | RegKeysFlagsFromOptions.substr(found + DumpToCustomDirFlagNameWithEqual.size(), |
| 291 | foundComma - (found + DumpToCustomDirFlagNameWithEqual.size())); |
| 292 | if (token.size() > 0) { |
| 293 | dumpPath = token; |
| 294 | } |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | char pathBuf[256]; |
| 299 | iSTD::CreateAppOutputDir(pathBuf, 256, dumpPath.c_str(), false, false, false); |
| 300 | |
| 301 | IGCBaseFolder = pathBuf; |
| 302 | } |
| 303 | #endif |
| 304 | return IGCBaseFolder.c_str(); |
| 305 | #else |
| 306 | return ""; |
| 307 | #endif |
| 308 | } |
| 309 | |
| 310 | OutputFolderName GetShaderOutputFolder() { |
| 311 | #if defined(IGC_DEBUG_VARIABLES) |
| 312 | static std::mutex m; |
| 313 | std::lock_guard<std::mutex> lck(m); |
| 314 | if (g_shaderOutputFolder != "") { |
| 315 | return g_shaderOutputFolder.c_str(); |
| 316 | } |
| 317 | #if defined(_WIN64) || defined(_WIN32) |
| 318 | if (!FCL_IGC_IS_FLAG_ENABLED(DumpToCurrentDir) && !FCL_IGC_IS_FLAG_ENABLED(DumpToCustomDir)) { |
| 319 | char dumpPath[256]; |
| 320 | sprintf_s(dumpPath, "%s", GetBaseIGCOutputFolder()); |
| 321 | char appPath[MAX_PATH] = {0}; |
| 322 | // check a process id and make an adequate directory for it: |
| 323 | |
| 324 | if (::GetModuleFileNameA(NULL, appPath, sizeof(appPath) - 1)) { |
| 325 | std::string appPathStr = std::string(appPath); |
| 326 | int pos = appPathStr.find_last_of("\\") + 1; |
| 327 | |
| 328 | if (FCL_IGC_IS_FLAG_ENABLED(ShaderDumpPidDisable)) { |
| 329 | sprintf_s(dumpPath, "%s%s\\", dumpPath, appPathStr.substr(pos, MAX_PATH).c_str()); |
| 330 | } else { |
| 331 | sprintf_s(dumpPath, "%s%s_%d\\", dumpPath, appPathStr.substr(pos, MAX_PATH).c_str(), _getpid()); |
| 332 | } |
| 333 | } else { |
| 334 | sprintf_s(dumpPath, "%sunknownProcess_%d\\", dumpPath, _getpid()); |
| 335 | } |
| 336 | |
| 337 | if (GetFileAttributesA(dumpPath) != FILE_ATTRIBUTE_DIRECTORY) { |
| 338 | _mkdir(dumpPath); |
| 339 | } |
| 340 | |
| 341 | g_shaderOutputFolder = dumpPath; |
| 342 | } else if (FCL_IGC_IS_FLAG_ENABLED(DumpToCustomDir)) { |
| 343 | char pathBuf[256]; |
| 344 | iSTD::CreateAppOutputDir(pathBuf, 256, GetBaseIGCOutputFolder(), false, true, |
| 345 | !FCL_IGC_IS_FLAG_ENABLED(ShaderDumpPidDisable)); |
| 346 | g_shaderOutputFolder = pathBuf; |
| 347 | } |
| 348 | #elif defined __linux__ |
| 349 | if (!FCL_IGC_IS_FLAG_ENABLED(DumpToCurrentDir) && g_shaderOutputFolder == "" && |
| 350 | !FCL_IGC_IS_FLAG_ENABLED(DumpToCustomDir)) { |
| 351 | bool needMkdir = true; |
| 352 | |
| 353 | char path[MAX_PATH] = {0}; |
| 354 | bool pidEnabled = !FCL_IGC_IS_FLAG_ENABLED(ShaderDumpPidDisable); |
| 355 | |
| 356 | if (needMkdir) { |
| 357 | iSTD::CreateAppOutputDir(path, MAX_PATH, GetBaseIGCOutputFolder(), false, true, pidEnabled); |
| 358 | } |
| 359 | |
| 360 | g_shaderOutputFolder = path; |
| 361 | } else if (FCL_IGC_IS_FLAG_ENABLED(DumpToCustomDir)) { |
| 362 | char pathBuf[256]; |
| 363 | iSTD::CreateAppOutputDir(pathBuf, 256, GetBaseIGCOutputFolder(), false, false, false); |
| 364 | g_shaderOutputFolder = pathBuf; |
| 365 | } |
| 366 | |
| 367 | #endif |
| 368 | return g_shaderOutputFolder.c_str(); |
| 369 | #else |
| 370 | return ""; |
| 371 | #endif |
| 372 | } |
| 373 | |
| 374 | } // namespace FCL |
| 375 | /// pk this ends here |
| 376 | #endif |
| 377 | |
| 378 | #ifndef WIN32 |
| 379 | #include <dlfcn.h> |
| 380 | #include <stdexcept> |
| 381 | #endif |
| 382 | |
| 383 | #if defined(_WIN32) |
| 384 | #include <Windows.h> |
| 385 | #include "DriverStore.h" |
| 386 | #endif |
| 387 | |
| 388 | using namespace llvm; |
| 389 | using namespace std; |
| 390 | |
| 391 | // ElfReader related typedefs |
| 392 | using namespace CLElfLib; |
| 393 | |
| 394 | void ElfReaderDP(CElfReader *pElfReader) { |
| 395 | if (pElfReader) |
| 396 | CElfReader::Delete(pElfReader); |
| 397 | } |
| 398 | typedef unique_ptr<CElfReader, decltype(&ElfReaderDP)> CElfReaderPtr; |
| 399 | |
| 400 | // ClangFE related typedefs |
| 401 | using namespace Intel::OpenCL::ClangFE; |
| 402 | void ReleaseDP(IOCLFEBinaryResult *pT) { |
| 403 | if (pT) |
| 404 | pT->Release(); |
| 405 | } |
| 406 | |
| 407 | typedef unique_ptr<IOCLFEBinaryResult, decltype(&ReleaseDP)> IOCLFEBinaryResultPtr; |
| 408 | |
| 409 | namespace TC { |
| 410 | constexpr bool is64bit = sizeof(void *) == sizeof(uint64_t); |
| 411 | // Misc utility functions used only in the current module |
| 412 | namespace Utils { |
| 413 | // Replace \0 in input string with \n. This works around an issue in |
| 414 | // Clang where the error message is not generated for inputs that contain |
| 415 | // a non-ending \0 |
| 416 | char *NormalizeString(char *input, uint32_t size) { |
| 417 | for (uint32_t i = 0; i < size; i++) { |
| 418 | if (input[i] == '\0') { |
| 419 | input[i] = '\n'; |
| 420 | } |
| 421 | } |
| 422 | input[size - 1] = '\0'; |
| 423 | return input; |
| 424 | } |
| 425 | |
| 426 | // Translates the ClangFE results to STB Output results |
| 427 | void FillOutputArgs(IOCLFEBinaryResult *pFEBinaryResult, STB_TranslateOutputArgs *pOutputArgs, |
| 428 | std::string &exceptString) { |
| 429 | // fill the result structure |
| 430 | uint32_t ErrorStringSize = (uint32_t)std::string(pFEBinaryResult->GetErrorLog()).length(); |
| 431 | if (ErrorStringSize > 0) { |
| 432 | TC::CClangTranslationBlock::SetErrorString(pFEBinaryResult->GetErrorLog(), pOutputArgs); |
| 433 | } else { |
| 434 | pOutputArgs->ErrorString.clear(); |
| 435 | } |
| 436 | uint32_t OutputSize = (uint32_t)pFEBinaryResult->GetIRSize(); |
| 437 | |
| 438 | // we have to copy the result due to unfortunate design of STB_TranslateOutputArg interface |
| 439 | // the better design would be for TranslateXXX calls to be responsible to allocate the outputArgs |
| 440 | // interface entirely, and the client to be responsible to call outputArgs->release() to free it. |
| 441 | // This way the implementation of TranslateXXX could be free to return inherited from outputArgs |
| 442 | // class which could glue the outputArgs with other internal interfaces (like the one returned from |
| 443 | // ::Compile method for example) without any buffer copy |
| 444 | if (OutputSize > 0) { |
| 445 | pOutputArgs->Output.resize(OutputSize); |
| 446 | char *IRBegin = (char *)pFEBinaryResult->GetIR(); |
| 447 | char *IREnd = (char *)pFEBinaryResult->GetIR() + OutputSize; |
| 448 | |
| 449 | pOutputArgs->Output.assign(IRBegin, IREnd); |
| 450 | } |
| 451 | } |
| 452 | } // namespace Utils |
| 453 | |
| 454 | struct OCLVersionNumberMapping { |
| 455 | const char *version; |
| 456 | unsigned int number; |
| 457 | }; |
| 458 | |
| 459 | // Input parameters to the 3 function |
| 460 | struct TranslateClangArgs { |
| 461 | TranslateClangArgs() : pszProgramSource(NULL), pPCHBuffer(NULL), uiPCHBufferSize(0), b32bit(!is64bit) {} |
| 462 | |
| 463 | // A pointer to main program's source (assumed one nullterminated string) |
| 464 | const char *pszProgramSource; |
| 465 | // array of additional input headers to be passed in memory |
| 466 | std::vector<const char *> inputHeaders; |
| 467 | // array of input headers names corresponding to pInputHeaders |
| 468 | std::vector<const char *> inputHeadersNames; |
| 469 | // optional pointer to the pch buffer |
| 470 | const char *pPCHBuffer; |
| 471 | // size of the pch buffer |
| 472 | size_t uiPCHBufferSize; |
| 473 | // OpenCL application supplied options |
| 474 | std::string options; |
| 475 | // optional extra options string usually supplied by runtime |
| 476 | std::string optionsEx; |
| 477 | // requested OCL version |
| 478 | std::string oclVersion; |
| 479 | // build for 32 bit |
| 480 | bool b32bit; |
| 481 | }; |
| 482 | |
| 483 | // Initialize static mutex object to be shared with all threads |
| 484 | // llvm::sys::Mutex CClangTranslationBlock::m_Mutex(/* recursive = */ true); |
| 485 | |
| 486 | /*****************************************************************************\ |
| 487 | |
| 488 | Function: |
| 489 | CClangTranslationBlock::Create |
| 490 | |
| 491 | Description: |
| 492 | |
| 493 | Input: |
| 494 | |
| 495 | Output: |
| 496 | |
| 497 | \*****************************************************************************/ |
| 498 | bool CClangTranslationBlock::Create(const STB_CreateArgs *pCreateArgs, STB_TranslateOutputArgs *pOutputArgs, |
| 499 | CClangTranslationBlock *&pTranslationBlock) { |
| 500 | bool success = true; |
| 501 | |
| 502 | pTranslationBlock = new CClangTranslationBlock(); |
| 503 | |
| 504 | if (pTranslationBlock) { |
| 505 | success = pTranslationBlock->Initialize(pCreateArgs); |
| 506 | |
| 507 | #ifdef _WIN32 |
| 508 | if (true == success) { |
| 509 | // Both Win32 and Win64 |
| 510 | // load dependency only on RS |
| 511 | // Load the Common Clang library |
| 512 | CCModuleStruct &CCModule = pTranslationBlock->m_CCModule; |
| 513 | if (GetWinVer() >= OS_WIN_RS) { |
| 514 | CCModule.pModule = LoadDependency(CCModule.pModuleName); |
| 515 | } else { |
| 516 | CCModule.pModule = LoadLibraryA(CCModule.pModuleName); |
| 517 | } |
| 518 | if (NULL != CCModule.pModule) { |
| 519 | CCModule.pCompile = (CCModuleStruct::PFcnCCCompile)GetProcAddress((HMODULE)CCModule.pModule, "Compile"); |
| 520 | success = CCModule.pCompile != NULL; |
| 521 | } else { |
| 522 | SetErrorString("Error: Opencl-clang library not found.", pOutputArgs); |
| 523 | success = false; |
| 524 | } |
| 525 | } |
| 526 | #endif |
| 527 | |
| 528 | if (!success) { |
| 529 | CClangTranslationBlock::Delete(pTranslationBlock); |
| 530 | } |
| 531 | } else { |
| 532 | success = false; |
| 533 | } |
| 534 | |
| 535 | return success; |
| 536 | } |
| 537 | |
| 538 | /*****************************************************************************\ |
| 539 | |
| 540 | Function: |
| 541 | CClangTranslationBlock::Delete |
| 542 | |
| 543 | Description: |
| 544 | |
| 545 | Input: |
| 546 | |
| 547 | Output: |
| 548 | |
| 549 | \*****************************************************************************/ |
| 550 | void CClangTranslationBlock::Delete(CClangTranslationBlock *&pTranslationBlock) { |
| 551 | #ifdef _WIN32 |
| 552 | // Unload the Common Clang library |
| 553 | if (pTranslationBlock->m_CCModule.pModule) { |
| 554 | // Both Win32 and Win64 |
| 555 | FreeLibrary((HMODULE)pTranslationBlock->m_CCModule.pModule); |
| 556 | } |
| 557 | #endif |
| 558 | |
| 559 | delete pTranslationBlock; |
| 560 | pTranslationBlock = NULL; |
| 561 | } |
| 562 | |
| 563 | /*****************************************************************************\ |
| 564 | |
| 565 | Function: |
| 566 | CClangTranslationBlock::SetErrorString |
| 567 | |
| 568 | Description: |
| 569 | Given an error string, mallocs memory for the string and sets the |
| 570 | appropriate STB_TranslateOutputArgs fields. |
| 571 | |
| 572 | Input: |
| 573 | |
| 574 | Output: |
| 575 | |
| 576 | \*****************************************************************************/ |
| 577 | void CClangTranslationBlock::SetErrorString(const char *pErrorString, STB_TranslateOutputArgs *pOutputArgs) { |
| 578 | IGC_ASSERT(pErrorString != NULL); |
| 579 | IGC_ASSERT(pOutputArgs != NULL); |
| 580 | pOutputArgs->ErrorString = pErrorString; |
| 581 | } |
| 582 | |
| 583 | /*****************************************************************************\ |
| 584 | |
| 585 | Function: |
| 586 | CClangTranslationBlock::GetOclApiVersion |
| 587 | |
| 588 | Description: |
| 589 | Parses the given internal options and return the OCL Version to be used |
| 590 | for Clang compilation. If OCL version was not specified in internal options |
| 591 | returns the default OCL version for the device |
| 592 | |
| 593 | Input: |
| 594 | |
| 595 | Output: |
| 596 | |
| 597 | \*****************************************************************************/ |
| 598 | std::string CClangTranslationBlock::GetOclApiVersion(const char *pInternalOptions) const { |
| 599 | static const char *OCL_VERSION_OPT = "-ocl-version="; |
| 600 | static size_t OCL_VERSION_OPT_SIZE = std::string(OCL_VERSION_OPT).length(); |
| 601 | |
| 602 | if (pInternalOptions) { |
| 603 | const char *pszOpt = strstr(pInternalOptions, OCL_VERSION_OPT); |
| 604 | if (NULL != pszOpt) { |
| 605 | // we are in control of internal option - assertion test the validity |
| 606 | IGC_ASSERT(std::string(pszOpt + OCL_VERSION_OPT_SIZE).length() >= 3); |
| 607 | return std::string(pszOpt + OCL_VERSION_OPT_SIZE, 3); |
| 608 | } |
| 609 | } |
| 610 | |
| 611 | return m_OCL_Ver; |
| 612 | } |
| 613 | |
| 614 | /*****************************************************************************\ |
| 615 | |
| 616 | Function: |
| 617 | EnforceOCLCVersion |
| 618 | |
| 619 | Description: |
| 620 | In case the '-force-cl-std' options was specified, check that the user |
| 621 | requested OCL C version isn't higher than the supported OCL version. |
| 622 | exception is thrown otherwise |
| 623 | |
| 624 | Input: |
| 625 | |
| 626 | Output: |
| 627 | |
| 628 | \*****************************************************************************/ |
| 629 | unsigned int GetOclCVersionFromOptions(const char *pOptions, const char *pInternalOptions, |
| 630 | const std::string &oclVersion /*OCL runtime API version*/, |
| 631 | std::string &exceptString) { |
| 632 | exceptString.clear(); |
| 633 | |
| 634 | if (pOptions == nullptr) { |
| 635 | return 0; // no options (i.e. no options from client application) |
| 636 | } |
| 637 | |
| 638 | std::string optName = "-cl-std="; // opt that we are looking for |
| 639 | unsigned int device_version = std::stoi(oclVersion); |
| 640 | |
| 641 | const char *optSubstring = strstr(pOptions, optName.c_str()); |
| 642 | if (optSubstring == nullptr) { |
| 643 | return 0; // -cl-std not specified |
| 644 | } |
| 645 | |
| 646 | bool validate = true; |
| 647 | if ((pInternalOptions != nullptr) && (strstr(pInternalOptions, "-force-cl-std") != nullptr)) { |
| 648 | // we're forcing the -cl-std version internally, so no need for validating it |
| 649 | validate = false; |
| 650 | } |
| 651 | |
| 652 | const char *optValue = optSubstring + optName.size(); |
| 653 | const char *end = optValue + std::string(optValue).length(); |
| 654 | |
| 655 | // parse |
| 656 | const std::string invalidFormatMessage = "Invalid format of -cl-std option, expected -cl-std=CLMAJOR.MINOR"; |
| 657 | auto isNumeric = [](char v) { return (v >= '0') && (v <= '9'); }; |
| 658 | if (false == ((end - optValue >= 5) && (optValue[0] == 'C') && (optValue[1] == 'L') && isNumeric(optValue[2]) && |
| 659 | (optValue[3] == '.') && isNumeric(optValue[4]))) { |
| 660 | exceptString = invalidFormatMessage; |
| 661 | return 0; |
| 662 | } |
| 663 | |
| 664 | unsigned int retVersion = 0; |
| 665 | // subverions |
| 666 | if ((end - optValue >= 7) && (optValue[5] != ' ')) { |
| 667 | if ((optValue[5] == '.') || isNumeric(optValue[6])) { |
| 668 | retVersion += optValue[6] - '0'; |
| 669 | } else if (isNumeric(optValue[5])) { |
| 670 | retVersion += optValue[5] - '0'; |
| 671 | } else { |
| 672 | exceptString = invalidFormatMessage; |
| 673 | return 0; |
| 674 | } |
| 675 | } |
| 676 | |
| 677 | retVersion += 100 * (optValue[2] - '0') + 10 * (optValue[4] - '0'); |
| 678 | |
| 679 | if (validate == false) { |
| 680 | return retVersion; |
| 681 | } |
| 682 | |
| 683 | if (device_version < retVersion) { |
| 684 | exceptString = "-cl-std OpenCLC version greater than OpenCL (API) version"; |
| 685 | return 0; |
| 686 | } |
| 687 | |
| 688 | return retVersion; |
| 689 | } |
| 690 | |
| 691 | /*****************************************************************************\ |
| 692 | |
| 693 | Function: |
| 694 | IsBuildingFor32bit |
| 695 | |
| 696 | Description: |
| 697 | Return true if clang should generate 32bit code |
| 698 | |
| 699 | Input: |
| 700 | |
| 701 | Output: |
| 702 | |
| 703 | \*****************************************************************************/ |
| 704 | bool IsBuildingFor32bit(const char *pInternalOptions) { |
| 705 | // Detect pointer size from internal option string. Default to using the |
| 706 | // architecture type if the string is unavailable. |
| 707 | if (pInternalOptions != NULL) { |
| 708 | if (strstr(pInternalOptions, "-m32") != NULL) { |
| 709 | return true; |
| 710 | } |
| 711 | |
| 712 | if (strstr(pInternalOptions, "-m64") != NULL) { |
| 713 | return false; |
| 714 | } |
| 715 | } |
| 716 | |
| 717 | return !is64bit; |
| 718 | } |
| 719 | |
| 720 | /*****************************************************************************\ |
| 721 | |
| 722 | Function: |
| 723 | AreVMETypesDefined |
| 724 | |
| 725 | Description: |
| 726 | Returns true if CommonClang used on current OS has VME types defined. |
| 727 | |
| 728 | \*****************************************************************************/ |
| 729 | bool AreVMETypesDefined() { |
| 730 | #ifdef VME_TYPES_DEFINED |
| 731 | #if VME_TYPES_DEFINED |
| 732 | return true; |
| 733 | #else |
| 734 | return false; |
| 735 | #endif |
| 736 | #endif |
| 737 | return true; |
| 738 | } |
| 739 | |
| 740 | /*****************************************************************************\ |
| 741 | |
| 742 | Function: |
| 743 | CClangTranslationBlock::GetTranslateClangArgs |
| 744 | |
| 745 | Description: |
| 746 | Prepares the arguments for the TranslateClang method for the given text input |
| 747 | |
| 748 | Input: |
| 749 | |
| 750 | Output: |
| 751 | |
| 752 | \*****************************************************************************/ |
| 753 | void CClangTranslationBlock::GetTranslateClangArgs(char *pInput, uint32_t uiInputSize, const char *pOptions, |
| 754 | const char *pInternalOptions, TranslateClangArgs *pClangArgs, |
| 755 | std::string &exceptString) { |
| 756 | pClangArgs->pszProgramSource = Utils::NormalizeString(pInput, uiInputSize); |
| 757 | pClangArgs->pPCHBuffer = NULL; |
| 758 | pClangArgs->uiPCHBufferSize = 0; |
| 759 | pClangArgs->oclVersion = GetOclApiVersion(pInternalOptions); |
| 760 | pClangArgs->b32bit = IsBuildingFor32bit(pInternalOptions); |
| 761 | |
| 762 | if (pOptions) { |
| 763 | pClangArgs->options.assign(pOptions); |
| 764 | } |
| 765 | #if defined(IGC_DEBUG_VARIABLES) |
| 766 | char debugOptions[1024]; |
| 767 | if (FCL::FCLReadIGCRegistry("ExtraOCLOptions", debugOptions, sizeof(debugOptions))) { |
| 768 | if (!pClangArgs->options.empty()) |
| 769 | pClangArgs->options += ' '; |
| 770 | pClangArgs->options += debugOptions; |
| 771 | } |
| 772 | #endif |
| 773 | |
| 774 | GetOclCVersionFromOptions(pOptions, pInternalOptions, pClangArgs->oclVersion, exceptString); |
| 775 | EnsureProperPCH(pClangArgs, pInternalOptions, exceptString); |
| 776 | } |
| 777 | |
| 778 | /*****************************************************************************\ |
| 779 | |
| 780 | Function: |
| 781 | CClangTranslationBlock::GetTranslateClangArgs |
| 782 | |
| 783 | Description: |
| 784 | Parses the given ELF binary to prepare the arguments for the TranslateClang |
| 785 | |
| 786 | Input: |
| 787 | |
| 788 | Output: |
| 789 | |
| 790 | \*****************************************************************************/ |
| 791 | void CClangTranslationBlock::GetTranslateClangArgs(CElfReader *pElfReader, const char *pOptions, |
| 792 | const char *pInternalOptions, TranslateClangArgs *pClangArgs, |
| 793 | std::string &exceptString) { |
| 794 | IGC_ASSERT_MESSAGE(pElfReader, "pElfReader is invalid"); |
| 795 | |
| 796 | const SElfHeader *pHeader = pElfReader->GetElfHeader(); |
| 797 | IGC_ASSERT_MESSAGE(pHeader->Type == EH_TYPE_OPENCL_SOURCE, "OPENCL_SOURCE elf type is expected"); |
| 798 | |
| 799 | // First section should be an OpenCL source code |
| 800 | const SElfSectionHeader *pSectionHeader = pElfReader->GetSectionHeader(1); |
| 801 | IGC_ASSERT_MESSAGE(NULL != pSectionHeader, "pSectionHeader cannot be NULL"); |
| 802 | |
| 803 | if (pSectionHeader->Type == SH_TYPE_OPENCL_SOURCE) { |
| 804 | char *pData = NULL; |
| 805 | size_t uiDataSize = 0; |
| 806 | pElfReader->GetSectionData(1, pData, uiDataSize); |
| 807 | |
| 808 | if (pData != NULL) { |
| 809 | IGC_ASSERT_MESSAGE(pData[uiDataSize - 1] == '\0', "Program source is not null terminated"); |
| 810 | pClangArgs->pszProgramSource = pData; |
| 811 | } |
| 812 | } |
| 813 | |
| 814 | // Other sections could be runtime supplied header files |
| 815 | for (unsigned i = 2; i < pHeader->NumSectionHeaderEntries; ++i) { |
| 816 | const SElfSectionHeader *pSectionHeader = pElfReader->GetSectionHeader(i); |
| 817 | |
| 818 | if ((pSectionHeader != NULL) && (pSectionHeader->Type == SH_TYPE_OPENCL_HEADER)) { |
| 819 | char *pData = NULL; |
| 820 | size_t uiDataSize = 0; |
| 821 | pElfReader->GetSectionData(i, pData, uiDataSize); |
| 822 | |
| 823 | if (pData != NULL) { |
| 824 | IGC_ASSERT_MESSAGE(pData[uiDataSize - 1] == '\0', "Header source is not null terminated"); |
| 825 | pClangArgs->inputHeaders.push_back(pData); |
| 826 | pClangArgs->inputHeadersNames.push_back(pElfReader->GetSectionName(i)); |
| 827 | } |
| 828 | } |
| 829 | } |
| 830 | |
| 831 | if (pOptions) { |
| 832 | pClangArgs->options.assign(pOptions); |
| 833 | } |
| 834 | |
| 835 | pClangArgs->oclVersion = GetOclApiVersion(pInternalOptions); |
| 836 | pClangArgs->b32bit = IsBuildingFor32bit(pInternalOptions); |
| 837 | |
| 838 | EnsureProperPCH(pClangArgs, pInternalOptions, exceptString); |
| 839 | } |
| 840 | |
| 841 | std::string FormatExtensionsString(const std::vector<std::string> &extensions) { |
| 842 | std::stringstream output; |
| 843 | |
| 844 | if (!extensions.empty()) { |
| 845 | output << "-cl-ext=-all"; |
| 846 | for (const std::string &extension : extensions) |
| 847 | output << ",+" << extension; |
| 848 | } |
| 849 | |
| 850 | output.flush(); |
| 851 | return output.str(); |
| 852 | } |
| 853 | |
| 854 | // Extracts a substring starting with "prefix" and ending with space. |
| 855 | std::string GetSubstring(const std::string &str, const std::string &prefix) { |
| 856 | size_t start_pos = 0, end_pos = 0; |
| 857 | std::string returnString = ""; |
| 858 | |
| 859 | while ((start_pos = str.find(prefix, end_pos)) != std::string::npos) { |
| 860 | end_pos = str.find(' ', start_pos); |
| 861 | returnString += str.substr(start_pos, end_pos - start_pos) + " "; |
| 862 | } |
| 863 | |
| 864 | return returnString; |
| 865 | } |
| 866 | |
| 867 | std::string GetCDefinesFromInternalOptions(const char *pInternalOptions) { |
| 868 | if (pInternalOptions == nullptr) { |
| 869 | return std::string{}; |
| 870 | } |
| 871 | |
| 872 | std::string internalDefines = ""; |
| 873 | |
| 874 | const char *beg = strstr(pInternalOptions, "-D"); |
| 875 | const char *end = nullptr; |
| 876 | while (beg != nullptr) { |
| 877 | if ((beg == pInternalOptions) || (beg[-1] == ' ')) { |
| 878 | end = strstr(beg, " "); |
| 879 | if (end == nullptr) { |
| 880 | if (beg[2] != '\0') { |
| 881 | // more than just -D |
| 882 | internalDefines += std::string(beg); |
| 883 | } |
| 884 | break; |
| 885 | } else { |
| 886 | if (end - beg > 2) { |
| 887 | internalDefines += std::string(beg, end); |
| 888 | } |
| 889 | } |
| 890 | internalDefines += " "; |
| 891 | } else { |
| 892 | end = beg + 2; // -D |
| 893 | } |
| 894 | |
| 895 | beg = strstr(end, "-D"); |
| 896 | } |
| 897 | |
| 898 | return internalDefines; |
| 899 | } |
| 900 | |
| 901 | // Tracks extensions that require manual feature macro generation for OpenCL C < 3.0. |
| 902 | // These specific extensions were implemented in Clang differently than other extensions - |
| 903 | // they require both the extension define AND corresponding feature macros to be enabled. |
| 904 | // For OpenCL C 3.0, the runtime automatically handles feature macros, but for older versions, |
| 905 | // IGC must manually enable the corresponding feature macros when these extensions are enabled. |
| 906 | struct ExtensionsRequiringManualFeatureMacros { |
| 907 | // Extensions that generate their own feature macros |
| 908 | bool integerDotProduct = false; // cl_khr_integer_dot_product |
| 909 | bool extFloatAtomics = false; // cl_ext_float_atomics |
| 910 | |
| 911 | // Dependency flags - control which macros are enabled |
| 912 | bool fp16 = false; // cl_khr_fp16 (dependency for atomic macros) |
| 913 | bool fp64 = false; // cl_khr_fp64 (dependency for atomic macros) |
| 914 | }; |
| 915 | |
| 916 | std::string GetFeatureMacrosForExtensions(const ExtensionsRequiringManualFeatureMacros &enabledExtensions, |
| 917 | unsigned int oclStd) { |
| 918 | // For OpenCL C versions older than 3.0, manually enable feature macros for specific extensions |
| 919 | std::string featureMacros; |
| 920 | |
| 921 | IGC_ASSERT_MESSAGE(oclStd < 300, "This function should only be called for OpenCL C versions older than 3.0"); |
| 922 | |
| 923 | // Integer dot product macros (OpenCL C 1.2+) |
| 924 | if (enabledExtensions.integerDotProduct && oclStd >= 120) { |
| 925 | featureMacros += " -D__opencl_c_integer_dot_product_input_4x8bit_packed"; |
| 926 | featureMacros += " -D__opencl_c_integer_dot_product_input_4x8bit"; |
| 927 | } |
| 928 | |
| 929 | // Float atomics macros (OpenCL C 2.0+) |
| 930 | if (enabledExtensions.extFloatAtomics && oclStd >= 200) { |
| 931 | if (enabledExtensions.fp16) { |
| 932 | featureMacros += " -D__opencl_c_ext_fp16_global_atomic_load_store"; |
| 933 | featureMacros += " -D__opencl_c_ext_fp16_local_atomic_load_store"; |
| 934 | featureMacros += " -D__opencl_c_ext_fp16_global_atomic_add"; |
| 935 | featureMacros += " -D__opencl_c_ext_fp16_local_atomic_add"; |
| 936 | featureMacros += " -D__opencl_c_ext_fp16_global_atomic_min_max"; |
| 937 | featureMacros += " -D__opencl_c_ext_fp16_local_atomic_min_max"; |
| 938 | } |
| 939 | if (enabledExtensions.fp64) { |
| 940 | featureMacros += " -D__opencl_c_ext_fp64_global_atomic_add"; |
| 941 | featureMacros += " -D__opencl_c_ext_fp64_local_atomic_add"; |
| 942 | featureMacros += " -D__opencl_c_ext_fp64_global_atomic_min_max"; |
| 943 | featureMacros += " -D__opencl_c_ext_fp64_local_atomic_min_max"; |
| 944 | } |
| 945 | // FP32 atomics (always available with cl_ext_float_atomics) |
| 946 | featureMacros += " -D__opencl_c_ext_fp32_global_atomic_add"; |
| 947 | featureMacros += " -D__opencl_c_ext_fp32_local_atomic_add"; |
| 948 | featureMacros += " -D__opencl_c_ext_fp32_global_atomic_min_max"; |
| 949 | featureMacros += " -D__opencl_c_ext_fp32_local_atomic_min_max"; |
| 950 | } |
| 951 | |
| 952 | return featureMacros; |
| 953 | } |
| 954 | |
| 955 | // The expected extensions input string is in a form: |
| 956 | // -cl-ext=-all,+supported_ext_name,+second_supported_ext_name |
| 957 | // -cl-feature=+__opencl_c_3d_image_writes,+__opencl_c_atomic_order_acq_rel |
| 958 | std::string GetCDefinesForEnableList(llvm::StringRef enableListStr, unsigned int oclStd, const StringRef prefix) { |
| 959 | |
| 960 | std::string definesStr; |
| 961 | |
| 962 | // check for the last occurence of prefix, as it invalidates previous occurances. |
| 963 | size_t pos = enableListStr.rfind(prefix); |
| 964 | if (pos == llvm::StringRef::npos) { |
| 965 | // If this string does not exist the input string does not contain valid extension list |
| 966 | // or it has all extensions disabled (-all without colon afterwards). |
| 967 | return definesStr; |
| 968 | } |
| 969 | |
| 970 | enableListStr = enableListStr.substr(pos + prefix.size()); |
| 971 | |
| 972 | // string with defines should be similar in size, ",+" will change to "-D". |
| 973 | definesStr.reserve(enableListStr.size()); |
| 974 | |
| 975 | llvm::SmallVector<StringRef, 0> v; |
| 976 | enableListStr.split(v, ','); |
| 977 | |
| 978 | ExtensionsRequiringManualFeatureMacros enabledExtensions; |
| 979 | for (auto ext : v) { |
| 980 | if (ext.consume_front("+")) { |
| 981 | if (ext.equals("cl_intel_device_side_avc_motion_estimation")) { |
| 982 | // If the user provided -cl-std option we need to add the define only if it's 1.2 and above. |
| 983 | // This is because clang will not allow declarations of extension's functions which use avc types otherwise. |
| 984 | if (!(oclStd >= 120 || oclStd == 0)) |
| 985 | continue; |
| 986 | } |
| 987 | |
| 988 | // Only collect extensions needed for manual feature macro generation |
| 989 | if (ext.equals("cl_khr_integer_dot_product")) { |
| 990 | enabledExtensions.integerDotProduct = true; |
| 991 | } else if (ext.equals("cl_ext_float_atomics")) { |
| 992 | enabledExtensions.extFloatAtomics = true; |
| 993 | } else if (ext.equals("cl_khr_fp16")) { |
| 994 | enabledExtensions.fp16 = true; |
| 995 | } else if (ext.equals("cl_khr_fp64")) { |
| 996 | enabledExtensions.fp64 = true; |
| 997 | } |
| 998 | |
| 999 | definesStr.append(" -D").append(ext.str()); |
| 1000 | } |
| 1001 | } |
| 1002 | |
| 1003 | // For OpenCL C versions older than 3.0, manually enable feature macros for specific extensions. |
| 1004 | // This is required because some extensions (like cl_khr_integer_dot_product) were implemented |
| 1005 | // in Clang to require both the extension define AND corresponding feature macros to be enabled. |
| 1006 | // In OpenCL C 3.0, the runtime automatically handles feature macros, but for older versions, |
| 1007 | // the runtime (NEO UMD) doesn't pass these feature macros, so IGC must enable them manually |
| 1008 | // when the corresponding extension is enabled. |
| 1009 | if (oclStd < 300) { |
| 1010 | definesStr += GetFeatureMacrosForExtensions(enabledExtensions, oclStd); |
| 1011 | } |
| 1012 | |
| 1013 | return definesStr; |
| 1014 | } |
| 1015 | |
| 1016 | /*****************************************************************************\ |
| 1017 | |
| 1018 | Function: |
| 1019 | CClangTranslationBlock::EnsureProperPCH |
| 1020 | |
| 1021 | Description: |
| 1022 | Ensures that the given TranslateClang arguments has the proper CTH and PCH |
| 1023 | headers specified |
| 1024 | |
| 1025 | Input: |
| 1026 | |
| 1027 | Output: |
| 1028 | |
| 1029 | \*****************************************************************************/ |
| 1030 | void CClangTranslationBlock::EnsureProperPCH(TranslateClangArgs *pArgs, const char *pInternalOptions, |
| 1031 | std::string &exceptString) { |
| 1032 | unsigned long CTHeaderSize = 0; |
| 1033 | m_cthBuffer = llvm::LoadCharBufferFromResource(IDR_CTH_H, "H", CTHeaderSize); |
| 1034 | IGC_ASSERT_MESSAGE(m_cthBuffer, "Error loading Opencl_cth.h"); |
| 1035 | |
| 1036 | if (m_cthBuffer) { |
| 1037 | // Process the CT Header |
| 1038 | IGC_ASSERT_MESSAGE(CTHeaderSize > 0, "Resource for the CT Header is empty"); |
| 1039 | IGC_ASSERT_MESSAGE(m_cthBuffer[CTHeaderSize - 1] == '\0', "Resource for the CT Header is not null terminated"); |
| 1040 | |
| 1041 | pArgs->inputHeaders.push_back(m_cthBuffer); |
| 1042 | pArgs->inputHeadersNames.push_back("CTHeader.h"); |
| 1043 | pArgs->optionsEx.append(" -include CTHeader.h"); |
| 1044 | } |
| 1045 | } |
| 1046 | |
| 1047 | /**********************************************************************\ |
| 1048 | |
| 1049 | Function: |
| 1050 | GetParam |
| 1051 | |
| 1052 | Description: |
| 1053 | takes first parameter from Head |
| 1054 | and assigns the rest of parameters to Tail |
| 1055 | Head : input string with list / output with head |
| 1056 | Tail : output string |
| 1057 | |
| 1058 | returns Head or NULL if Head is empty |
| 1059 | |
| 1060 | \**********************************************************************/ |
| 1061 | char *GetParam(char *Head, char *Tail) { |
| 1062 | static char Delim = ' '; |
| 1063 | static char Slash = '\\'; |
| 1064 | char QuoteDouble = 0; |
| 1065 | char QuoteSingle = 0; |
| 1066 | char PrevChar = 0; |
| 1067 | char *Pos = NULL; |
| 1068 | int Length = 0; |
| 1069 | |
| 1070 | if (Head == NULL) { |
| 1071 | *Tail = 0; |
| 1072 | goto ERROR_HANDLER; |
| 1073 | } |
| 1074 | |
| 1075 | QuoteDouble = Delim; |
| 1076 | QuoteSingle = Delim; |
| 1077 | Pos = Head; |
| 1078 | Length = (int)std::string(Head).length(); |
| 1079 | |
| 1080 | while (*Pos == Delim) { |
| 1081 | Pos++; |
| 1082 | Length--; |
| 1083 | } |
| 1084 | if (*Pos == 0) { |
| 1085 | *Tail = 0; |
| 1086 | Head = NULL; |
| 1087 | goto ERROR_HANDLER; |
| 1088 | } |
| 1089 | |
| 1090 | switch (*Pos) { |
| 1091 | case '\"': |
| 1092 | QuoteDouble = *Pos; |
| 1093 | break; |
| 1094 | case '\'': |
| 1095 | QuoteSingle = *Pos; |
| 1096 | break; |
| 1097 | default: |
| 1098 | break; |
| 1099 | } |
| 1100 | |
| 1101 | do { |
| 1102 | PrevChar = *Pos; |
| 1103 | Pos++; |
| 1104 | Length--; |
| 1105 | switch (*Pos) { |
| 1106 | case '\"': |
| 1107 | if (PrevChar != Slash) { |
| 1108 | if (QuoteDouble == Delim) { |
| 1109 | QuoteDouble = *Pos; // Open quote string |
| 1110 | } else { |
| 1111 | QuoteDouble = Delim; // Close quote string |
| 1112 | } |
| 1113 | } |
| 1114 | break; |
| 1115 | case '\'': |
| 1116 | if (PrevChar != Slash) { |
| 1117 | if (QuoteSingle == Delim) { |
| 1118 | QuoteSingle = *Pos; // Open quote string |
| 1119 | } else { |
| 1120 | QuoteSingle = Delim; // Close quote string |
| 1121 | } |
| 1122 | } |
| 1123 | break; |
| 1124 | default: |
| 1125 | break; |
| 1126 | } |
| 1127 | } while ((*Pos != 0) && ((*Pos != Delim) || ((*Pos == Delim) && ((QuoteDouble != Delim) || (QuoteSingle != Delim))))); |
| 1128 | if (*Pos == Delim) { |
| 1129 | *Pos = 0; // finish Head |
| 1130 | Pos++; // skip zero |
| 1131 | while (*Pos == Delim) { |
| 1132 | Pos++; // skip multiple delimiters |
| 1133 | Length--; |
| 1134 | } |
| 1135 | if (*Pos != 0) { |
| 1136 | strcpy_s(Tail, Length, Pos); // Assign the rest of params to Tail |
| 1137 | } else { |
| 1138 | *Tail = 0; |
| 1139 | } |
| 1140 | } else { |
| 1141 | *Tail = 0; |
| 1142 | } |
| 1143 | |
| 1144 | while (*Head == Delim) { |
| 1145 | Head++; |
| 1146 | } |
| 1147 | |
| 1148 | ERROR_HANDLER: |
| 1149 | return Head; |
| 1150 | } |
| 1151 | |
| 1152 | /**********************************************************************\ |
| 1153 | |
| 1154 | Class Function: |
| 1155 | BuildOptionsAreValid |
| 1156 | |
| 1157 | Description: |
| 1158 | Walks through options and makes sure they're ok |
| 1159 | |
| 1160 | \**********************************************************************/ |
| 1161 | |
| 1162 | int BuildOptionsAreValid(const std::string &options, std::string &exceptString) { |
| 1163 | int retVal = 0; |
| 1164 | |
| 1165 | char *nextTok = NULL; |
| 1166 | char *pParam = NULL; |
| 1167 | char *pBuffer = NULL; |
| 1168 | bool ignoreNextToken = false; |
| 1169 | bool checkBinaryType = false; |
| 1170 | bool isCommonOption = false; |
| 1171 | |
| 1172 | if (!options.empty()) { |
| 1173 | size_t optionsSize = options.size() + 1; |
| 1174 | // alocate memory for pBuffer and nextTok |
| 1175 | pBuffer = new char[optionsSize]; |
| 1176 | nextTok = new char[optionsSize]; |
| 1177 | |
| 1178 | strncpy_s(pBuffer, optionsSize, options.c_str(), optionsSize); |
| 1179 | pParam = GetParam(pBuffer, nextTok); |
| 1180 | |
| 1181 | if (pParam) { |
| 1182 | do { |
| 1183 | if (checkBinaryType) { |
| 1184 | // If "spir" does not follow the -x option, we must fail |
| 1185 | if ((strcmp(pParam, "spir") && strcmp(pParam, "spir64"))) { |
| 1186 | // Invalid option - break out of the loop and return |
| 1187 | // CL_INVALID_BUILD_OPTIONS |
| 1188 | retVal = -43; |
| 1189 | std::string invalidOption(pParam); |
| 1190 | |
| 1191 | exceptString += "\nUnrecognized build options: " + invalidOption; |
| 1192 | break; |
| 1193 | } |
| 1194 | |
| 1195 | // reset |
| 1196 | checkBinaryType = false; |
| 1197 | } else if (ignoreNextToken == false) { |
| 1198 | // Check for common Intel OpenCL CPU/GPU options |
| 1199 | isCommonOption = |
| 1200 | (strcmp(pParam, "-cl-single-precision-constant") == 0) || (strcmp(pParam, "-cl-denorms-are-zero") == 0) || |
| 1201 | (strcmp(pParam, "-cl-fp32-correctly-rounded-divide-sqrt") == 0) || |
| 1202 | (strcmp(pParam, "-cl-opt-disable") == 0) || (strcmp(pParam, "-ze-opt-disable") == 0) || |
| 1203 | (strcmp(pParam, "-cl-strict-aliasing") == 0) || (strcmp(pParam, "-cl-mad-enable") == 0) || |
| 1204 | (strcmp(pParam, "-cl-no-signed-zeros") == 0) || (strcmp(pParam, "-cl-unsafe-math-optimizations") == 0) || |
| 1205 | (strcmp(pParam, "-cl-finite-math-only") == 0) || (strcmp(pParam, "-cl-fast-relaxed-math") == 0) || |
| 1206 | (strcmp(pParam, "-cl-match-sincospi") == 0) || (strcmp(pParam, "-w") == 0) || |
| 1207 | (strcmp(pParam, "-Werror") == 0) || (strcmp(pParam, "-cl-std=CL1.1") == 0) || |
| 1208 | (strcmp(pParam, "-cl-std=CL1.2") == 0) || (strcmp(pParam, "-cl-std=CL2.0") == 0) || |
| 1209 | (strcmp(pParam, "-cl-std=CL2.1") == 0) || (strcmp(pParam, "-cl-std=CL3.0") == 0) || |
| 1210 | (strcmp(pParam, "-cl-uniform-work-group-size") == 0) || // it's work only for OCL version greater than 1.2 |
| 1211 | (strcmp(pParam, "-cl-kernel-arg-info") == 0) || (strncmp(pParam, "-x", 2) == 0) || |
| 1212 | (strncmp(pParam, "-D", 2) == 0) || (strncmp(pParam, "-I", 2) == 0) || |
| 1213 | (strncmp(pParam, "-spir-std=", 10) == 0) || (strcmp(pParam, "-gline-tables-only") == 0) || |
| 1214 | (strcmp(pParam, "-triple") == 0) || // used in NEO |
| 1215 | (strcmp(pParam, "-dwarf-column-info") == 0) || |
| 1216 | (strcmp(pParam, "-cl-intel-no-prera-scheduling") == 0) || // temporary options |
| 1217 | (strcmp(pParam, "-igc_opts") == 0) || // temporary options |
| 1218 | (strcmp(pParam, "-cl-intel-gtpin-rera") == 0) || // temporary options |
| 1219 | (strcmp(pParam, "-cl-intel-256-GRF-per-thread") == 0) || // temporary options |
| 1220 | (strcmp(pParam, "-ze-opt-256-GRF-per-thread") == 0) || // temporary options |
| 1221 | (strcmp(pParam, "-cl-intel-512-GRF-per-thread") == 0) || // temporary options |
| 1222 | (strcmp(pParam, "-ze-opt-512-GRF-per-thread") == 0) || // temporary options |
| 1223 | (strcmp(pParam, "-ze-exp-register-file-size") == 0) || // temporary options |
| 1224 | (strcmp(pParam, "-ze-opt-large-register-file") == 0) || // temporary options |
| 1225 | (strcmp(pParam, "-cl-intel-large-grf-kernel") == 0) || |
| 1226 | (strcmp(pParam, "-ze-opt-large-grf-kernel") == 0) || |
| 1227 | (strcmp(pParam, "-cl-intel-regular-grf-kernel") == 0) || |
| 1228 | (strcmp(pParam, "-ze-opt-regular-grf-kernel") == 0) || |
| 1229 | (strcmp(pParam, "-ze-opt-disable-recompilation") == 0) || // temporary options |
| 1230 | (strcmp(pParam, "-cl-intel-num-thread-per-eu") == 0) || // temporary options |
| 1231 | (strncmp(pParam, "-cl-intel-reqd-eu-thread-count", 30) == 0) || |
| 1232 | (strcmp(pParam, "-cl-replace-global-offsets-by-zero") == 0) || // temporary options |
| 1233 | (strcmp(pParam, "-cl-kernel-debug-enable") == 0) || // temporary options |
| 1234 | (strcmp(pParam, "-cl-include-sip-csr") == 0) || // temporary options |
| 1235 | (strcmp(pParam, "-cl-include-sip-kernel-debug") == 0) || // temporary options |
| 1236 | (strcmp(pParam, "-cl-include-sip-kernel-local-debug") == 0) || // temporary options |
| 1237 | (strcmp(pParam, "-cl-intel-use-32bit-ptr-arith") == 0) || // temporary options |
| 1238 | (strcmp(pParam, "-cl-intel-force-disable-4GB-buffer") == 0) || // temporary options |
| 1239 | (strcmp(pParam, "-cl-intel-greater-than-4GB-buffer-required") == 0) || // temporary options |
| 1240 | (strcmp(pParam, "-ze-opt-greater-than-4GB-buffer-required") == 0) || // temporary options |
| 1241 | (strcmp(pParam, "-cl-intel-has-buffer-offset-arg") == 0) || // temporary options |
| 1242 | (strcmp(pParam, "-ze-opt-has-buffer-offset-arg") == 0) || // temporary options |
| 1243 | (strcmp(pParam, "-cl-intel-buffer-offset-arg-required") == 0) || // temporary options |
| 1244 | (strcmp(pParam, "-ze-opt-buffer-offset-arg-required") == 0) || // temporary options |
| 1245 | (strcmp(pParam, "-cl-force-global-mem-allocation") == 0) || // temp |
| 1246 | (strcmp(pParam, "-ze-force-global-mem-allocation") == 0) || // temp |
| 1247 | (strcmp(pParam, "-cl-no-local-to-generic") == 0) || // temp |
| 1248 | (strcmp(pParam, "-ze-no-local-to-generic") == 0) || // temp |
| 1249 | (strcmp(pParam, "-cl-intel-debug-info") == 0) || (strncmp(pParam, "-dump-opt-llvm", 14) == 0) || |
| 1250 | (strcmp(pParam, "-cl-no-subgroup-ifp") == 0) || |
| 1251 | (strcmp(pParam, "-cl-intel-disable-a64WA") == 0) || // temporary options |
| 1252 | (strcmp(pParam, "-ze-gtpin-rera") == 0) || // used by GTPin |
| 1253 | (strcmp(pParam, "-ze-gtpin-grf-info") == 0) || // used by GTPin |
| 1254 | (strcmp(pParam, "-ze-gtpin-scratch-area-size") == 0) || // used by GTPin |
| 1255 | (strcmp(pParam, "-ze-opt-enable-auto-large-GRF-mode") == 0) || |
| 1256 | (strcmp(pParam, "-cl-intel-enable-auto-large-GRF-mode") == 0) || (strcmp(pParam, "-ze-skip-fde") == 0) || |
| 1257 | (strcmp(pParam, "-ze-no-fusedCallWA") == 0) || (strcmp(pParam, "-ze-disable-compaction") == 0) || |
| 1258 | (strcmp(pParam, "-cl-poison-unsupported-fp64-kernels") == 0) || // used by fp64 poisoning |
| 1259 | (strcmp(pParam, "-ze-poison-unsupported-fp64-kernels") == 0) || // used by fp64 poisoning |
| 1260 | (strcmp(pParam, "-cl-fp64-gen-emu") == 0) || // used by fp64 emulation |
| 1261 | (strcmp(pParam, "-ze-fp64-gen-emu") == 0) || // used by fp64 emulation |
| 1262 | (strcmp(pParam, "-cl-fp64-gen-conv-emu") == 0) || // used by fp64 conversion emulation |
| 1263 | (strcmp(pParam, "-ze-fp64-gen-conv-emu") == 0) || // used by fp64 conversion emulation |
| 1264 | (strcmp(pParam, "-Xfinalizer") == 0) || // used to pass options to visa finalizer |
| 1265 | (strcmp(pParam, "-cl-intel-enable-ieee-float-exception-trap") == |
| 1266 | 0) || // used to enable IEEE float exception trap |
| 1267 | (strcmp(pParam, "-ze-intel-enable-ieee-float-exception-trap") == |
| 1268 | 0) || // used to enable IEEE float exception trap |
| 1269 | (strcmp(pParam, "-cl-intel-disable-sendwarwa") == 0) || |
| 1270 | (strcmp(pParam, "-ze-opt-disable-sendwarwa") == 0) || |
| 1271 | (strcmp(pParam, "-cl-intel-static-profile-guided-trimming") == |
| 1272 | 0) || // used to enable profile-guided trimming |
| 1273 | (strcmp(pParam, "-ze-opt-static-profile-guided-trimming") == 0); // used to enable profile-guided trimming |
| 1274 | |
| 1275 | if (isCommonOption) { |
| 1276 | // check to see if they used a space immediately after |
| 1277 | // the define/include. If they did... |
| 1278 | if ((strcmp(pParam, "-D") == 0) || (strcmp(pParam, "-I") == 0) || (strcmp(pParam, "-igc_opts") == 0)) { |
| 1279 | // ignore next token as it is the define/include |
| 1280 | ignoreNextToken = true; |
| 1281 | } else if (strcmp(pParam, "-x") == 0) { |
| 1282 | // we need to check the next parameter for "spir" |
| 1283 | checkBinaryType = true; |
| 1284 | } else if (strcmp(pParam, "-triple") == 0) { |
| 1285 | checkBinaryType = true; |
| 1286 | } else if (strcmp(pParam, "-cl-intel-num-thread-per-eu") == 0 || |
| 1287 | strcmp(pParam, "-cl-intel-reqd-eu-thread-count") == 0 || |
| 1288 | strcmp(pParam, "-ze-gtpin-scratch-area-size") == 0 || |
| 1289 | strcmp(pParam, "-ze-exp-register-file-size") == 0) { |
| 1290 | // Next token is N, so ignore it |
| 1291 | ignoreNextToken = true; |
| 1292 | } else if ((strcmp(pParam, "-cl-intel-large-grf-kernel") == 0) || |
| 1293 | (strcmp(pParam, "-ze-opt-large-grf-kernel") == 0) || |
| 1294 | (strcmp(pParam, "-cl-intel-regular-grf-kernel") == 0) || |
| 1295 | (strcmp(pParam, "-ze-opt-regular-grf-kernel") == 0)) { |
| 1296 | // Next token is kernel name substring, ignore it |
| 1297 | ignoreNextToken = true; |
| 1298 | } else if (strcmp(pParam, "-Xfinalizer") == 0) { |
| 1299 | // if -Xfinalizer is used, ignore next token as it is the option for visa |
| 1300 | ignoreNextToken = true; |
| 1301 | } |
| 1302 | } |
| 1303 | // Check for Intel OpenCL CPU options |
| 1304 | // OCL Kernel Profiler requires "-g" to create debug information for instrumented kernels. |
| 1305 | // Without those information OCL Profiler is unable to associate OpenC code with IL instructions. |
| 1306 | else if ((strcmp(pParam, "-g") == 0) || (strcmp(pParam, "-profiler") == 0) || |
| 1307 | (strncmp(pParam, "-s", 2) == 0)) { |
| 1308 | if (strcmp(pParam, "-s") == 0) { |
| 1309 | // ignore next token as it is the source path |
| 1310 | ignoreNextToken = true; |
| 1311 | } |
| 1312 | } else { |
| 1313 | // Invalid option - break out of the loop and return |
| 1314 | // CL_INVALID_BUILD_OPTIONS |
| 1315 | retVal = -43; |
| 1316 | std::string invalidOption(pParam); |
| 1317 | |
| 1318 | exceptString += "\nUnrecognized build options: " + invalidOption; |
| 1319 | break; |
| 1320 | } |
| 1321 | } else { |
| 1322 | ignoreNextToken = false; |
| 1323 | } |
| 1324 | strncpy_s(pBuffer, optionsSize, nextTok, optionsSize); |
| 1325 | } while ((pParam = GetParam(pBuffer, nextTok)) != NULL); |
| 1326 | } |
| 1327 | |
| 1328 | delete[] pBuffer; |
| 1329 | delete[] nextTok; |
| 1330 | } |
| 1331 | return retVal; |
| 1332 | } |
| 1333 | |
| 1334 | /*****************************************************************************\ |
| 1335 | |
| 1336 | Function: |
| 1337 | CClangTranslationBlock::TranslateClang |
| 1338 | |
| 1339 | Description: |
| 1340 | Translates from CL to LL/BC |
| 1341 | |
| 1342 | Input: |
| 1343 | |
| 1344 | Output: |
| 1345 | |
| 1346 | \*****************************************************************************/ |
| 1347 | bool CClangTranslationBlock::TranslateClang(const TranslateClangArgs *pInputArgs, STB_TranslateOutputArgs *pOutputArgs, |
| 1348 | std::string &exceptString, const char *pInternalOptions) { |
| 1349 | // additional clang options |
| 1350 | std::string optionsEx = pInputArgs->optionsEx; |
| 1351 | std::string options = pInputArgs->options; |
| 1352 | optionsEx.append(" -disable-llvm-optzns -fblocks -I. -D__ENABLE_GENERIC__=1"); |
| 1353 | |
| 1354 | switch (m_OutputFormat) { |
| 1355 | case TB_DATA_FORMAT_LLVM_TEXT: |
| 1356 | optionsEx += " -emit-llvm"; |
| 1357 | break; |
| 1358 | case TB_DATA_FORMAT_LLVM_BINARY: |
| 1359 | optionsEx += " -emit-llvm-bc"; |
| 1360 | break; |
| 1361 | case TB_DATA_FORMAT_SPIR_V: |
| 1362 | optionsEx += " -emit-spirv"; |
| 1363 | break; |
| 1364 | default: |
| 1365 | break; |
| 1366 | } |
| 1367 | |
| 1368 | if (AreVMETypesDefined()) { |
| 1369 | optionsEx += " -D__VME_TYPES_DEFINED__"; |
| 1370 | } |
| 1371 | |
| 1372 | if (options.find("-triple") == std::string::npos) { |
| 1373 | // if target triple not explicitly set |
| 1374 | if (pInputArgs->b32bit) { |
| 1375 | optionsEx += " -D__32bit__=1"; |
| 1376 | options += " -triple spir"; |
| 1377 | } else { |
| 1378 | options += " -triple spir64"; |
| 1379 | } |
| 1380 | } |
| 1381 | |
| 1382 | if (options.find("-gline-tables-only") != std::string::npos) { |
| 1383 | optionsEx += " -debug-info-kind=line-tables-only -dwarf-version=4"; |
| 1384 | } |
| 1385 | |
| 1386 | #if (LLVM_VERSION_MAJOR < 17 || defined(IGC_LLVM_TRUNK_REVISION)) && defined(IGC_DEBUG_VARIABLES) |
| 1387 | // Allow to dynamically switch from typed to opaque pointers on |
| 1388 | // LLVM < 17. Disabling opaque pointers dynamically is not possible. |
| 1389 | if (FCL_IGC_IS_FLAG_ENABLED(EnableOpaquePointersBackend)) { |
| 1390 | optionsEx += " -opaque-pointers"; |
| 1391 | } else { |
| 1392 | #endif |
| 1393 | optionsEx += " "; |
| 1394 | optionsEx += __IGC_OPAQUE_POINTERS_DEFAULT_ARG_CLANG; |
| 1395 | #if (LLVM_VERSION_MAJOR < 17 || defined(IGC_LLVM_TRUNK_REVISION)) && defined(IGC_DEBUG_VARIABLES) |
| 1396 | } |
| 1397 | #endif |
| 1398 | |
| 1399 | std::string extensionsFromInternalOptions = GetSubstring(pInternalOptions, "-cl-ext="); |
| 1400 | |
| 1401 | std::string extensions; |
| 1402 | |
| 1403 | // if extensions list is passed in via internal options, it will override the default ones. |
| 1404 | if (extensionsFromInternalOptions.size() != 0) { |
| 1405 | extensions = extensionsFromInternalOptions; |
| 1406 | } else { |
| 1407 | extensions = FormatExtensionsString(m_Extensions); |
| 1408 | } |
| 1409 | |
| 1410 | optionsEx += " " + extensions; |
| 1411 | |
| 1412 | unsigned int oclStd = |
| 1413 | GetOclCVersionFromOptions(pInputArgs->options.data(), nullptr, pInputArgs->oclVersion, exceptString); |
| 1414 | |
| 1415 | // Undefine Clang's SPIR/SPIRV macros to prevent automatic extension enablement. |
| 1416 | // According to the March 20th OpenCL tooling meeting, Clang's automatic extension |
| 1417 | // handling "is trying to do the right thing on a best effort basis, but should not |
| 1418 | // be treated as a reference solution, and in its current state appears to be broken |
| 1419 | // and doing more harm than good." The recommended solution is to handle all extension |
| 1420 | // and feature macro definitions manually. |
| 1421 | // By undefining __SPIR__ and __SPIRV__, we prevent Clang from automatically enabling extensions, |
| 1422 | // allowing us to explicitly control which extensions are enabled through manual defines. |
| 1423 | optionsEx += " -U__SPIR__"; |
| 1424 | optionsEx += " -U__SPIRV__"; |
| 1425 | |
| 1426 | // get additional -D flags from internal options |
| 1427 | optionsEx += " " + GetCDefinesFromInternalOptions(pInternalOptions); |
| 1428 | optionsEx += " " + GetCDefinesForEnableList(extensions, oclStd, "-cl-ext=-all,"); |
| 1429 | |
| 1430 | optionsEx += " -D__ENDIAN_LITTLE__"; |
| 1431 | |
| 1432 | optionsEx += " -D__LLVM_VERSION_MAJOR__=" + to_string(LLVM_VERSION_MAJOR); |
| 1433 | |
| 1434 | // Workaround for Clang issue. |
| 1435 | // Clang always defines __IMAGE_SUPPORT__ macro for SPIR target, even if device doesn't support it. |
| 1436 | if (optionsEx.find("__IMAGE_SUPPORT__") == std::string::npos) { |
| 1437 | optionsEx += " -U__IMAGE_SUPPORT__"; |
| 1438 | } |
| 1439 | |
| 1440 | // TODO: Workaround - remove after some time to be consistent with LLVM15+ behavior |
| 1441 | optionsEx += " -Wno-error=implicit-int"; |
| 1442 | |
| 1443 | // Pass the list of supported SPIR-V extensions from IGC to opencl-clang. |
| 1444 | // This allows opencl-clang to enable only relevant extensions when compiling |
| 1445 | // OpenCL C to SPIR-V instead of enabling all extensions by default, and |
| 1446 | // prevents generating SPIR-V that uses extensions not supported by IGC. |
| 1447 | const auto &Extensions = IGC::SPIRVExtensionsSupport::AllExtensions; |
| 1448 | if (!Extensions.empty()) { |
| 1449 | optionsEx += " --spirv-ext="; |
| 1450 | |
| 1451 | auto it = Extensions.begin(); |
| 1452 | optionsEx += "+" + it->Name; |
| 1453 | |
| 1454 | for (++it; it != Extensions.end(); ++it) { |
| 1455 | optionsEx += ",+" + it->Name; |
| 1456 | } |
| 1457 | } |
| 1458 | |
| 1459 | IOCLFEBinaryResult *pResultPtr = NULL; |
| 1460 | int res = 0; |
| 1461 | { |
| 1462 | #ifdef _WIN32 |
| 1463 | res = m_CCModule.pCompile( |
| 1464 | #else |
| 1465 | res = Compile( |
| 1466 | #endif |
| 1467 | pInputArgs->pszProgramSource, (const char **)pInputArgs->inputHeaders.data(), |
| 1468 | (unsigned int)pInputArgs->inputHeaders.size(), (const char **)pInputArgs->inputHeadersNames.data(), NULL, 0, |
| 1469 | options.c_str(), optionsEx.c_str(), pInputArgs->oclVersion.c_str(), &pResultPtr); |
| 1470 | } |
| 1471 | if (0 != BuildOptionsAreValid(options, exceptString)) |
| 1472 | res = -43; |
| 1473 | |
| 1474 | Utils::FillOutputArgs(pResultPtr, pOutputArgs, exceptString); |
| 1475 | if (!exceptString.empty()) // str != "" => there was an exception. skip further code and return. |
| 1476 | { |
| 1477 | return false; |
| 1478 | } |
| 1479 | |
| 1480 | // if -dump-opt-llvm is enabled dump the llvm output to the file |
| 1481 | size_t dumpOptPosition = options.find("-dump-opt-llvm"); |
| 1482 | if ((0 == res) && dumpOptPosition != std::string::npos) { |
| 1483 | std::string dumpFileName; |
| 1484 | std::istringstream iss(options.substr(dumpOptPosition)); |
| 1485 | iss >> dumpFileName; |
| 1486 | size_t equalSignPosition = dumpFileName.find('='); |
| 1487 | if (equalSignPosition != std::string::npos) { |
| 1488 | dumpFileName = dumpFileName.substr(equalSignPosition + 1); |
| 1489 | // dump the archive |
| 1490 | FILE *file = fopen(dumpFileName.c_str(), "wb"); |
| 1491 | if (file != NULL) { |
| 1492 | fwrite(pOutputArgs->Output.data(), pOutputArgs->Output.size(), 1, file); |
| 1493 | fclose(file); |
| 1494 | } |
| 1495 | } else { |
| 1496 | SetErrorString("\nWarning: File name not specified with the -dump-opt-llvm option.\n", pOutputArgs); |
| 1497 | } |
| 1498 | } |
| 1499 | |
| 1500 | pResultPtr->Release(); |
| 1501 | |
| 1502 | return (0 == res); |
| 1503 | } |
| 1504 | |
| 1505 | /*****************************************************************************\ |
| 1506 | |
| 1507 | Function: |
| 1508 | CClangTranslationBlock::ReturnSuppliedIR |
| 1509 | |
| 1510 | Description: Extract the IR from the input arguments and supply it unmodified |
| 1511 | to the output |
| 1512 | |
| 1513 | Input: |
| 1514 | |
| 1515 | Output: |
| 1516 | |
| 1517 | \*****************************************************************************/ |
| 1518 | bool CClangTranslationBlock::ReturnSuppliedIR(const STB_TranslateInputArgs *pInputArgs, |
| 1519 | STB_TranslateOutputArgs *pOutputArgs) { |
| 1520 | bool success = true; |
| 1521 | |
| 1522 | pOutputArgs->ErrorString.clear(); |
| 1523 | pOutputArgs->Output.clear(); |
| 1524 | |
| 1525 | CElfReader *pElfReader = CElfReader::Create(pInputArgs->pInput, pInputArgs->InputSize); |
| 1526 | RAIIElf ElfObj(pElfReader); |
| 1527 | |
| 1528 | if (!pElfReader || !pElfReader->IsValidElf(pInputArgs->pInput, pInputArgs->InputSize)) { |
| 1529 | SetErrorString("Invalid input/output passed to library", pOutputArgs); |
| 1530 | return false; |
| 1531 | } |
| 1532 | |
| 1533 | const SElfHeader *pHeader = pElfReader->GetElfHeader(); |
| 1534 | IGC_ASSERT(pHeader != NULL); |
| 1535 | |
| 1536 | for (unsigned i = 1; i < pHeader->NumSectionHeaderEntries; i++) { |
| 1537 | const SElfSectionHeader *pSectionHeader = pElfReader->GetSectionHeader(i); |
| 1538 | IGC_ASSERT(pSectionHeader != NULL); |
| 1539 | if (pSectionHeader == NULL) { |
| 1540 | SetErrorString("No section header", pOutputArgs); |
| 1541 | return false; |
| 1542 | } |
| 1543 | |
| 1544 | if ((pSectionHeader->Type == SH_TYPE_OPENCL_LLVM_ARCHIVE) || (pSectionHeader->Type == SH_TYPE_OPENCL_LLVM_BINARY)) { |
| 1545 | char *pData = NULL; |
| 1546 | size_t dataSize = 0; |
| 1547 | const unsigned char *pBufStart; |
| 1548 | |
| 1549 | if (!pOutputArgs->Output.empty()) { |
| 1550 | SetErrorString("Multiple inputs passed to library", pOutputArgs); |
| 1551 | success = false; |
| 1552 | break; |
| 1553 | } |
| 1554 | |
| 1555 | pElfReader->GetSectionData(i, pData, dataSize); |
| 1556 | pBufStart = (const unsigned char *)pData; |
| 1557 | |
| 1558 | if (llvm::isBitcode(pBufStart, pBufStart + pHeader->ElfHeaderSize)) { |
| 1559 | pOutputArgs->Output.resize(dataSize); |
| 1560 | memcpy_s(pOutputArgs->Output.data(), dataSize, pBufStart, dataSize); |
| 1561 | } else { |
| 1562 | SetErrorString("Invalid input/output passed to library", pOutputArgs); |
| 1563 | success = false; |
| 1564 | break; |
| 1565 | } |
| 1566 | } |
| 1567 | } |
| 1568 | |
| 1569 | return success; |
| 1570 | } |
| 1571 | |
| 1572 | /// |
| 1573 | // Process the translation of ELF input type |
| 1574 | // |
| 1575 | bool CClangTranslationBlock::TranslateElf(const STB_TranslateInputArgs *pInputArgs, |
| 1576 | STB_TranslateOutputArgs *pOutputArgs, std::string &exceptString) { |
| 1577 | CElfReaderPtr pElfReader(CElfReader::Create(pInputArgs->pInput, pInputArgs->InputSize), ElfReaderDP); |
| 1578 | |
| 1579 | if (!pElfReader.get()) { |
| 1580 | SetErrorString("CElfReader::Create returned NULL\n", pOutputArgs); |
| 1581 | return false; |
| 1582 | } |
| 1583 | |
| 1584 | if (!pElfReader->IsValidElf(pInputArgs->pInput, pInputArgs->InputSize)) { |
| 1585 | // throw invalid_input_param ("Wrong ELF format"); |
| 1586 | exceptString = "Wrong ELF format"; |
| 1587 | return false; |
| 1588 | } |
| 1589 | // Elf is valid, so it is safe to access the header |
| 1590 | E_EH_TYPE ehType = *(const E_EH_TYPE *)&pElfReader->GetElfHeader()->Type; |
| 1591 | |
| 1592 | //{ { TB_DATA_FORMAT_ELF, TB_DATA_FORMAT_LLVM_BINARY } }, |
| 1593 | if (m_OutputFormat == TB_DATA_FORMAT_LLVM_BINARY || m_OutputFormat == TB_DATA_FORMAT_SPIR_V) { |
| 1594 | switch (ehType) { |
| 1595 | case EH_TYPE_OPENCL_SOURCE: { |
| 1596 | TranslateClangArgs args; |
| 1597 | GetTranslateClangArgs(pElfReader.get(), pInputArgs->pOptions, pInputArgs->pInternalOptions, &args, exceptString); |
| 1598 | bool success = TranslateClang(&args, pOutputArgs, exceptString, pInputArgs->pInternalOptions); |
| 1599 | if (exceptString.empty()) { |
| 1600 | return success; |
| 1601 | } else { |
| 1602 | return false; |
| 1603 | } |
| 1604 | } |
| 1605 | |
| 1606 | case EH_TYPE_OPENCL_OBJECTS: |
| 1607 | if (strstr(pInputArgs->pOptions, "-x spir") == NULL) { |
| 1608 | exceptString = "Unsupported ELF container"; |
| 1609 | return false; |
| 1610 | } |
| 1611 | |
| 1612 | return ReturnSuppliedIR(pInputArgs, pOutputArgs); |
| 1613 | |
| 1614 | default: |
| 1615 | exceptString = "Unsupported ELF header type"; |
| 1616 | return false; |
| 1617 | } |
| 1618 | } else { |
| 1619 | exceptString = "Unsupported output format"; |
| 1620 | } |
| 1621 | |
| 1622 | return false; |
| 1623 | } |
| 1624 | |
| 1625 | /*****************************************************************************\ |
| 1626 | |
| 1627 | Function: |
| 1628 | CClangTranslationBlock::Translate |
| 1629 | |
| 1630 | Description: |
| 1631 | |
| 1632 | Input: |
| 1633 | |
| 1634 | Output: |
| 1635 | |
| 1636 | \*****************************************************************************/ |
| 1637 | bool CClangTranslationBlock::Translate(const STB_TranslateInputArgs *pInputArgs, STB_TranslateOutputArgs *pOutputArgs) { |
| 1638 | // Setup a MutexGuard so that it's automatically released if it goes out of |
| 1639 | // scope |
| 1640 | // llvm::MutexGuard mutexGuard(m_Mutex); |
| 1641 | // resetOptionOccurrence(); |
| 1642 | |
| 1643 | std::string exceptString; |
| 1644 | switch (m_InputFormat) { |
| 1645 | // Processing the translations from OCL to LLVM |
| 1646 | //{{ TB_DATA_FORMAT_OCL_TEXT, TB_DATA_FORMAT_LLVM_TEXT }} , |
| 1647 | //{{ TB_DATA_FORMAT_OCL_TEXT, TB_DATA_FORMAT_LLVM_BINARY }}, |
| 1648 | case TB_DATA_FORMAT_OCL_TEXT: { |
| 1649 | TranslateClangArgs args; |
| 1650 | GetTranslateClangArgs(pInputArgs->pInput, pInputArgs->InputSize, pInputArgs->pOptions, pInputArgs->pInternalOptions, |
| 1651 | &args, exceptString); |
| 1652 | bool successTC = TranslateClang(&args, pOutputArgs, exceptString, pInputArgs->pInternalOptions); |
| 1653 | |
| 1654 | #if defined(IGC_DEBUG_VARIABLES) |
| 1655 | if (pInputArgs->pOptions != nullptr) { |
| 1656 | const std::string optionsWithFlags = pInputArgs->pOptions; |
| 1657 | std::size_t found = optionsWithFlags.find("-igc_opts"); |
| 1658 | if (found != std::string::npos) { |
| 1659 | std::size_t foundFirstSingleQuote = optionsWithFlags.find('\'', found); |
| 1660 | std::size_t foundSecondSingleQuote = optionsWithFlags.find('\'', foundFirstSingleQuote + 1); |
| 1661 | if (foundFirstSingleQuote != std::string::npos && foundSecondSingleQuote != std::string::npos) { |
| 1662 | FCL::RegKeysFlagsFromOptions = |
| 1663 | optionsWithFlags.substr(foundFirstSingleQuote + 1, foundSecondSingleQuote - foundFirstSingleQuote - 1); |
| 1664 | FCL::RegKeysFlagsFromOptions = FCL::RegKeysFlagsFromOptions + ','; |
| 1665 | } |
| 1666 | } |
| 1667 | } |
| 1668 | |
| 1669 | if (FCL_IGC_IS_FLAG_ENABLED(ShaderDumpEnable)) { |
| 1670 | // Works for all OSes. Creates dir if necessary. |
| 1671 | const char *pOutputFolder = FCL::GetShaderOutputFolder(); |
| 1672 | stringstream ss; |
| 1673 | const char *pBuffer = pInputArgs->pInput; |
| 1674 | UINT bufferSize = pInputArgs->InputSize; |
| 1675 | |
| 1676 | if (FCL_IGC_IS_FLAG_ENABLED(EnableKernelNamesBasedHash)) { |
| 1677 | // The spirv parser cannot be used here - we would have to include it in the Makefile |
| 1678 | // which is simply not worth it. Without it there's no good and reliable way to get |
| 1679 | // the kernel names for the hash generation, so the warning is to be emitted instead. |
| 1680 | pOutputArgs->ErrorString.append("warning: EnableKernelNamesBasedHash flag doesn't affect .cl dump's hash\n"); |
| 1681 | } |
| 1682 | |
| 1683 | // Create hash based on cclang binary output (currently llvm binary; later also spirv). |
| 1684 | // Hash computed in fcl needs to be same as the one computed in igc. |
| 1685 | // This is to ensure easy matching .cl files dumped in fcl with .ll/.dat/.asm/... files dumped in igc. |
| 1686 | QWORD hash = iSTD::Hash(reinterpret_cast<const DWORD *>(pOutputArgs->Output.data()), |
| 1687 | (DWORD)(pOutputArgs->Output.size()) / 4); |
| 1688 | |
| 1689 | ss << pOutputFolder; |
| 1690 | ss << "OCL_" |
| 1691 | << "asm" << std::hex << std::setfill('0') << std::setw(sizeof(hash) * CHAR_BIT / 4) << hash << std::dec |
| 1692 | << std::setfill(' ') << ".cl"; |
| 1693 | |
| 1694 | FILE *pFile = NULL; |
| 1695 | fopen_s(&pFile, ss.str().c_str(), "wb"); |
| 1696 | if (pFile) { |
| 1697 | fwrite(pBuffer, 1, bufferSize, pFile); |
| 1698 | fclose(pFile); |
| 1699 | } |
| 1700 | } |
| 1701 | #endif |
| 1702 | |
| 1703 | if (exceptString.empty()) { |
| 1704 | return successTC; |
| 1705 | } |
| 1706 | // else continue to process "catch" |
| 1707 | break; |
| 1708 | } |
| 1709 | // Processing the translations from ELF to LLVM |
| 1710 | //{ { TB_DATA_FORMAT_ELF, TB_DATA_FORMAT_LLVM_BINARY } }, |
| 1711 | case TB_DATA_FORMAT_ELF: { |
| 1712 | bool successTE = TranslateElf(pInputArgs, pOutputArgs, exceptString); |
| 1713 | if (exceptString.empty()) { |
| 1714 | return successTE; |
| 1715 | } |
| 1716 | // else continue to process exception |
| 1717 | break; |
| 1718 | } |
| 1719 | default: { |
| 1720 | exceptString = "Unsupported input format"; |
| 1721 | // continue to process exception |
| 1722 | } |
| 1723 | } |
| 1724 | |
| 1725 | // exceptString != "" => there was an exception. we get here only if there is an exception |
| 1726 | { |
| 1727 | if (exceptString.compare("bad_alloc") == 0) { |
| 1728 | SetErrorString("fcl: Allocation failure", pOutputArgs); |
| 1729 | return false; |
| 1730 | } else { |
| 1731 | SetErrorString(exceptString.c_str(), pOutputArgs); |
| 1732 | return false; |
| 1733 | } |
| 1734 | } |
| 1735 | } |
| 1736 | |
| 1737 | /*****************************************************************************\ |
| 1738 | |
| 1739 | Function: |
| 1740 | CClangTranslationBlock constructor |
| 1741 | |
| 1742 | Description: |
| 1743 | |
| 1744 | Input: |
| 1745 | |
| 1746 | Output: |
| 1747 | |
| 1748 | \*****************************************************************************/ |
| 1749 | CClangTranslationBlock::CClangTranslationBlock(void) : m_GlobalData() {} |
| 1750 | |
| 1751 | /*****************************************************************************\ |
| 1752 | |
| 1753 | Function: |
| 1754 | CClangTranslationBlock destructor |
| 1755 | |
| 1756 | Description: |
| 1757 | |
| 1758 | Input: |
| 1759 | |
| 1760 | Output: |
| 1761 | |
| 1762 | \*****************************************************************************/ |
| 1763 | CClangTranslationBlock::~CClangTranslationBlock(void) {} |
| 1764 | |
| 1765 | |
| 1766 | /*****************************************************************************\ |
| 1767 | |
| 1768 | Function: |
| 1769 | CClangTranslationBlock::Initialize |
| 1770 | |
| 1771 | Description: |
| 1772 | |
| 1773 | Input: |
| 1774 | |
| 1775 | Output: |
| 1776 | |
| 1777 | \*****************************************************************************/ |
| 1778 | bool CClangTranslationBlock::Initialize(const STB_CreateArgs *pCreateArgs) { |
| 1779 | if (pCreateArgs == NULL) { |
| 1780 | return false; |
| 1781 | } |
| 1782 | |
| 1783 | unsigned int i; |
| 1784 | for (i = 0; i < std::size(g_cClangTranslationCodes); i++) { |
| 1785 | // Some quick checks to ensure that the input and output types |
| 1786 | // are compatible with this translation blocks |
| 1787 | if ((pCreateArgs->TranslationCode.Type.Input == g_cClangTranslationCodes[i].Type.Input) && |
| 1788 | (pCreateArgs->TranslationCode.Type.Output == g_cClangTranslationCodes[i].Type.Output)) { |
| 1789 | break; |
| 1790 | } |
| 1791 | } |
| 1792 | |
| 1793 | if (i >= std::size(g_cClangTranslationCodes)) { |
| 1794 | return false; |
| 1795 | } |
| 1796 | |
| 1797 | // Find out what GPU platform the driver is running on |
| 1798 | if (pCreateArgs->pCreateData != nullptr) { |
| 1799 | } else { |
| 1800 | // assume m_OCL_Ver, etc. will be set-up later. |
| 1801 | SGlobalData globDataTmp = {0}; |
| 1802 | m_GlobalData = globDataTmp; |
| 1803 | m_HWPlatform = IGFX_UNKNOWN; |
| 1804 | m_CoreFamily = IGFX_UNKNOWN_CORE; |
| 1805 | m_OCL_Ver = "120"; |
| 1806 | } |
| 1807 | m_InputFormat = pCreateArgs->TranslationCode.Type.Input; |
| 1808 | m_OutputFormat = pCreateArgs->TranslationCode.Type.Output; |
| 1809 | |
| 1810 | return true; |
| 1811 | } |
| 1812 | } // namespace TC |